<?php

namespace App\Services\Operation;

use App\Models\Operation\Business;
use BlueCity\Core\Service\Service;
use Illuminate\Support\Facades\DB;
use App\Http\Requests\Validators\Operation\StoreListValidator;
use App\Services\Shop\ShopService;

class StoreListService extends Service
{
    public static $instance;
    public $modelMain = null;
    public $mainValidator = null;

    public function __construct()
    {
        $this->modelMain = new Business();
        $this->mainValidator = new StoreListValidator();
    }

    /**
     * @return mixed
     */
    public static function getInstance()
    {
        if (is_null(static::$instance)) {
            static::$instance = new static;
        }
        return static::$instance;
    }

    /**
     * 检查是不是存在同名内容
     * @param $name 考核项名称
     * @param $type 类型：1施工部位2整车3其他
     * @param int $id 排除这个id
     * @return mixed
     */
    public static function nameExists($user_info, $request, $id = 0)
    {
        if ($id == 0) {
            return Business::where('bucl_name', $request['bucl_name'])
                ->where('bucl_shop_id', $user_info->adm_shop_id)
                ->where('bucl_del', 1)
                ->exists();
        } else {
            return Business::where('bucl_name', $request['bucl_name'])
                ->where('bucl_shop_id', $user_info->adm_shop_id)
                ->where('bucl_del', 1)
                ->where('bucl_id', '<>', $id)
                ->exists();
        }
    }

    /**
     * 检查是不是存在相同手机号
     */
    public static function phoneExists($user_info, $request, $id = 0)
    {
        if ($id == 0) {
            $find_buac_data = DB::table('business_account')
                ->where('buac_phone', $request['buac_phone'])
                ->where('buac_bucl_id', $request['bucl_id'])
                ->where('buac_del', 1)
                ->exists();
            if ($find_buac_data) { //本单位存在手机号
                return 1;
            }
            $find_all_buac_data = DB::table('business_account')
                ->where('buac_phone', $request['buac_phone'])
                ->where('buac_del', 1)
                ->exists();
            if ($find_all_buac_data) { //其他单位存在此手机号
                return 2;
            } else {
                return 3;
            }
        } else {
            $find_buac_data = DB::table('business_account')
                ->where('buac_phone', $request['buac_phone'])
                ->where('buac_bucl_id', $request['bucl_id'])
                ->where('buac_id', '<>', $id)
                ->where('buac_del', 1)
                ->exists();
            if ($find_buac_data) { //本单位存在手机号
                return 1;
            }
            $find_all_buac_data = DB::table('business_account')
                ->where('buac_phone', $request['buac_phone'])
                ->where('buac_id', '<>', $id)
                ->where('buac_del', 1)
                ->exists();
            if ($find_all_buac_data) { //其他单位存在此手机号
                return 2;
            } else {
                return 3;
            }
        }
    }

    // 新增
    public static function add($user_info, $request)
    {
        // 判断门店名称是否存在
        $store_name = DB::table('shop')
            ->where('shop_cid', $request['shop_cid'])
            ->where('shop_store_name', $request['shop_store_name'])
            ->value('shop_store_name');
        if ($store_name) {
            return ["code" => 500, 'msg' => '门店名称已存在', 'data' => ''];
        }
        // 判断手机号是否存在
        $adm_phone = DB::table('admin_shop_role')
            ->where('phone', $request['shop_phone'])
            ->where('adm_shop_leave', 1)
            ->value('adm_id');
        if (!empty($adm_phone)) {
            return response()->json(["code" => 500, 'msg' => '该手机号已是其他门店店长', 'data' => '']);
        }


        // 3新增门店
        DB::beginTransaction();

        // 3.1 门店表新增一个门店数据
        $shop_add_data['shop_cid'] = $request['shop_cid']; //所属公司id
        $shop_add_data['shop_superior_id'] = 0; //所属总店id
        $shop_add_data['shop_type'] = 1; //类型：1总店2直营店3加盟店
        $shop_add_data['shop_parent_id'] = 0; //隶属上级门店id
        $shop_add_data['shop_versions'] = $request['shop_versions']; //系统版本：1基础版2企业版3连锁版
        $shop_add_data['shop_store_name'] = $request['shop_store_name']; //门店名称
        $shop_add_data['shop_name'] = $request['shop_name']; //联系人姓名
        $shop_add_data['shop_phone'] = $request['shop_phone']; //联系电话/手机号
        $shop_add_data['shop_adm_id'] = 0; //店长账号id
        $shop_add_data['shop_province'] = $request['shop_province']; //省份
        $shop_add_data['shop_city'] = $request['shop_city']; //市
        $shop_add_data['shop_county'] = $request['shop_county']; //区县
        $shop_add_data['shop_address'] = $request['shop_address']; //详细地址
        $shop_add_data['shop_opening_start_time'] = date('Y-m-d H:i:s');
        $shop_add_data['shop_opening_end_time'] = '2025-03-24';
        if (!empty($request['shop_longitude'])) {
            $shop_add_data['shop_longitude'] = $request['shop_longitude'];
        }
        if (!empty($request['shop_latitude'])) {
            $shop_add_data['shop_latitude'] = $request['shop_latitude'];
        }

        // 新增门店
        $shop_id =  DB::table('shop')->insertGetId($shop_add_data);
        ShopService::addFestival($shop_id);
        // 为门店添加服务
        // $server_pro = config('apisystem.SERVER_PRO');
        $server_data = [
            '改色贴膜','洗车','隐形车衣','玻璃膜施工'
        ];
        $sepr_pic_conf = [
            '[{"id":1,"show_word":"汽车名牌","must_state":1},{"id":2,"show_word":"车膜标签","must_state":1},{"id":3,"show_word":"膜桶标签","must_state":1},{"id":4,"show_word":"全车照片","must_state":1},{"id":5,"show_word":"全车视频","must_state":1}]',
            '[{"id":1,"show_word":"汽车名牌","must_state":1},{"id":2,"show_word":"车膜标签","must_state":1},{"id":3,"show_word":"膜桶标签","must_state":1},{"id":4,"show_word":"全车照片","must_state":1},{"id":5,"show_word":"全车视频","must_state":1}]',
            '[{"id":1,"show_word":"汽车名牌","must_state":1},{"id":2,"show_word":"车膜标签","must_state":1},{"id":3,"show_word":"膜桶标签","must_state":1},{"id":4,"show_word":"全车照片","must_state":1},{"id":5,"show_word":"全车视频","must_state":1}]',
            '[{"id":1,"show_word":"汽车名牌","must_state":1},{"id":2,"show_word":"车膜标签","must_state":1},{"id":3,"show_word":"膜桶标签","must_state":1},{"id":4,"show_word":"全车照片","must_state":1},{"id":5,"show_word":"全车视频","must_state":1}]',
        ];
        $date = date('Y-m-d H:i:s');
        foreach ($server_data as $k => $v) {
            $server_pro[$k]['sepr_cid'] = $request['shop_cid'];
            $server_pro[$k]['sepr_shop_id'] = $shop_id;
            $server_pro[$k]['sepr_superior_shop_id'] = $shop_id;
            $server_pro[$k]['sepr_name'] = $v;
            $server_pro[$k]['sepr_show_location'] = 3;
            $server_pro[$k]['sepr_pic_conf'] = $sepr_pic_conf[$k];
            $server_pro[$k]['sepr_create_time'] = $date;
        }
        $service_project = DB::table('service_project')->insert($server_pro);

        // 新增职称数据
        $grade_professional = ['小工','中工','大工','学徒'];
        foreach ($grade_professional as $k => $v) {
            $professional['grpr_cid'] = $request['shop_cid'];
            $professional['grpr_superior_shop_id'] = $shop_id;
            $professional['grpr_shop_id'] = $shop_id;
            $professional['grpr_name'] = $v;
            $professional['grpr_update_time'] = $date;
            $grpr_id = DB::table('wash_grade_professional')->insertGetId($professional);
            // 添加级别数据
            if ($v == '大工' || $v == '中工') {
                $temp_data['grle_cid'] = $request['shop_cid'];
                $temp_data['grle_superior_shop_id'] = $shop_id;
                $temp_data['grle_shop_id'] = $shop_id;
                $temp_data['grle_grpr_id'] = $grpr_id;
                $temp_data['grle_name'] = '一级';
                $temp_data['grle_remark'] = $v.'一级';
                $temp_data['grle_update_time'] = $date;
                $grade_level[] = $temp_data;
                unset($temp_data);
                $temp_data['grle_cid'] = $request['shop_cid'];
                $temp_data['grle_superior_shop_id'] = $shop_id;
                $temp_data['grle_shop_id'] = $shop_id;
                $temp_data['grle_grpr_id'] = $grpr_id;
                $temp_data['grle_name'] = '二级';
                $temp_data['grle_remark'] = $v.'二级';
                $temp_data['grle_update_time'] = $date;
                $grade_level[] = $temp_data;
                unset($temp_data);
                $temp_data['grle_cid'] = $request['shop_cid'];
                $temp_data['grle_superior_shop_id'] = $shop_id;
                $temp_data['grle_shop_id'] = $shop_id;
                $temp_data['grle_grpr_id'] = $grpr_id;
                $temp_data['grle_name'] = '三级';
                $temp_data['grle_remark'] = $v.'三级';
                $temp_data['grle_update_time'] = $date;
                $grade_level[] = $temp_data;
                unset($temp_data);
                $grle_id = DB::table('wash_grade_level')->insert($grade_level);
                unset($grade_level);
            }
            if ($v == '小工') {
                $temp_data['grle_cid'] = $request['shop_cid'];
                $temp_data['grle_superior_shop_id'] = $shop_id;
                $temp_data['grle_shop_id'] = $shop_id;
                $temp_data['grle_grpr_id'] = $grpr_id;
                $temp_data['grle_name'] = '小工';
                $temp_data['grle_remark'] = '初学者';
                $temp_data['grle_update_time'] = $date;
                $grade_level[] = $temp_data;
                unset($temp_data);
                $grle_id = DB::table('wash_grade_level')->insert($grade_level);
                unset($grade_level);
            }
        }

        // 添加验车管理数据
        // 车内异常
        $validate_car1 = ['电动天窗异常', '车内缺点烟器', '车内照明灯异常', '仪表异常 （有故障码）'];
        // 外观异常
        $validate_car2 = ['胶皮密封条破损或异常', '车头、侧身等灯具类破损或异常', '车标、格栅、装饰条破损或损坏', '装饰件破损或异常'];
        foreach ($validate_car1 as $key => $value) {
            $validate_car_data[$key]['vacm_cid'] = $request['shop_cid'];
            $validate_car_data[$key]['vacm_shop_id'] = $shop_id;
            $validate_car_data[$key]['vacm_superior_shop_id'] = $shop_id;
            $validate_car_data[$key]['vacm_unusual_name'] = $value;
            $validate_car_data[$key]['vacm_type'] = 1;
            $validate_car_data[$key]['vacm_update_time'] = $date;
        }
        $vacm_id = DB::table('wash_validate_car_manage')->insert($validate_car_data);
        unset($validate_car_data);
        foreach ($validate_car2 as $key => $value) {
            $validate_car_data[$key]['vacm_cid'] = $request['shop_cid'];
            $validate_car_data[$key]['vacm_shop_id'] = $shop_id;
            $validate_car_data[$key]['vacm_superior_shop_id'] = $shop_id;
            $validate_car_data[$key]['vacm_unusual_name'] = $value;
            $validate_car_data[$key]['vacm_type'] = 2;
            $validate_car_data[$key]['vacm_update_time'] = $date;
        }
        $vacm_id = DB::table('wash_validate_car_manage')->insert($validate_car_data);
        unset($validate_car_data);

        // 新增质检数据
        $reward_punishment = [
            [
                'qurp_cid'=>$request['shop_cid'],
                'qurp_superior_shop_id'=>$shop_id,
                'qurp_shop_id'=>$shop_id,
                'qurp_name'=>'刀痕',
                'qurp_standard'=>-10,
                'qurp_standard_type'=>1,
                'qurp_type'=>1,
                'qurp_update_time'=>$date
            ],
            [
                'qurp_cid'=>$request['shop_cid'],
                'qurp_superior_shop_id'=>$shop_id,
                'qurp_shop_id'=>$shop_id,
                'qurp_name'=>'气泡',
                'qurp_standard'=>-10,
                'qurp_standard_type'=>1,
                'qurp_type'=>1,
                'qurp_update_time'=>$date
            ],
            [
                'qurp_cid'=>$request['shop_cid'],
                'qurp_superior_shop_id'=>$shop_id,
                'qurp_shop_id'=>$shop_id,
                'qurp_name'=>'漏漆',
                'qurp_standard'=>-10,
                'qurp_standard_type'=>1,
                'qurp_type'=>1,
                'qurp_update_time'=>$date
            ],
            [
                'qurp_cid'=>$request['shop_cid'],
                'qurp_superior_shop_id'=>$shop_id,
                'qurp_shop_id'=>$shop_id,
                'qurp_name'=>'废料太高',
                'qurp_standard'=>-10000,
                'qurp_standard_type'=>2,
                'qurp_type'=>3,
                'qurp_update_time'=>$date
            ],
            [
                'qurp_cid'=>$request['shop_cid'],
                'qurp_superior_shop_id'=>$shop_id,
                'qurp_shop_id'=>$shop_id,
                'qurp_name'=>'余料多，节省材料',
                'qurp_standard'=>10000,
                'qurp_standard_type'=>2,
                'qurp_type'=>2,
                'qurp_update_time'=>$date
            ],
        ];
        $qurp_id = DB::table('wash_quality_reward_punishment')->insert($reward_punishment);

        // 3.2 新增一个角色数据，店长的角色，店长角色的权限应该是固定的，新增店长账号需要有对应的角色
        // 查询基础版权限
        $jur_where['jur_delete'] = 1;
        $jur_where['jur_state'] = $request['shop_versions']; //类型：1基础版2企业版3连锁版
        $jur_res = DB::table('jurisdiction')->where($jur_where)->select('jur_privilege_multiple')->first();

        $role_add_data['rol_cid'] = $request['shop_cid'];
        $role_add_data['rol_shop_id'] = $shop_id;
        $role_add_data['rol_type'] = 1;
        $role_add_data['rol_name'] = '总管理';
        $role_add_data['rol_privilege_multiple'] = $jur_res->jur_privilege_multiple;
        $role_add_data['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($admId)) {
            $admin_add_data['adm_cid'] = $request['shop_cid'];
            $admin_add_data['adm_superior_shop_id'] = $shop_id;
            $admin_add_data['adm_shop_id'] = $shop_id;
            $admin_add_data['adm_leave'] = 1;
            $admin_add_data['adm_phone'] = $request['shop_phone'];
            $admin_add_data['adm_account'] = 'os' . time() . rand(100, 999);
            if (empty($request['adm_password'])) {
                $adm_password = '123456';
            } else {
                $adm_password = $request['adm_password'];
            }
            $admin_add_data['adm_password'] = md5($adm_password.'faster123456');
            $admin_add_data['adm_name'] = $request['shop_name'];
            $admin_add_data['adm_role'] = $role_id;
            $admin_add_data['adm_creator_id'] = $user_info->adm_id;
            // 新增账号
            $adm_id =  DB::table('admin')->insertGetId($admin_add_data);
        }

        //新增账号门店权限关系表
        $insertAdminShopRoleData = [
            'adm_id' => $adm_id,
            'shop_cid' => $request['shop_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);

        // 新增默认仓库
        $ware_add_data['ware_cid'] = $request['shop_cid']; //门店id
        $ware_add_data['ware_shop_id'] = $shop_id; //门店id
        $ware_add_data['ware_superior_shop_id'] = $shop_id; //总店id
        $ware_add_data['ware_name'] = '默认仓库'; //仓库名称
        $ware_add_data['ware_type'] = 1; //类型：1固定仓2技师库3移动仓
        $ware_add_data['ware_leader_id'] = $adm_id; //仓库负责人id
        $ware_add_data['ware_address'] = $request['shop_address']; //总店id
        // 新增仓库
        $ware_res =  DB::table('warehouse')->insertGetId($ware_add_data);
        // 添加默认仓库分类
        $warehouse_class = config('apisystem.warehouse_class');
        foreach ($warehouse_class as $key => $value) {
            $warehouse_class[$key]['wacl_cid'] = $request['shop_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);
        // 新增仓库类别数据
        $waon_class = config('apisystem.WAREHOUSE_CLASS'); //  仓库类别：1货物仓2非货物仓3旧货仓4临时仓
        foreach ($waon_class as $key => $value) {
            $waon_data[$key]['waon_ware_id'] = $ware_res;
            $waon_data[$key]['waon_class'] = $value;
            $waon_data[$key]['waon_update_time'] = date('Y-m-d H:i:s');
        }
        $waon_res =  DB::table('warehouse_onhand')->insert($waon_data);
        if ($ware_add_data['ware_type'] == 1 && $request['shop_versions'] == 2) {
            // 新增默认仓位
            $data['wafr_shop_id'] = $shop_id; //仓位隶属门店id
            $data['wafr_ware_id'] = $ware_res; //仓位隶属仓库id
            $data['wafr_parent_id'] = 0; //仓位隶属上级id
            $data['wafr_rank'] = 1; //仓位级别，第几级
            $data['wafr_name'] = '默认仓位'; //仓位名称
            $data['wafr_delete'] = 1; //是否删除1否2是
            $data['wafr_first_parent_id'] = 0; //仓位所属一级id
            $wafr_id = DB::table('warehouse_freight')->insertGetId($data);
        } else {
            $wafr_id = true;
        }
        // 设置我的仓库权限
        $adms_data['adms_adm_id'] = $adm_id; //员工id
        $adms_data['adms_myware_id'] = $ware_res; //我的仓库-仓库查看及相关操作权限
        $adms_data['adms_update_time'] = date('Y-m-d H:i:s'); //更新时间
        $adms_data['adms_shop_id'] = $shop_id; //员工id
        $adms_res = DB::table('admin_set')->insert($adms_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 ($shop_id && $role_id && $adm_id && $shop_save_res && $class_res && $service_project && $waon_res && $wafr_id && $adms_res && $qurp_id && $admin_shop_role_id) {
            DB::commit();
            return response()->json(["code" => 200, 'msg' => '新增门店成功', 'data' => '']);
        } else {
            DB::rollBack();
            return response()->json(["code" => 500, 'msg' => '新增门店失败', 'data' => '']);
        }
    }
}
