<?php
namespace App\Http\Controllers\Api\SystemsManage;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Api\Verify\SystemsManage\VerifyStoresController;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Crypt;
use App\Http\Models\Api\Common;
use App\Http\Controllers\Api\YongYou\YongYouController;
use App\Services\Shop\ShopService;

// 加盟店
class StoresController extends Controller
{
    // 列表每页显示数据个数
    protected $show_count = 10;

    // 列表
    public function index(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyStoresController;
        $error_message = $verify_data->indexValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        if ($user_info->shop_superior_id == 0) {
            $shop_id = $user_info->adm_shop_id;
        } else {
            $shop_id = $user_info->shop_superior_id;
        }

        $search_data = $request->all();
        $list_data = DB::table('shop')
                        ->where('shop_cid', $user_info->adm_cid)
                        ->where('shop_superior_id', $shop_id)
                        ->where('shop_type', 3)
                        ->where(function ($query) use ($search_data) {
                            if (!empty($search_data['shop_store_name'])) {
                                $query->where('shop_store_name', 'like', '%' . $search_data['shop_store_name'].'%');
                            }
                        })
                        ->where(function ($query) use ($search_data) {
                            if (!empty($search_data['shop_name'])) {
                                $query->where('shop_name', 'like', '%'.$search_data['shop_name'].'%');
                            }
                        })
                        ->where(function ($query) use ($search_data) {
                            if (!empty($search_data['shop_phone'])) {
                                $query->where('shop_phone', 'like', '%'.$search_data['shop_phone'].'%');
                            }
                        })
                        ->where(function ($query) use ($search_data) {
                            if (!empty($search_data['shop_address'])) {
                                $query->where('shop_address', 'like', '%' . $search_data['shop_address'].'%');
                            }
                        })
                        ->where(function ($query) use ($search_data) {
                            if (!empty($search_data['shop_state'])) {
                                $query->where('shop_state', $search_data['shop_state']);
                            }
                        })
                        ->select(
                            'shop_id',
                            'shop_store_name',
                            'shop_name',
                            'shop_phone',
                            'shop_province',
                            'shop_superior_id',
                            'shop_city',
                            'shop_county',
                            'shop_address',
                            'shop_state',
                            'shop_staff_number',
                            'shop_type'
                        )
                        ->orderBy('shop_id', 'desc')
                        ->paginate($this->show_count);
        $data_info['current_page'] = $list_data->currentPage();  //当前页面页码
        $data_info['last_page'] = $list_data->lastPage();        //表示最后一页的页码
        $data_info['total'] = $list_data->total();               //总数据个数
        $data_info['current_number'] = $this->show_count;       //一页显示多少个
        $data_info['data'] = $list_data->items();                //返回数据

        // 获取当前列表下的按钮
        $list_button = getListButton($request['api_token'], $request['pri_id']);
        if ($list_data) {
            return response()->json(['code'=> 200,'msg'=>'success','data'=>$data_info,'list_button'=>$list_button]);
        } else {
            return response()->json(['code'=> 500,'msg'=>'error','data'=>'暂无数据']);
        }
    }

    // 新增
    public function add(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyStoresController;
        $error_message = $verify_data->addValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);

        // 1. 判断加盟店名称是否存在
        $store_name = DB::table('shop')
            ->where('shop_cid', $user_info->adm_cid)
            ->where('shop_store_name', $request['shop_store_name'])
            ->first();
        if ($store_name) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'加盟店名称已存在']);
        }

        // 2. 判断手机号是否存在
        $adm_phone = DB::table('admin_shop_role')
            ->where('phone', $request['shop_phone'])
            ->where('shop_id', $user_info->adm_shop_id)
            ->first();
        if ($adm_phone) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前门店手机号已存在']);
        }else{
            $res = DB::table('admin_shop_role')
                ->where('phone', $request['shop_phone'])
                ->where('adm_shop_leave', 1)
                ->first();
            if(!empty($res)) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前手机号已是店长']);
            }
        }

        // 3. 新增加盟店
        DB::beginTransaction();

        // 3.1 门店表新增一个加盟店数据
        $shop_add_data = [
            'shop_cid'=>$user_info->adm_cid,
            'shop_superior_id'=>$user_info->adm_shop_id,
            'shop_store_name'=>$request['shop_store_name'],
            'shop_name'=>$request['shop_name'],
            'shop_phone'=>$request['shop_phone'],
            'shop_adm_id'=>0,
            'shop_province'=>$request['shop_province'],
            'shop_city'=>$request['shop_city'],
            'shop_county'=>$request['shop_county'],
            'shop_address'=>$request['shop_address'],
            'shop_type'=>3
        ];
        // 新增加盟店
        $shop_id =  DB::table('shop')->insertGetId($shop_add_data);
        ShopService::addFestival($shop_id);

        // 3.2 新增一个角色数据，店长的角色，店长角色的权限应该是固定的，新增店长账号需要有对应的角色
        $role_add_data = [
            'rol_cid'=>$user_info->adm_cid,
            'rol_shop_id'=>$shop_id,
            'rol_type'=>1,
            'rol_name'=>'总管理',
            'rol_privilege'=>config('apisystem.franchisee_shop'),
            'rol_creator_id'=>$user_info->adm_id
        ];
        // 新增角色
        $role_id =  DB::table('role')->insertGetId($role_add_data);

        // 3.3 账号表新增一个账号数据，账号类型为店长
        $adm_id= DB::table('admin')
            ->where('adm_phone', $request['shop_phone'])
            ->value('adm_id');
        if(empty($adm_id)) {
            $admin_add_data = [
                'adm_cid'=>$user_info->adm_cid,
                'adm_superior_shop_id'=>$user_info->adm_shop_id,
                'adm_shop_id'=>$shop_id,
                'adm_leave'=>1,
                'adm_phone'=>$request['shop_phone'],
                'adm_account'=>$request['adm_account'],
                'adm_password'=>md5($request['adm_password'].'faster123456'),
                'adm_name'=>$request['shop_name'],
                'adm_role'=>$role_id,
                'adm_creator_id'=>$user_info->adm_id,
            ];
            // 新增账号
            $adm_id =  DB::table('admin')->insertGetId($admin_add_data);
        }

        //新增账号门店权限关系表
        $insertAdminShopRoleData = [
            'adm_id' => $adm_id,
            'shop_cid' => $user_info->adm_cid,
            'superior_shop_id' => $user_info->adm_shop_id,
            'shop_id' => $shop_id,
            'role_id' => $role_id,
            'adm_shop_leave' => 1,
            'phone' => $request['shop_phone'],
            'create_time' => date("Y-m-d H:i:s", time()),
            'update_time' => date("Y-m-d H:i:s", time()),
        ];
        $admin_shop_role_id =  DB::table('admin_shop_role')->insertGetId($insertAdminShopRoleData);

        //添加加盟店默认仓库分类
        $warehouse_class = config('apisystem.warehouse_class');
        foreach ($warehouse_class as $key => $value) {
            $warehouse_class[$key]['wacl_cid'] = $user_info->adm_cid;
            $warehouse_class[$key]['wacl_superior_shop_id'] = $shop_id;
            $warehouse_class[$key]['wacl_shop_id'] = $shop_id;
        }
        $class_res = DB::table('warehouse_class')->insert($warehouse_class);
        // 3.4 将新增的账号id更新到门店表的 shop_adm_id 字段
        $shop_save_res = DB::table('shop')->where('shop_id', $shop_id)->update(['shop_adm_id' => $adm_id]);

        // 新增单位类型
        $chty_add_data['chty_cid'] = $user_info->adm_cid;
        $chty_add_data['chty_superior_shop_id'] = $shop_id;
        $chty_add_data['chty_shop_id'] = $shop_id;
        $chty_add_data['chty_name'] = '供应商';//单位类型名称
        $chty_add_data['chty_state'] = 1;
        $chty_add_data['chty_system_type'] = 1;//系统类型1系统2门店
        $chty_id = DB::table('channel_type')->insertGetId($chty_add_data);

        // 新增客户单位
        $chin_data[0]['key'] = '张国锋';//联系人
        $chin_data[0]['value'] = '18810207681';//联系电话
        $chin_data[0]['default'] = '1';
        if ($chin_data[0]['default'] == '1') {
            $chun_add_data['chun_name'] = $chin_data[0]['key'];
            $chun_add_data['chun_phone'] = $chin_data[0]['value'];
        }
        $chin_add_data['chin_data'] = json_encode($chin_data);
        $chun_add_data['chun_cid'] = $user_info->adm_cid;
        $chun_add_data['chun_superior_shop_id'] = $shop_id;
        $chun_add_data['chun_shop_id'] = $shop_id;
        $chun_add_data['chun_search_letter'] = 'SDKB';//检索字母
        $chun_add_data['chun_unit_name'] = '速电快保';//客户单位名称
        $chun_add_data['chun_chty_id'] = $chty_id;//渠道类型id
        $chun_add_data['chun_state'] = '1';//状态1.启用 2.停用3被合并/删除
        $chun_add_data['chun_payment_way'] = '1';//结算方式1.账期 2.现结
        $chun_add_data['chun_province'] = '北京市';//省
        $chun_add_data['chun_city'] = '市辖区';//市
        $chun_add_data['chun_county'] = '大兴区';//县
        $chun_add_data['chun_address'] = '亦庄经济技术开发区大族广场T3栋1205-09室';//经纬度
        $chun_add_data['chun_class'] = '2';//系统类型1自营2系统
        $chun_id = DB::table('channel_unit')->insertGetId($chun_add_data);
        // 新增客户单位信息表
        $chin_add_data['chin_chun_id'] = $chun_id;
        $chin_add_data['chin_level'] = 'A';//客户等级
        $chin_add_data['chin_type'] = '2';//铺货类型1是铺货2不是铺货
        $chin_add_data['chin_owe_day'] = '0';//可欠天数
        $chin_add_data['chin_owe_money'] = '0';//可欠金额
        $chin_add_data['chin_caution_day'] = '0';//警示天数
        $chin_add_data['chin_longitude'] = '116.513522';//经度
        $chin_add_data['chin_latitude'] = '39.791753';//维度
        $chin_id = DB::table('channel_info')->insert($chin_add_data);
        // 客户单位所属渠道类型更改
        $chty_save_type = DB::table('channel_type')
            ->where('chty_id', $chty_id)
            ->increment('chty_channel_number');

        // 加盟店设置
        $shse_data['shse_shop_id'] = $shop_id;
        $shse_data['shse_superior_shop_id'] = $user_info->adm_shop_id;
        $shse_data['shse_order_data'] = json_encode(config('apisystem.PRINT_SYSTEM'));
        $shse_res = DB::table('shop_set')->insert($shse_data);
        
        // 判断门店是否使用用友u8财务系统
        if (config('apiu8cloud.CODE_START') && in_array($user_info->adm_shop_id, config('apiu8cloud.u8cloud_shop'))) {
            // 调用u8系统接口，将客商数据传到用友系统上
            $yongyou = new YongYouController;
            // 客商基本档案新增
            $u8cloud_data['cbdocvo'][0]['parentvo']['creator'] = config('apiu8cloud.pk_prepared');//否  创建人
            $u8cloud_data['cbdocvo'][0]['parentvo']['custcode'] = config('apiu8cloud.custcode.assignment').$user_info->adm_shop_id.$shop_id;//是 客商编码
            $u8cloud_data['cbdocvo'][0]['parentvo']['custname'] =$request['shop_store_name'];//是 客商名称
            $u8cloud_data['cbdocvo'][0]['parentvo']['custprop'] ='0';//否 客商类型(0 - 外部单位,1 - 内部核算单位,2 - 内部法人单位,3 - 内部渠道成员)
            $u8cloud_data['cbdocvo'][0]['parentvo']['custshortname'] =$request['shop_store_name'];//是    客商简称
            $u8cloud_data['cbdocvo'][0]['parentvo']['pk_areacl'] =config('apiu8cloud.SHOP_BASIC_SETUP')[$user_info->adm_shop_id]['areaclcode'];//否   所属地区(填写编码)
            // 调用u8系统接口
            $curl_return = $yongyou->u8cloudApi('客商基本档案新增', $u8cloud_data);
            // 判断用友接口返回的数据
            if ($curl_return['status'] != 'success') {
                DB::rollBack();
                return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'U8财务系统添加客商失败！']);
            }
            // 客户数据添加成功，分配客商到门店
            $curl_data = json_decode($curl_return['data'], true);
            $chin_add_data['pk_cubasdoc'] = $curl_data[0]['parentvo']['pk_cubasdoc'];//客商基本档案主键--添加门店系统

            $custbasvo['custbasvo'][0]['pk_corp'] = config('apiu8cloud.SHOP_BASIC_SETUP')[$user_info->adm_shop_id]['pk_corp'];//公司主键
            $custbasvo['custbasvo'][0]['pk_cubasdoc'] =$curl_data[0]['parentvo']['pk_cubasdoc'];//客商基本档案主键
            $curl_return = $yongyou->u8cloudApi('客商基本档案分配', $custbasvo);
        }

        if ($shop_id && $role_id && $adm_id && $shop_save_res && $class_res && $shse_res && $chty_id && $chun_id && $chin_id && $chty_save_type && $admin_shop_role_id) {
            DB::commit();
            Common::addLog($user_info, getRealIp($request), '加盟店', '新增', '新增加盟店：'.$request['shop_store_name'].'成功');
            return response()->json(["code"=>200,'msg'=>'success','data'=>'新增加盟店成功']);
        } else {
            return response()->json(["code"=>500,'msg'=>'error','data'=>'新增加盟店失败']);
        }
    }

    // 编辑
    public function edit(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyStoresController;
        $error_message = $verify_data->editValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);

        // 1. 判断加盟店名称是否存在
        $store_name = DB::table('shop')
                        ->where('shop_cid', $user_info->adm_cid)
                        ->where('shop_id', '<>', $request['shop_id'])
                        ->where('shop_store_name', $request['shop_store_name'])
                        ->select('shop_store_name')
                        ->first();
        if ($store_name) {
            return response()->json(["code"=>500,'msg'=>'error','data'=>'加盟店名称已存在']);
        }

        // 2. 判断手机号是否存在
        $store_name = DB::table('shop')
                        ->where('shop_id', $request['shop_id'])
                        ->select('shop_store_name', 'shop_adm_id')
                        ->first();
        $adm_phone = DB::table('admin_shop_role')
                        ->where('phone', $request['shop_phone'])
                        ->where('shop_id', $user_info->adm_shop_id)
                        ->where('adm_id', '<>', $store_name->shop_adm_id)
                        ->select('adm_phone')
                        ->first();
        if ($adm_phone) {
            return response()->json(["code"=>500,'msg'=>'error','data'=>'手机号已存在']);
        }

        // 3 编辑加盟店信息
        DB::beginTransaction();

        // 3.1 门店表更改数据
        $shop_save_data = [
            'shop_store_name'=>$request['shop_store_name'],
            'shop_name'=>$request['shop_name'],
            'shop_phone'=>$request['shop_phone'],
            'shop_province'=>$request['shop_province'],
            'shop_city'=>$request['shop_city'],
            'shop_county'=>$request['shop_county'],
            'shop_address'=>$request['shop_address'],
            'shop_update_time'=>date('Y-m-d H:i:s'),
        ];
        $shop_save_res = DB::table('shop')->where('shop_id', $request['shop_id'])->update($shop_save_data);

        // 3.2 账号表更改数据
        $admin_save_data = [
            'adm_phone'=>$request['shop_phone'],
            'adm_name'=>$request['shop_name'],
            'adm_creator_id'=>$user_info->adm_id,
            'adm_update_time'=>date('Y-m-d H:i:s'),
        ];
        if ($request['adm_password']) {
            $admin_save_data['adm_password'] = md5($request['adm_password'].'faster123456');
        }
        $adm_save_res = DB::table('admin')->where('adm_id', $store_name->shop_adm_id)->update($admin_save_data);
        $adm_save_res1 = DB::table('admin_shop_role')->where('adm_id', $store_name->shop_adm_id)->where('shop_id',  $request['shop_id'])->update(['phone'=>$request['shop_phone']]);
        if ($shop_save_res && $adm_save_res && $adm_save_res1) {
            DB::commit();
            Common::addLog($user_info, getRealIp($request), '加盟店', '编辑', '编辑加盟店：'.$request['shop_store_name'].'成功');
            return response()->json(["code"=>200,'msg'=>'success','data'=>'编辑加盟店成功']);
        } else {
            return response()->json(["code"=>500,'msg'=>'error','data'=>'编辑加盟店失败']);
        }
    }

    // 启用
    public function start(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyStoresController;
        $error_message = $verify_data->startValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);

        // 查询加盟店信息
        $find_shop = DB::table('shop')
                    ->whereIn('shop_id', $request['shop_id'])
                    ->select('shop_store_name')
                    ->get();
        foreach ($find_shop as $key => $value) {
            $shop_store_name[] = $value->shop_store_name;
        }

        // 启用
        $update_data['shop_state'] = 1;//状态1启用2停用
        $update_data['shop_update_time'] = date('Y-m-d H:i:s');
        $shop_res = DB::table('shop')->whereIn('shop_id', $request['shop_id'])->update($update_data);

        if ($shop_res) {
            Common::addLog($user_info, getRealIp($request), '加盟店', '启用', '启用加盟店：（'.implode(',', $shop_store_name).'）启用成功');
            return response()->json(["code"=>200,'msg'=>'success','data'=>'启用成功']);
        } else {
            return response()->json(["code"=>500,'msg'=>'error','data'=>'启用失败']);
        }
    }

    // 停用
    public function stop(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyStoresController;
        $error_message = $verify_data->startValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        $shop_id = $request['shop_id'];
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        if ($user_info->shop_superior_id == 0) {
            // 总店id，判断要停用的数组中是否有总店id
            if (in_array($user_info->adm_shop_id, $shop_id)) {
                // 删除总店id
                $shop_key = array_search($user_info->adm_shop_id, $shop_id);
                unset($shop_id[$shop_key]);
            }
        }

        // 查询加盟店信息
        $find_shop = DB::table('shop')
                    ->whereIn('shop_id', $shop_id)
                    ->select('shop_store_name')
                    ->get();
        foreach ($find_shop as $key => $value) {
            $shop_store_name[] = $value->shop_store_name;
        }

        // 停用
        $update_data['shop_state'] = 2;//状态1启用2停用
        $update_data['shop_update_time'] = date('Y-m-d H:i:s');
        $shop_res = DB::table('shop')->whereIn('shop_id', $shop_id)->update($update_data);

        if ($shop_res) {
            Common::addLog($user_info, getRealIp($request), '加盟店', '停用', '停用加盟店：（'.implode(',', $shop_store_name).'）停用成功');
            return response()->json(["code"=>200,'msg'=>'success','data'=>'停用成功']);
        } else {
            return response()->json(["code"=>500,'msg'=>'error','data'=>'停用失败']);
        }
    }
}
