<?php

namespace App\Http\Controllers\Api\Store;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Crypt;
use App\Http\Models\Api\Common;
use App\Http\Controllers\Api\Verify\Store\VerifyStoreListController;
use App\Services\Shop\ShopService;

class StoreListController  extends Controller
{

    // 列表每页显示数据个数
    protected $show_count = 10;

    // 列表
    public function index(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyStoreListController;
        $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']);
        $search_data = $request->all();
        $list_data = DB::table('shop')
            ->where('shop_cid', $user_info->adm_cid)
            ->where('shop_parent_id', $user_info->adm_shop_id)
            ->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_image',
                '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',
                'shop_on_trial_start_time',
                'shop_on_trial_end_time',
                'shop_opening_start_time',
                'shop_opening_end_time',
                'shop_timelong',
                'shop_opening_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 VerifyStoreListController;
        $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'])
            ->value('shop_store_name');
        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)
            ->value('adm_id');
        if (!empty($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)
                ->value('adm_id');
            if(!empty($res)) {
                return response()->json(["code" => 500, 'msg' => 'error', 'data' => '当前手机号已是店长']);
            }
        }
        // 判断是否有新图片上传
        if (strpos($request['shop_image'], 'data:image') === 0) {
            // 调用全局函数 上传图片
            $image_path = uploadBase64ImgFolder($user_info->adm_shop_id,$request['shop_image']);
        } else {
            $image_path = '';
        }
        // 3. 新增门店
        DB::beginTransaction();
        DB::connection('mysql_scm')->beginTransaction();

        if ($request['shop_opening_type'] == 1) {//试用时间
            if (strlen($request['shop_on_trial_start_time']) > 13) {
                $start_time = $request['shop_on_trial_start_time'];
            } else {
                $start_time = $request['shop_on_trial_start_time'].':00:00';
            }
            $request['shop_on_trial_end_time'] = dateSomeMonthsLater($start_time, $request['shop_timelong']);
            $request['shop_opening_start_time'] = '0000-00-00 00:00:00';
            $request['shop_opening_end_time'] = '0000-00-00 00:00:00';
            $shor_add_data['shor_before_start_time'] = '0000-00-00 00:00:00';
            $shor_add_data['shor_before_end_time'] = '0000-00-00 00:00:00';
            $shor_add_data['shor_opening_type'] = $request['shop_opening_type'];  
            $shor_add_data['shor_after_end_time'] = $request['shop_on_trial_end_time'];
            $shor_add_data['shor_after_start_time'] = $request['shop_on_trial_start_time'];
        } else {//开通时间
            if (strlen($request['shop_opening_start_time']) > 13) {
                $start_time = $request['shop_opening_start_time'];
            } else {
                $start_time = $request['shop_opening_start_time'].':00:00';
            }
            $request['shop_opening_end_time'] = dateSomeMonthsLater($start_time, $request['shop_timelong']);
            $request['shop_on_trial_start_time'] = '0000-00-00 00:00:00';
            $request['shop_on_trial_end_time'] = '0000-00-00 00:00:00';
            $shor_add_data['shor_before_start_time'] = '0000-00-00 00:00:00';
            $shor_add_data['shor_before_end_time'] = '0000-00-00 00:00:00';
            $shor_add_data['shor_after_start_time'] = $request['shop_opening_start_time'];
            $shor_add_data['shor_after_end_time'] = $request['shop_opening_end_time'];
            $shor_add_data['shor_opening_type'] = $request['shop_opening_type'];
        }
        
        // 3.1 门店表新增一个门店数据
        $shop_add_data = [
            'shop_cid' => $user_info->adm_cid,
            'shop_superior_id' => 0,
            'shop_parent_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_versions' => 1, //默认基础版
            'shop_province' => $request['shop_province'],
            'shop_city' => $request['shop_city'],
            'shop_county' => $request['shop_county'],
            'shop_address' => $request['shop_address'],
            'shop_image' => $image_path,
            'shop_type' => 1,
            'shop_on_trial_start_time' => $request['shop_on_trial_start_time'],
            'shop_on_trial_end_time' => $request['shop_on_trial_end_time'],
            'shop_opening_start_time' => $request['shop_opening_start_time'],
            'shop_opening_end_time' => $request['shop_opening_end_time'],
            'shop_opening_type' => $request['shop_opening_type'],
            'shop_timelong' => $request['shop_timelong'],
        ];
        // 新增门店
        $shop_id =  DB::table('shop')->insertGetId($shop_add_data);
        ShopService::addFestival($shop_id);
        // 计算结束时间数据 添加修改记录
        $shor_add_data['shor_adm_id'] = $user_info->adm_id;
        $shor_add_data['shor_shop_id'] = $shop_id;
        $shor_add_data['shor_timelong'] = $request['shop_timelong'];
        $shor_add_data['shor_shop_store_name'] = $request['shop_store_name'];
        
        $chor_id = DB::table('shop_operation_record')->insertGetId($shor_add_data);
        //为门店添加服务
        $server_pro = config('apisystem.SERVER_PRO');
        $date = date('Y-m-d H:i:s');
        foreach ($server_pro as $k => $v) {
            $server_pro[$k]['sepr_cid'] = $user_info->adm_cid;
            $server_pro[$k]['sepr_shop_id'] = $shop_id;
            $server_pro[$k]['sepr_superior_shop_id'] = $shop_id;
            $server_pro[$k]['sepr_create_time'] = $date;
        }
        $service_project = DB::table('service_project')->insert($server_pro);

        // 新增门店设置
        $shse_add_data['shse_shop_id'] = $shop_id;
        $shse_add_data['shse_superior_shop_id'] = $shop_id;
        $shse_add_data['shse_replenishment_state'] = 2; //补货关系1开启2关闭
        $shse_add_data['shse_shop_state'] = 1; //门店功能1开启2关闭
        $shse_add_data['shse_brand'] = config('apisystem.SHSE_BRAND');
        $shse_add_data['shse_order_data'] = json_encode(config('apisystem.PRINT_SYSTEM'));
        $shse_id = DB::table('shop_set')->insertGetId($shse_add_data);

        // 新增单位类型
        $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);

        // 添加默认仓库分类
        $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);
       
        //查询系统品类商品数量
        $date = date('Y-m-d H:i:s');
        $cate_res = DB::table('goods')
            ->where('goo_shop_id', 0)
            ->groupBy('goo_cate_id')
            ->select('goo_cate_id', DB::raw('count(*) as num'))
            ->get();
        $caco_data = array();
        foreach ($cate_res as $cate_val) {
            $cate_data['caco_shop_id'] = $shop_id;
            $cate_data['caco_cate_id'] = $cate_val->goo_cate_id;
            $cate_data['caco_goods_number'] = $cate_val->num;
            $cate_data['caco_update_time'] = $date;
            $caco_data[] = $cate_data;
        }
        $caco_add = DB::table('category_correlation')->insert($caco_data);

        //查询系统品牌商品数量
        $brand_res = DB::table('goods')
            ->where('goo_shop_id', 0)
            ->groupBy('goo_bra_id')
            ->select('goo_bra_id', DB::raw('count(*) as num'))
            ->get();
        $brco_data = array();
        foreach ($brand_res as $bra_val) {
            $bra_data['brco_shop_id'] = $shop_id;
            $bra_data['brco_bra_id'] = $bra_val->goo_bra_id;
            $bra_data['brco_goods_number'] = $bra_val->num;
            $bra_data['brco_update_time'] = $date;
            $brco_data[] = $bra_data;
        }
        $brco_add = DB::table('brand_correlation')->insert($brco_data);

        //查询系统系列商品数量
        $brse_res = DB::table('goods')
            ->where('goo_shop_id', 0)
            ->groupBy('goo_brse_id')
            ->select('goo_brse_id', DB::raw('count(*) as num'))
            ->get();
        $seco_data = array();
        foreach ($brse_res as $brse_val) {
            $serie_data['brsc_shop_id'] = $shop_id;
            $serie_data['brsc_brse_id'] = $brse_val->goo_brse_id;
            $serie_data['brsc_goods_number'] = $brse_val->num;
            $serie_data['brsc_update_time'] = $date;
            $seco_data[] = $serie_data;
        }
        $seco_add = DB::table('brand_serie_correlation')->insert($seco_data);

        //向供应链后台添加数据
        $chan_add_data['chan_cid'] = $shop_add_data['shop_cid'];
        $chan_add_data['chan_shop_id'] = $shop_id;
        $chan_add_data['chan_account'] = $request['adm_account'];
        $chan_add_data['chan_unit_name'] = $shop_add_data['shop_store_name'];
        $chan_add_data['chan_name'] = $shop_add_data['shop_name'];
        $chan_add_data['chan_phone'] = $shop_add_data['shop_phone'];
        $chan_add_data['chan_province'] = $shop_add_data['shop_province'];
        $chan_add_data['chan_city'] = $shop_add_data['shop_city'];
        $chan_add_data['chan_county'] = $shop_add_data['shop_county'];
        $chan_add_data['chan_address'] = $shop_add_data['shop_address'];
        $chan_add_data['chan_versions'] = 1;
        $chan_add_data['chan_img_source'] = 1;//图片来源1门店2供应链
        $chan_add_data['chan_image'] = $image_path;
        $chan_add_data['chan_timelong'] = $shop_add_data['shop_timelong'];
        $chan_add_data['chan_opening_type'] = $shop_add_data['shop_opening_type'];
        $chan_add_data['chan_on_trial_start_time'] = $shop_add_data['shop_on_trial_start_time'];
        $chan_add_data['chan_on_trial_end_time'] = $shop_add_data['shop_on_trial_end_time'];
        $chan_add_data['chan_opening_start_time'] = $shop_add_data['shop_opening_start_time'];
        $chan_add_data['chan_opening_end_time'] = $shop_add_data['shop_opening_end_time'];
        $chan_id = DB::connection('mysql_scm')->table('channel')->insertGetId($chan_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');

        // 3.2 新增一个角色数据，店长的角色，店长角色的权限应该是固定的，新增店长账号需要有对应的角色
        //查询基础版权限
        $jur_where['jur_delete'] = 1;
        $jur_where['jur_state'] = 1;
        $jur_res = DB::connection('mysql_scm')->table('jurisdiction')->where($jur_where)->select('jur_privilege')->first();
        $role_add_data = [
            'rol_cid' => $user_info->adm_cid,
            'rol_shop_id' => $shop_id,
            'rol_type' => 1,
            'rol_name' => '总管理',
            'rol_privilege' => $jur_res->jur_privilege,
            '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' => $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' => $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);


        //新增银行卡
        $bankcard_add_data = [
            'acti_adm_id' => $user_info->adm_cid,
            'acti_shop_id' => $shop_id,
            'acti_shop_superior_id' => $shop_id,
            'acti_subject_code' => 1000000,
            'acti_course_title' => '默认账号',
            'acti_state' => 1,
            'acti_update_time' => date('Y-m-d H:i:s'),
        ];
        // 新增银行卡
        $acti_id =  DB::table('account_title')->insertGetId($bankcard_add_data);
        // 3.4 将新增的账号id更新到门店表的 shop_adm_id 字段
        $shop_save_res = DB::table('shop')->where('shop_id', $shop_id)->update(['shop_adm_id' => $adm_id]);
        if ($admin_shop_role_id && $caco_add && $caco_add && $seco_add && $chin_id && $shop_id && $role_id && $adm_id && $shop_save_res && $chan_id && $chty_save_type && $chun_id && $class_res && $chty_id && $shse_id && $service_project && $chor_id && $acti_id) {
            DB::commit();
            DB::connection('mysql_scm')->commit();
            Common::addLog($user_info, getRealIp($request), '城市运营中心', '新增', '门店基础版：' . $request['shop_store_name'] . '成功');
            return response()->json(["code" => 200, 'msg' => 'success', 'data' => '新增门店成功']);
        } else {
            DB::rollBack();
            DB::connection('mysql_scm')->rollBack();
            return response()->json(["code" => 500, 'msg' => 'error', 'data' => '新增门店失败']);
        }
    }

    // 编辑
    public function edit(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyStoreListController;
        $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', 'shop_on_trial_start_time', 'shop_on_trial_end_time', 'shop_opening_start_time', 'shop_opening_end_time', 'shop_adm_id')
            ->first();
        if ($store_name) {
            return response()->json(["code" => 500, 'msg' => 'error', 'data' => '门店名称已存在']);
        }
        $find_shop = DB::table('shop')
            ->where('shop_id', $request['shop_id'])
            ->select('shop_store_name', 'shop_on_trial_start_time', 'shop_on_trial_end_time', 'shop_opening_start_time', 'shop_opening_end_time', 'shop_adm_id')
            ->first();
        // 2. 判断手机号是否存在
        $adm_phone = DB::table('admin')
            ->where('adm_phone', $request['shop_phone'])
            ->where('adm_id', '<>', $find_shop->shop_adm_id)
            ->select('adm_phone')
            ->first();
        if ($adm_phone) {
            return response()->json(["code" => 500, 'msg' => 'error', 'data' => '手机号已存在']);
        }
        

        // 判断是否有新图片上传
        if (strpos($request['shop_image'], 'data:image') === 0) {
            // 调用全局函数 上传图片
            $image_path = uploadBase64ImgFolder($user_info->adm_shop_id,$request['shop_image']);
        } else {
            $image_path = $request['shop_image'];
        }
        // 3 编辑门店信息
        DB::beginTransaction();
        DB::connection('mysql_scm')->beginTransaction();

        if (!empty($request['shop_timelong'])) {
            // 计算结束时间数据 添加修改记录
            $shor_add_data['shor_adm_id'] = $user_info->adm_id;
            $shor_add_data['shor_shop_id'] = $request['shop_id'];
            $shor_add_data['shor_timelong'] = $request['shop_timelong'];
            $shor_add_data['shor_shop_store_name'] = $request['shop_store_name'];
            if ($request['shop_opening_type'] == 1) {//试用时间
                if (strlen($request['shop_on_trial_start_time']) > 13) {
                    $start_time = $request['shop_on_trial_start_time'];
                } else {
                    $start_time = $request['shop_on_trial_start_time'].':00:00';
                }
                $request['shop_on_trial_end_time'] = dateSomeMonthsLater($start_time, $request['shop_timelong']);
                $request['shop_opening_start_time'] = '0000-00-00 00:00:00';
                $request['shop_opening_end_time'] = '0000-00-00 00:00:00';
                $shor_add_data['shor_before_start_time'] = $find_shop->shop_on_trial_start_time;
                $shor_add_data['shor_before_end_time'] = $find_shop->shop_on_trial_end_time;
                $shor_add_data['shor_opening_type'] = $request['shop_opening_type'];  
                $shor_add_data['shor_after_end_time'] = $request['shop_on_trial_end_time'];
                $shor_add_data['shor_after_start_time'] = $request['shop_on_trial_start_time'];
            } else {//开通时间
                if (strlen($request['shop_opening_start_time']) > 13) {
                    $start_time = $request['shop_opening_start_time'];
                } else {
                    $start_time = $request['shop_opening_start_time'].':00:00';
                }
                $request['shop_opening_end_time'] = dateSomeMonthsLater($start_time, $request['shop_timelong']);
                $request['shop_on_trial_start_time'] = '0000-00-00 00:00:00';
                $request['shop_on_trial_end_time'] = '0000-00-00 00:00:00';
                $shor_add_data['shor_before_start_time'] = $find_shop->shop_opening_start_time;
                $shor_add_data['shor_before_end_time'] = $find_shop->shop_opening_end_time;
                $shor_add_data['shor_after_start_time'] = $request['shop_opening_start_time'];
                $shor_add_data['shor_after_end_time'] = $request['shop_opening_end_time'];
                $shor_add_data['shor_opening_type'] = $request['shop_opening_type'];
            }
            $chor_id = DB::table('shop_operation_record')->insertGetId($shor_add_data);
        } else {
            $chor_id = true;
        }
        
        // 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_image' => $image_path,
            'shop_on_trial_start_time' => $request['shop_on_trial_start_time'],
            'shop_on_trial_end_time' => $request['shop_on_trial_end_time'],
            'shop_opening_start_time' => $request['shop_opening_start_time'],
            'shop_opening_end_time' => $request['shop_opening_end_time'],
            'shop_opening_type' => $request['shop_opening_type'],
            'shop_timelong' => $request['shop_timelong'],
            '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);

        //向供应链后台添加数据
        $chan_edit_data['chan_unit_name'] = $shop_save_data['shop_store_name'];
        $chan_edit_data['chan_name'] = $shop_save_data['shop_name'];
        $chan_edit_data['chan_phone'] = $shop_save_data['shop_phone'];
        $chan_edit_data['chan_province'] = $shop_save_data['shop_province'];
        $chan_edit_data['chan_city'] = $shop_save_data['shop_city'];
        $chan_edit_data['chan_county'] = $shop_save_data['shop_county'];
        $chan_edit_data['chan_address'] = $shop_save_data['shop_address'];
        $chan_edit_data['chan_image'] = $image_path;
        $chan_edit_data['chan_on_trial_start_time'] = $shop_save_data['shop_on_trial_start_time'];
        $chan_edit_data['chan_on_trial_end_time'] = $shop_save_data['shop_on_trial_end_time'];
        $chan_edit_data['chan_opening_start_time'] = $shop_save_data['shop_opening_start_time'];
        $chan_edit_data['chan_opening_end_time'] = $shop_save_data['shop_opening_end_time'];
        $chan_edit_data['chan_timelong'] = $shop_save_data['shop_timelong'];
        $chan_edit_data['chan_opening_type'] = $shop_save_data['shop_opening_type'];
        $chan_edit_data['chan_update_time'] = date('Y-m-d H:i:s');
        $chan_edit_res = DB::connection('mysql_scm')->table('channel')->where('chan_shop_id', $request['shop_id'])->update($chan_edit_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', $find_shop->shop_adm_id)->update($admin_save_data);
        if ($shop_save_res && $adm_save_res && $chan_edit_res && $chor_id) {
            DB::commit();
            DB::connection('mysql_scm')->commit();
            Common::addLog($user_info, getRealIp($request), '城市运营中心', '编辑', '门店基础版：' . $request['shop_store_name'] . '成功');
            return response()->json(["code" => 200, 'msg' => 'success', 'data' => '编辑门店成功']);
        } else {
            DB::rollBack();
            DB::connection('mysql_scm')->rollBack();
            return response()->json(["code" => 500, 'msg' => 'error', 'data' => '编辑门店失败']);
        }
    }

    // 营业
    public function start(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyStoreListController;
        $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 VerifyStoreListController;
        $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']);

        $shop_id = $request['shop_id'];

        // 查询门店信息
        $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' => '停业失败']);
        }
    }
}
