<?php

namespace App\Services\SettleIn;
use App\Http\Models\Api\ReceivableBill;
use App\Models\SettleIn;
use App\Models\SettleInSchedule;
use App\Models\SettleInSyncInformation;
use App\Services\CommonService;
use App\Services\LoginUserService;
use App\Services\ReceivablePay\ReceivablePayService;
use App\Services\ThreeApi\BaiDu\BaiDuService;
use BlueCity\Core\Service\Service;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Models\Api\Common;
use Overtrue\Pinyin\Pinyin;
use \Illuminate\Support\Facades\Validator;
use App\Services\Shop\ShopService;
use App\Http\Models\Api\CashierDesk;

class SettleInService extends Service
{
    // 列表每页显示数据个数
    protected $show_count = 10;

    // 列表

    /**
     * @name 列表
     * @param Request $request
     * @return mixed
     * @author du
     * @date 2023/5/18
     * @Time: 10:30
     */
    public static function getList($input,$pageSize)
    {

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

          // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
          $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;*/

        $list_data = SettleIn::orderBy('id', 'desc');
        $where = [];
        if(isset($input['status'])){
            if(in_array($input['status'],[1,2,3,4,5,6,7])){
                $where['status'] = $input['status'];
                $where['submit_history'] = 2;//展示完成提交的数据
            }
        }

        if(isset($input['shop_name'])){
            $where['shop_name_like'] = $input['shop_name'];
//            $list_data = $list_data ->where('shop_name','like','%'.$input['shop_name'].'%');
        }
        if(isset($input['charge_name'])){
            $where['charge_name_like'] = $input['charge_name'];
//            $list_data = $list_data ->where('charge_name','like','%'.$input['charge_name'].'%');
        }
        if(isset($input['phone'])){
            $where['phone_like'] = $input['phone'];
//            $list_data = $list_data ->where('phone','like','%'.$input['phone'].'%');
        }
        $where = CommonService::jointWhere($where);
        if($where){
            $list_data = $list_data->whereRaw($where) ->select('id', 'shop_name', 'phone', 'charge_name', 'create_time', 'goods_ids','address',
                'status','submit_end','shop_province','shop_city','shop_county')
                ->orderBy('id', 'desc')
                ->paginate($pageSize);
        }else{
            $list_data = $list_data ->select('id', 'shop_name', 'phone', 'charge_name', 'create_time', 'goods_ids',
                'status','address','submit_end','shop_province','shop_city','shop_county')
                ->orderBy('id', 'desc')
                ->paginate($pageSize);
        }
        $list_items = $list_data->items();
        if ($list_items) {
            $status_names = self::getSettleStatus();
            $goods_idsnames = self::getTypeNameOld(true);
            // 获取当前列表下的按钮
            $list_button = getListButton($input['api_token'], $input['pri_id']);
            foreach ($list_items as $key => $value) {
                $buttonData = [];
                if(in_array($value['status'], [1,3])){
                    $buttonData[] = 'editStatus';
                }elseif (in_array($value['status'], [4,5])) {
                    $buttonData[] = 'exmInfo';
                }/*elseif(in_array($value['status'], [5])){
                    $buttonData[] = 'exmInfo';
                }*/
                $button = CommonService::getListButton($buttonData,$list_button);
                //submit_end = 1是未完成状态，status = 2是不审核状态。不展示按钮
                if(($value['submit_end'] == 1 && $value['submit_history'] == 1 ) || $value['status'] == 2){
                    if($value['submit_end'] == 1){
                        $list_items[$key]['status_name'] = '未完成';
                    }else if($value['status'] == 2){
                        $list_items[$key]['status_name'] = '不审核';
                    }
                    $list_items[$key]['button_one'] = [];
                    $list_items[$key]['button_two'] = [];
                    $list_items[$key]['button_three'] = [];
                }else{
                    $list_items[$key]['status_name'] = $status_names[$value['status']];
                    $list_items[$key]['button_one'] = $button['button_one']??[];
                    $list_items[$key]['button_two'] = $button['button_two']??[];
                    $list_items[$key]['button_three'] = $button['button_three']??[];
                }

                $data = explode(',', $value['goods_ids']);
                $goods = [];
                foreach ($data as $k => $v) {
                    if(isset($goods_idsnames[$v])){
                        $goods[$k] = $goods_idsnames[$v];
                    }
                }
                if($goods) {
                    $list_items[$key]['goods_name'] = implode(',',$goods);
                }else{
                    $list_items[$key]['goods_name'] = '';
                }
                $list_items[$key]['address'] = $list_items[$key]['shop_province'].$list_items[$key]['shop_city'].$list_items[$key]['shop_county'].$list_items[$key]['address'];
            }
            $data_info['showcount'] = self::getStatusBar(true);
        }else{
            $data_info['showcount'] = self::getStatusBar(true);
        }

        $data_info['current_page'] = $list_data->currentPage();  //当前页面页码
        $data_info['last_page'] = $list_data->lastPage();        //表示最后一页的页码
        $data_info['total'] = $list_data->total();               //总数据个数
        $data_info['current_number'] = $pageSize;       //一页显示多少个
        $data_info['data'] = $list_items;                //返回数据
        if($list_data) {
            return response()->json(['code'=> 200,'msg'=>'获取成功','data'=>$data_info]);
        }else{
            return response()->json(['code'=> 500,'msg'=>'暂无数据','data'=>'']);
        }
    }

    /*---------------------------------------------------------------------------------
     * @name 获取顶部状态栏
     * @param string $type 查询数据类型
     * @retrun /multitype:array
     * @author dou 2023-06-06 006 下午 3:45:04
     * |---------------------------------------------------------------------------------
     */
    public static function getStatusBar ( $type = false){
        $showcount = [
            ['showname' => "全部", 'shownum' => '0','status'=>0],
            ['showname' => "待审核", 'shownum' => '0','status'=>1],
            ['showname' => "已联系", 'shownum' => '0','status'=>3],
            ['showname' => "已通过", 'shownum' => '0','status'=>4],
            ['showname' => "已驳回", 'shownum' => '0','status'=>5],
            ['showname' => "不审核", 'shownum' => '0','status'=>2]
        ];
        if($type){
            foreach( $showcount as $k => $v ){
                $showcount[$k]['shownum'] = self::getStatusNum($v['status']);
            }
        }
        return $showcount;
    }
    /**
     * 获取指定状态订单数量
     * @param string $status 状态栏参数
     * @return /multitype:array
     * @author dou 2023-06-06 006 下午 3:45:04
     */
    public static function getStatusNum ( $status ){
        if(in_array($status,[1,2,3,4,5])){
            $db = new SettleIn();
            $where['status'] = $status;
            $where['submit_history'] = 2;
            $num = CommonService::getMysqlData($db,$where,[],[],'count');
            $num = $num??'0';
            return $num;
        }else{
            return '--';
        }
    }

    /*
     * @name 判断入驻是新增还是修改
     * @param array $input  提交的数据
     * @retrun array
     * @author Ma 2023/7/4 16:24
     *
    */
    public static function settleUp($input){
        if (!isset($input['open_id'])) {
            return ['code'=> 500, 'msg'=>'open_id不能为空', 'data'=>''];
        }
        if(isset($input['id']) && !empty($input['id'])){
            //修改
            $data = self::updateSettleData($input,$input['id']);
        }else{
            //添加
            $data = self::add($input);
        }
        return $data;
    }

    /*
     * @name 整理平台联盟数据
     * @param array  $input 提交的数据
     * @retrun array  返回是否同步
     * @author Ma 2023/7/4 16:43
     *
    */
    public static function updatePlatform($input){
        $data = [];
        if(isset($input['platform']) && !empty($input['platform'])){
            $platform_data = explode(',', $input['platform']);
            foreach ($platform_data as $key => $value){
                $data['type'] = $value;
            }
        }
        return $data;
    }

    /*
     * @name 添加申请入驻验证
     * @param string $input
     * @retrun \Illuminate\Http\JsonResponse /multitype:array
     * @author Ma 2023/7/4 14:14
     *
     */
    public static function addValidator($input){
        $message = [
            'shop_name.required'=> '门店不能为空',
            'phone.required'=> '电话不能为空',
            'phone.regex'=> '电话号码不正确',
            'charge_name.required'=> '姓名不能为空',
            //'goods_ids.required'=> '服务项目不能为空',
        ];
        $rules = [
            'shop_name' =>'required',
            //  'shop_name' =>'required|unique:settle_in,shop_name',
            'phone' =>'required',
            'phone' =>['regex:/^[1](([3][0-9])|([4][5-9])|([5][0-3,5-9])|([6][5,6])|([7][0-8])|([8][0-9])|([9][1,8,9]))[0-9]{8}$/'],
            // 'charge_name'=>'required',
            //'goods_ids'=>'required',
        ];
        $Validator = Validator::make($input,$rules,$message);
        if($Validator->fails()){
            return ['data'=>'','code'=>500, 'msg'=>$Validator->errors()->first()];
        }
        // $shop_exist = DB::table('shop')
        //     ->where('shop_phone', $input['phone'])
        //     ->value('shop_id');
        // // $admin_exist = DB::table('admin')->where('adm_phone',$input['phone'])->value('adm_id');
        // if($shop_exist){
        //     return ['data'=>'','code'=>500, 'msg'=>'账号已存在'];
        // }
        // $shop_exist = DB::table('shop')->where('shop_store_name',$input['shop_name'])->value('shop_id');
        // if($shop_exist){
        //     return ['data'=>'','code'=>500, 'msg'=>'该门店已存在'];
        // }

        $phone_exist = DB::table('settle_in')->where('status','!=',5)->where('phone',$input['phone'])->value('id');
        $find_shop = DB::table('shop as a')
            ->leftJoin('settle_in as s', 's.shop_id', '=', 'a.shop_id')
            ->where('id', $phone_exist)
            ->select('shop_source_identify')
            ->first();
        if ($find_shop) {
            if ($find_shop->shop_source_identify != '5') {
                if($phone_exist){
                    return ['data'=>'','code'=>500, 'msg'=>'手机号已存在'];
                }
            }
        }
        $shop_exist = DB::table('settle_in')->where('shop_name',$input['shop_name'])->where('status','!=',5)->value('id');
        if($shop_exist){
            return ['data'=>'','code'=>500, 'msg'=>'该门店已存在'];
        }
        return ['data'=>'success','code'=>200, 'msg'=>'success'];
    }

    /**
     * @name 新增入驻公司
     * @param $input
     * @return mixed
     * @author du
     * @date 2023/5/18
     * @Time: 11:17
     */
    public static function add($input)
    {
        //数据验证
        if((!isset($input['shop_id']) || $input['shop_id'] < 1) && $input['type'] == 1){
            $data_validator = self::addValidator($input);
            if($data_validator['code'] != 200){
                return $data_validator;exit;
            }
        }
        $find_shop = DB::table('shop as a')
            ->leftJoin('settle_in as s', 's.shop_id', '=', 'a.shop_id')
            ->where('phone', $input['phone'])
            ->where('shop_source_identify', 5)
            ->value('id');
        if (isset($input['type']) && $input['type'] == 2) {// 账号注册
            if (!isset($input['adm_account']) || empty($input['adm_account'])) {
                return ['code'=>500, 'msg'=>'请输入账号', 'data'=>''];
            }
            $find_admin = DB::table('admin')
                ->where('adm_account', $input['adm_account'])
                ->first();
            if ($find_admin && $find_admin->adm_phone) {
                return ['code'=>500, 'msg'=>'账号已存在', 'data'=>''];
            }
            $find_shop = DB::table('settle_in')
                ->where('shop_adm_account', $input['adm_account'])
                ->value('id');
            if ($find_shop) {
                return ['code'=>500, 'msg'=>'账号已存在', 'data'=>''];
            }
            $find_shop = DB::table('shop as a')
                ->leftJoin('settle_in as s', 's.shop_id', '=', 'a.shop_id')
                ->where('s.shop_adm_account', $input['adm_account'])
                ->where('shop_source_identify', 5)
                ->value('id');
        }

        if ($input['inv_code']) {
            $find_inv_data = DB::table('shop_invitate_code_config')
                ->where('shic_code', $input['inv_code'])
                ->first();
            if ($find_inv_data) {
                if ($find_inv_data->shic_state == 1 && $find_inv_data->shic_start_date < date('Y-m-d H:i:s') && $find_inv_data->shic_end_date > date('Y-m-d H:i:s')) {
                    $input['inv_shop_code'] = $find_inv_data->shic_shop_code;
                    $update_shic['shic_use_num'] = $find_inv_data->shic_use_num + 1;
                    if ($update_shic['shic_use_num'] >= $find_inv_data->shic_num) {
                        $update_shic['shic_state'] = 2;
                    }
                    $inv_gift_time = $find_inv_data->shic_gift_time;
                    $update_shic_res = DB::table('shop_invitate_code_config')
                        ->where('shic_id', $find_inv_data->shic_id)
                        ->update($update_shic);
                } else {
                    return ['code'=>500, 'msg'=>'此邀请码已作废', 'data'=>''];
                }
            } else {
                return ['code'=>500, 'msg'=>'未查询到此邀请码', 'data'=>''];
            }
        } else {
            $inv_gift_time = config('apisystem.Gift_time');
        }

        if ($find_shop) {
            $update['status'] = 1;
            $update['inv_code'] = $input['inv_code']??'0';
            $update['inv_shop_code'] = $input['inv_shop_code']??'0';
            $update['inv_shop_code_type'] = $input['inv_shop_code_type']??'2';
            $update['inv_gift_time'] = $find_inv_data->shop_gift_time;//赠送邀请人时长
            $update_res = DB::table('settle_in')
                ->where('id', $find_shop)
                ->update($update);
            if (isset($input['inv_shop_code'])) {
                $find_code = DB::table('shop')
                    ->where('shop_code', $input['inv_shop_code'])
                    ->first();

                if (empty($find_code)) {
                    return ['code'=>500, 'msg'=>'未查询到此邀请码，请清除或修改邀请码', 'data'=>''];
                }
                $add_log['inlo_sein_id'] = $find_shop;
                $add_log['inlo_create_time'] = date('Y-m-d H:i:s');
                $add_res = DB::table('invitation_log')->insertGetId($add_log);
            }
            $wechat_msg['pushtype'] = 8; //注册提醒
            $wechat_msg['adm_id'] = 485; //推送人
            $wechat_msg['shop_name'] = $input['shop_name']; //门店名称
            $wechat_msg['state'] = '审核中'; //审核状态
            $wechat_msg['ord_number'] = ''; //审核状态
            $wechat_msg['wor_number'] = ''; //审核状态
            $wechat_msg['time'] = date('Y-m-d H:i:s'); //时间
            $CashierDesk = new CashierDesk;
            $CashierDesk->inforPush($wechat_msg);
            if ($update_res) {
                return ['code'=>200, 'msg'=>'门店创建成功，请等待审核', 'data'=>$find_shop];
            } else {
                return ['code'=>500, 'msg'=>'门店创建失败', 'data'=>'新增失败'];
            }
        }
        // 2 新增
        $data['shop_adm_account'] = $input['adm_account'] ? $input['adm_account'] : 'os' . time() . rand(100, 999); //用户名（登录账号）;
        $data['shop_name'] = $input['shop_name'];
        $data['phone'] = $input['phone'];
        $data['charge_name'] = $input['charge_name']?$input['charge_name']:$input['phone'];
        $data['goods_ids'] = $input['goods_ids']??'';
        $data['weixin'] = $input['weixin']??'';
        $data['appointment_phone'] = $input['appointment_phone']??'';
        $data['bussiness_time'] = $input['bussiness_time']??'';
        $data['store_area'] = $input['store_area']??'0';
        $data['parking_num'] = $input['parking_num']??'0';
        $data['technicians_num'] = $input['technicians_num']??'0';
        $data['avg_age'] = $input['avg_age']??'0';
        $data['workshop'] = $input['workshop']??'1';
        $data['can_wash_car'] = $input['can_wash_car']??'1';
        $data['brands'] = $input['brands']??'';
        $data['shop_code'] = $input['shop_code']??'';
        $data['company_name'] = $input['company_name']??'';
        $data['legal_person_name'] = $input['legal_person_name']??'';
        $data['legal_person_card'] = $input['legal_person_card']??'';
        $data['payment_method'] = $input['payment_method']??'1';
        $data['payment_account'] = $input['payment_account']??'';
        $data['opening_bank'] = $input['opening_bank']??'';
        $data['payment_name'] = $input['payment_name']??'';
        $data['shop_pic'] = $input['shop_pic']??'';
        $data['bussiness_pic'] = $input['bussiness_pic']??'';
        $data['receptio_pic'] = $input['receptio_pic']??'';
        $data['rest_pic'] = $input['rest_pic']??'';
        $data['build_pic'] = $input['build_pic']??'';
        $data['workshop_pic'] = $input['workshop_pic']??'';
        $data['payment_code_pic'] = $input['payment_code_pic']??'';
        $data['alipay_code_pic'] = $input['alipay_code_pic']??'';
        $data['front_card'] = $input['front_card']??'';
        $data['back_card'] = $input['back_card']??'';
        $data['remarks'] = $input['remark']??'';
        $data['shop_province'] = $input['shop_province']??'';
        $data['shop_city'] = $input['shop_city']??'';
        $data['shop_county'] = $input['shop_county']??'';
        $data['longitude'] = $input['longitude']??'';
        $data['latitude'] = $input['latitude']??'';
        $data['open_id'] = $input['open_id']??'';
        $data['shop_id'] = $input['shop_id']??0;
        $data['step'] = $input['step']??0;
        $data['update_time'] = date('Y-m-d H:i:s');
        $data['is_invitation_code'] = $input['is_invitation_code']??'0';
        $data['inv_code'] = $input['inv_code']??'0';
        $data['inv_shop_code'] = $input['inv_shop_code']??'0';
        $data['inv_shop_code_type'] = $input['inv_shop_code_type']??'2';
        $data['inv_gift_time'] = $inv_gift_time;
        if(isset($input['address'])){
            if(isset($data['shop_province']) && isset($data['shop_city']) && isset($data['shop_county'])){
                $data['address'] = str_replace($data['shop_province'].$data['shop_city'].$data['shop_county'],'',$input['address']);
            }else{
                $data['address'] = $input['address'];
            }
        }
        if($data['is_invitation_code'] > 0){
            $data['status'] = 2;
        }
        if(!isset($input['platform'])){//不选择联盟，提交就是完成状态
            $data['submit_end'] = 2;
            $data['submit_history'] = 2;
        }
        $res = SettleIn::insertGetId($data);
        if($res){
            if(isset($input['platform']) && !empty($input['platform'])){
                $settle_data['settle_in_id'] = $res;
                $platform_data = explode(',', $input['platform']);
                foreach ($platform_data as $key => $value){
                    $settle_data['type'] = $value;
                    $settle_data['info_status'] = 1;
                    SettleInSyncInformation::insert($settle_data);//添加需要同步的数据
                }
            }
        }
        if (isset($input['inv_shop_code'])) {
            $find_code = DB::table('shop')
                ->where('shop_code', $input['inv_shop_code'])
                ->first();
            if (!$find_code) {
                return ['code'=>500, 'msg'=>'未查询到此邀请码，请清除或修改邀请码', 'data'=>''];
            }
            $add_log['inlo_sein_id'] = $res;
            $add_log['inlo_create_time'] = date('Y-m-d H:i:s');
            $add_res = DB::table('invitation_log')->insertGetId($add_log);
        }
        $wechat_msg['pushtype'] = 8; //注册提醒
        $wechat_msg['adm_id'] = 2095; //推送人
        $wechat_msg['shop_name'] = $input['shop_name']; //门店名称
        $wechat_msg['state'] = '审核中'; //审核状态
        $wechat_msg['ord_number'] = ''; //订单号
        $wechat_msg['wor_number'] = ''; //工单号
        $wechat_msg['time'] = date('Y-m-d H:i:s'); //时间
        $CashierDesk = new CashierDesk;
        $CashierDesk->inforPush($wechat_msg);

        if ($res) {
            return ['code'=>200, 'msg'=>'门店创建成功，请等待审核', 'data'=>$res];
        } else {
            return ['code'=>500, 'msg'=>'门店创建失败', 'data'=>'新增失败'];
        }
    }

    /*
     * @name 修改申请入驻
     * @param array $input 修改的数据
     * @param int $id where条件
     * @retrun array
     * @author Ma 2023/7/4 16:17
     *
    */
    public static function  updateSettleData($input,$id){
        //
        if(isset($input['phone']) && !empty($input['phone'])){
            $phone_exist = DB::table('settle_in')->where('phone',$input['phone'])->where('id', '<>', $id)->where('status', '<>', 5)->value('id');
            if($phone_exist){
                return ['data'=>'','code'=>500, 'msg'=>'手机号已存在'];
            }
        }
        if(isset($input['shop_name']) && !empty($input['shop_name'])){
            $phone_exist = DB::table('settle_in')->where('shop_name',$input['shop_name'])->where('id', '<>', $id)->where('status', '<>', 5)->value('id');
            if($phone_exist){
                return ['data'=>'','code'=>500, 'msg'=>'该门店已存在'];
            }
        }
        //查看入驻申请信息（如果申请过入驻，必须有审核驳回才能再次申请）
        if(isset($input['platform']) && !empty($input['platform'])){
            $submit = false;//可以提交
            $platform_data_va = explode(',', $input['platform']);
            $all_information_va = DB::table('settle_sync_information')
                ->where('settle_in_id', $id)
                ->whereIn('type', $platform_data_va)
                ->get()->toArray();
            if($all_information_va){
                foreach ($all_information_va as $va_k => $va_v){
                    $result_v[$va_v->type] = $va_v;
                }
                foreach ($platform_data_va as $v_k => $v_v){
                    //已经提交过，并且在审核中或者审核通过，已经推送的状态下，不可以提交
                    if(isset($result_v[$v_v]->info_status) && in_array($result_v[$v_v]->info_status,[1,2]) && $result_v[$v_v]->is_push == 2){
                        $submit = true;//不可以提交
                    }else{
                        $submit = false;//可以提交
                        break;
                    }
                }
            }
            if($submit){
                return response()->json(['code'=>500, 'msg'=>'请选择新的需要加入的联盟', 'data'=>'请选择新的需要加入的联盟']);
            }
        }
        //获取修改的字段
        $data = self::updateValueData($input);
        if($data['code'] != 200){
            return $data;
        }
        //如果扫码进来，手机号存在，获取申请的哪个联盟

        //获取图片的内容
        if($data['data']['step'] == 3){
            $img_data = self::getContentByImg($data['data']);
            $data['data'] = array_merge($data['data'],$img_data);
        }
        $settle_ret_old = DB::table('settle_in')->where('id',$id)->get()->first();//修改前的数据
        DB::beginTransaction();
        //修改入驻表信息
        $res = DB::table('settle_in')->where('id',$id)->update($data['data']);
        //修改同步表faster_settle_sync_information
        if(isset($input['platform']) && !empty($input['platform'])){
            if($settle_ret_old->submit_end == 1){//未提交完成，可以修改联盟信息
                $settle_data['settle_in_id'] = $id;
                $platform_data = explode(',', $input['platform']);
                //查找该用户入驻的的信息
                $all_information = DB::table('settle_sync_information')
                    ->where('settle_in_id', $id)
                    ->get()->toArray();
                foreach ($all_information as $all_key => $all_value){
                    if($all_value->is_push == 1 || $all_value->info_status == 3){
                        $del_ok[] = $all_value->id;//可以删除的id
                    }
                }
                if(isset($del_ok) && !empty($del_ok)){
                    $del_information = DB::table('settle_sync_information')
                        ->whereIn('id', $del_ok)
                        ->delete();
                }
                foreach ($platform_data as $key => $value){
                    //查找该用户入驻的的信息
                    $all_information = DB::table('settle_sync_information')
                        ->where('settle_in_id', $id)
                        ->where('type', $value)
                        ->first();
                    if($all_information){
                    }else{
                        $settle_data['type'] = $value;
                        $settle_data['info_status'] = 1;
                        DB::table('settle_sync_information')->insertGetId($settle_data);//添加需要同步的数据
                    }
                    //SettleInSyncInformation::insert($settle_data);
                }
            }else{
                //查找该用户入驻的的信息
                $all_information = DB::table('settle_sync_information')
                    ->where('settle_in_id', $id)
                    ->get()->toArray();
                if($all_information){
                    foreach ($all_information as $a_k => $a_v){
                        $all_types[] = $a_v->type;
                    }
                }
                $settle_data['settle_in_id'] = $id;
                $platform_data = explode(',', $input['platform']);
                foreach ($platform_data as $key => $value){
                    if (isset($all_types) && !empty($all_types)){
                        if (!in_array($value, $all_types)){
                            $settle_data['type'] = $value;
                            $settle_data['info_status'] = 1;
                            DB::table('settle_sync_information')->insertGetId($settle_data);//添加需要同步的数据
                        }
                    }else{
                        $settle_data['type'] = $value;
                        $settle_data['info_status'] = 1;
                        DB::table('settle_sync_information')->insertGetId($settle_data);//添加需要同步的数据
                    }
                }
            }
        }
        //$submit_end = DB::table('settle_in')->where('id',$id)->value('submit_end');
        $settle_ret = DB::table('settle_in')->where('id',$id)->get()->first();//修改后的数据
        $info_res = DB::table('settle_sync_information')->where('settle_in_id',$id)->first();
        //如果现在是驳回状态，前端修改在提交，状态修改为待审核
        if($settle_ret->status == 5 && isset($input['shop_id']) && $input['shop_id'] == 0){
            $res = DB::table('settle_in')->where('id',$id)->update(['status'=>1]);
        }
        //完成提交，同步信息到智配
        if($settle_ret->submit_end == 2 && !empty($info_res)){
            $up_arr = DB::table('settle_in as a')
                ->leftJoin('settle_sync_information as b', 'a.id', '=', 'b.settle_in_id')
                ->where('a.id',$input['id'])->select('type','shop_name','charge_name','phone','goods_ids','weixin','appointment_phone','bussiness_time','address','store_area','parking_num','technicians_num','avg_age','workshop','can_wash_car','brands','shop_code','company_name','legal_person_name','legal_person_card','payment_method','payment_account','payment_name','front_card','back_card','remarks','shop_province','shop_city','shop_county','opening_bank','longitude','latitude','is_push','info_status','shop_pic','bussiness_pic','receptio_pic','rest_pic','build_pic','workshop_pic','front_card','back_card','payment_code_pic','alipay_code_pic')->get()->toArray();
            if($up_arr){
                foreach ($up_arr as $k => $v){
                    $sto = $v;
                    $sto->company_id = $v->type;
                    $sto->remark = $v->remarks;
                    if($v->is_push == 1 || ($v->is_push == 2 && $v->info_status ==3)){//没有推送过并且同盟已经驳回的数据推送
                        $stor_arr[] = $sto;
                        $type[] = $v->type;
                    }
                }
            }
            if(isset($stor_arr) && !empty($stor_arr)){
                $param = json_decode(json_encode($stor_arr),true);
                $url = config('apiconnect.ZPTZ_URL') .'/index.php/api/service/ShopAudit/toAudit';
                $doPost_res = Common::doPost($param, $url, 2);
                $doPost_res = json_decode($doPost_res);
                if ($doPost_res->code != 200) {
                    DB::rollback();
                    return response()->json(['code'=>500, 'msg'=>'同步失败', 'data'=>$doPost_res->msg]);
                }else{
                    //同步成功后更新表faster_settle_sync_information
                    $information = [
                        'is_push'=> 2,
                        'in_weixin'=> $settle_ret->weixin,
                        'in_bussiness_time'=> $settle_ret->bussiness_time,
                        'in_address'=> $settle_ret->address,
                        'in_store_area'=> $settle_ret->store_area,
                        'in_parking_num'=> $settle_ret->parking_num,
                        'in_technicians_num'=> $settle_ret->technicians_num,
                        'in_avg_age'=> $settle_ret->avg_age,
                        'in_workshop'=> $settle_ret->workshop,
                        'in_can_wash_car'=> $settle_ret->can_wash_car,
                        'in_brands'=> $settle_ret->brands,
                        'in_shop_code'=> $settle_ret->shop_code,
                        'in_company_name'=> $settle_ret->company_name,
                        'in_legal_person_name'=> $settle_ret->legal_person_name,
                        'in_legal_person_card'=> $settle_ret->legal_person_card,
                        'in_payment_method'=> $settle_ret->payment_method,
                        'in_payment_account'=> $settle_ret->payment_account,
                        'in_payment_name'=> $settle_ret->payment_name,
                        'in_shop_pic'=> $settle_ret->shop_pic,
                        'in_bussiness_pic'=> $settle_ret->bussiness_pic,
                        'in_receptio_pic'=> $settle_ret->receptio_pic,
                        'in_rest_pic'=> $settle_ret->rest_pic,
                        'in_build_pic'=> $settle_ret->build_pic,
                        'in_workshop_pic'=> $settle_ret->workshop_pic,
                        'in_payment_code_pic'=> $settle_ret->payment_code_pic,
                        'in_alipay_code_pic'=> $settle_ret->alipay_code_pic,
                        'in_front_card'=> $settle_ret->front_card,
                        'in_back_card'=> $settle_ret->back_card,
                        'in_shop_province'=> $settle_ret->shop_province,
                        'in_shop_city'=> $settle_ret->shop_city,
                        'in_shop_county'=> $settle_ret->shop_county,
                        'in_opening_bank'=> $settle_ret->opening_bank,
                        'in_longitude'=> $settle_ret->longitude,
                        'in_latitude'=> $settle_ret->latitude,
                        'info_status'=> 1,
                        'remark'=> '',
                    ];
                    DB::table('settle_sync_information')->where('settle_in_id',$input['id'])
                        ->whereIn('type',$type)->update($information);
                }
            }
        }

        //改变状态
        /*$input['id'] = $id;
        $input['status'] = 4;
        $input['remark'] = '已完善';
        $input['type'] = 2;
        $input['ip'] = $_SERVER["REMOTE_ADDR"];
        $input['status_type'] = 1;
        self::editSchedule($input);*/
        if ($res) {
            DB::commit();
            return ['code'=>200, 'msg'=>'门店修改成功', 'data'=>$id];
        } else {
            DB::rollback();
            return ['code'=>500, 'msg'=>'门店修改失败', 'data'=>'修改失败'];
        }
    }

    /*
     * @name 通过图片获取内容
     * @param array  imgs
     * @retrun array
     * @author Ma 2023/7/10 18:25
     *
    */
    public static function getContentByImg($imgs){
        $data = [];
        //营业执照
        if(isset($imgs['bussiness_pic']) && !empty($imgs['bussiness_pic'])){
            $bussiness_pic = $imgs['bussiness_pic'];
            $img = file_get_contents($bussiness_pic);
            $img = base64_encode($img);
            $bodys = array(
                'image'=>$img
            );
            $bussiness_ret = BaiDuService::getPicData($bodys, 2);
            $bussiness_ret = json_decode(json_encode($bussiness_ret),true);
            if($bussiness_ret['code'] == 200){
                $data['legal_person_name'] = $bussiness_ret['data']['words_result']['法人']['words']??'';
                $data['company_name'] = $bussiness_ret['data']['words_result']['单位名称']['words']??'';
                $data['shop_code'] = $bussiness_ret['data']['words_result']['社会信用代码']['words']??'';
            }
        }
        //身份证
        if(isset($imgs['front_card']) && !empty($imgs['front_card'])){
            $front_card = $imgs['front_card'];
            $img = file_get_contents($front_card);
            $img = base64_encode($img);
            $bodys = array(
                'id_card_side' => "front",
                'image' => $img
            );
            $front_card_ret = BaiDuService::getPicData($bodys, 3);
            $front_card_ret = json_decode(json_encode($front_card_ret),true);
            if($front_card_ret['code'] == 200){
                $data['legal_person_card'] = $front_card_ret['data']['words_result']['公民身份号码']['words']??'';
            }
        }
        return $data;
    }

    /*
     * @name 申请入驻修改的字段
     * @param $input 提交的字段
     * @retrun array 可修改的字段
     * @author Ma 2023/7/4 11:46
     *
    */
    public static function updateValueData($input){
        if(isset($input['shop_name'])){
            $data['shop_name'] = $input['shop_name'];
        }
        if(isset($input['charge_name'])){
            $data['charge_name'] = $input['charge_name'];
        }
        if(isset($input['goods_ids'])){
            $data['goods_ids'] = $input['goods_ids'];
        }
        if(isset($input['weixin'])){
            $data['weixin'] = $input['weixin'];
        }
        if(isset($input['appointment_phone'])){
            $data['appointment_phone'] = $input['appointment_phone'];
        }
        if(isset($input['bussiness_time'])){
            $data['bussiness_time'] = $input['bussiness_time'];
        }
        if(isset($input['store_area'])){
            $data['store_area'] = $input['store_area'];
        }
        if(isset($input['parking_num'])){
            $data['parking_num'] = $input['parking_num'];
        }
        if(isset($input['technicians_num'])){
            $data['technicians_num'] = $input['technicians_num'];
        }
        if(isset($input['avg_age'])){
            $data['avg_age'] = $input['avg_age'];
        }
        if(isset($input['workshop'])){
            $data['workshop'] = $input['workshop'];
        }
        if(isset($input['can_wash_car'])){
            $data['can_wash_car'] = $input['can_wash_car'];
        }
        if(isset($input['brands'])){
            $data['brands'] = $input['brands'];
        }
        if(isset($input['shop_code'])){
            $data['shop_code'] = $input['shop_code'];
        }
        if(isset($input['company_name'])){
            $data['company_name'] = $input['company_name'];
        }
        if(isset($input['legal_person_name'])){
            $data['legal_person_name'] = $input['legal_person_name'];
        }
        if(isset($input['legal_person_card'])){
            $data['legal_person_card'] = $input['legal_person_card'];
        }
        if(isset($input['payment_method'])){
            $data['payment_method'] = $input['payment_method'];
        }
        if(isset($input['payment_account'])){
            $data['payment_account'] = $input['payment_account'];
        }
        if(isset($input['opening_bank'])){
            $data['opening_bank'] = $input['opening_bank'];
        }
        if(isset($input['payment_name'])){
            $data['payment_name'] = $input['payment_name'];
        }
        if(isset($input['shop_pic'])){
            $data['shop_pic'] = $input['shop_pic'];
        }
        if(isset($input['bussiness_pic'])){
            $data['bussiness_pic'] = $input['bussiness_pic'];
        }
        if(isset($input['receptio_pic'])){
            $data['receptio_pic'] = $input['receptio_pic'];
        }
        if(isset($input['rest_pic'])){
            $data['rest_pic'] = $input['rest_pic'];
        }
        if(isset($input['build_pic'])){
            $data['build_pic'] = $input['build_pic'];
        }
        if(isset($input['workshop_pic'])){
            $data['workshop_pic'] = $input['workshop_pic'];
        }
        if(isset($input['payment_code_pic'])){
            $data['payment_code_pic'] = $input['payment_code_pic'];
        }
        if(isset($input['alipay_code_pic'])){
            $data['alipay_code_pic'] = $input['alipay_code_pic'];
        }
        if(isset($input['front_card'])){
            $data['front_card'] = $input['front_card'];
        }else{
            if($input['step'] == 3){
                $data['front_card'] = '';
            }
        }
        if(isset($input['back_card'])){
            $data['back_card'] = $input['back_card'];
        }else{
            if($input['step'] == 3){
                $data['back_card'] = '';
            }
        }
        if(isset($input['remark'])){
            $data['remarks'] = $input['remark'];
        }
        if(isset($input['shop_province'])){
            $data['shop_province'] = $input['shop_province'];
        }
        if(isset($input['shop_city'])){
            $data['shop_city'] = $input['shop_city'];
        }
        if(isset($input['shop_county'])){
            $data['shop_county'] = $input['shop_county'];
        }
        if(isset($input['address'])){
            $data['address'] = $input['address'];
            if(isset($data['shop_province'])){
                $data['address'] = str_replace($data['shop_province'],'',$data['address']);
            }
            if(isset($data['shop_city'])){
                $data['address'] = str_replace($data['shop_city'],'',$data['address']);
            }
            if(isset($data['shop_county'])){
                $data['address'] = str_replace($data['shop_county'],'',$data['address']);
            }
        }
        if(isset($input['longitude'])){
            $data['longitude'] = $input['longitude'];
        }
        if(isset($input['latitude'])){
            $data['latitude'] = $input['latitude'];
        }
        if(isset($input['open_id'])){
            $data['open_id'] = $input['open_id'];
        }
        if(isset($input['step'])){
            $data['step'] = $input['step'];
        }
        if(isset($input['submit_end'])){
            $data['submit_end'] = $input['submit_end'];
            if($input['submit_end'] == 2){
                $data['submit_history'] = 2;
            }
        }

        /*if(isset($input['is_invitation_code'])){//是否为邀请码申请，邀请码申请的无需审核
            $data['is_invitation_code'] = $input['is_invitation_code'];
            if($input['is_invitation_code'] == 2){
                $data['status'] = 2;
            }
        }*/
        $data['update_time'] = date('Y-m-d H:i:s');
        return ['code'=>200, 'msg'=>'success', 'data'=>$data];
    }

    /**
     * @name 跟进
     * @param id 入驻ID
     * @param $input
     * @return mixed
     * @author du
     * @date 2023/5/18
     * @Time: 11:56
     */
    public static function editSchedule($input)
    {
        // 验证数据
        if (!isset($input['id'])||!isset($input['type'])) {
            return response()->json(['code'=> 500, 'msg'=>'参数错误', 'data'=>'']);
        }

        $info = SettleIn::where('id', $input['id'])->select('shop_name','charge_name','phone','status')->first();
        //获取页面数据
        if ($input['type']==1) {
            // 查询跟进信息
            $find_meca = SettleInSchedule::where('settle_in_id', $input['id'])->where('s_status','!=',1)->get();
            $status_names = self::getSettleStatus();
            $arr['settle_info'] = $info;
            $arr['settle_info']['status_name'] = $status_names[$arr['settle_info']['status']];
            $arr['list'] = $find_meca;
            $s_status_names = self::getSettleStatus();
            foreach ($arr['list'] as $k=>$v) {
                $arr['list'][$k]['s_status_name'] = $s_status_names[$v['s_status']];
            }
            return response()->json(['code'=> 200, 'msg'=>'获取成功', 'data'=>$arr]);
        }else{
            //修改数据
            // 状态 1待审核 2无需审核 3已联系 4已通过 5已驳回
            if (!isset($input['status'])) {
                return response()->json(['code'=> 500, 'msg'=>'请输入状态', 'data'=>'请输入状态']);
            }
            //已联系 和 已驳回 需要输入原因
            if(in_array($input['status'],[3,5]) && !isset($input['remark']) ){
                return response()->json(['code'=> 500, 'msg'=>'请输入原因', 'data'=>'请输入原因']);
            }
            if($input['status']<$info['status'] && !isset($input['status_type'])){
                return response()->json(['code'=> 500, 'msg'=>'状态不正确', 'data'=>'状态不正确']);
            }
            if(isset($input['api_token'])){
                // 获取当前操作账号信息
                $user_info = Common::getUserInfo($input['api_token']);
                if(empty($user_info)){
                    $user_info = Common::wechatGetUserInfo($input['api_token']);
                }
                $user_info = CommonService::dataToArray($user_info);
            }
            DB::beginTransaction();
            //添加跟进log
            $data['follow_up_id'] = $user_info['adm_id']??'0';
            $data['follow_up_name'] = $user_info['adm_name']??'';
            $data['s_status'] = $input['status'];
            $data['remark'] = $input['remark'] ??'';
            $data['settle_in_id'] = $input['id'];
            $res = SettleInSchedule::insert($data);
            //修改申请的状态
            DB::table('settle_in')->where('id',$input['id'])->update(['status'=>$input['status']]);
            if ($res) {
                //如果通过
                if($data['s_status']==4){
                    $find_settle = SettleIn::where('id', $input['id'])->first();
                    $shop_data['shop_store_name'] = $find_settle['shop_name'];
                    $shop_data['shop_name'] = $find_settle['charge_name'];
                    $shop_data['adm_account'] = $find_settle['shop_adm_account'];
                    $shop_data['shop_phone'] = $find_settle['phone'];
                    $shop_data['shop_province'] = $find_settle['shop_province'];
                    $shop_data['shop_city'] = $find_settle['shop_city'];
                    $shop_data['shop_county'] = $find_settle['shop_county'];
                    $shop_data['shop_address'] = $find_settle['address'];
                    $shop_data['goods_ids'] = $find_settle['goods_ids'];
                    $shop_data['shop_adm_name'] = $find_settle['charge_name'];
                    $word = substr($find_settle['phone'], -6);
                    $shop_data['shop_password'] =  md5($word.'faster123456');
                    $shop_data['shop_source_identify'] = 1;
                    $shop_data['api_token'] = isset($input['api_token']) ? $input['api_token'] : '';
                    if($find_settle['shop_pic']){
                        $shop_data['shop_image'] = $find_settle['shop_pic'];
                    }else{
                        $shop_data['shop_image'] = config('apisystem.server_name_https') .'/image/pcImg/shop_default_img.png';
                    }
                    $shop_data['shop_opening_time'] = $find_settle['bussiness_time'];
                    $shop_data['shop_longitude'] = $find_settle['longitude'];
                    $shop_data['shop_latitude'] = $find_settle['latitude'];
                    if($find_settle['goods_ids']){
                        $goods_ids = explode(',',$find_settle['goods_ids']);
                        $goods_name = SettleInService::getTypeName('all',true);
                        foreach ($goods_ids as $goo_ke => $goo_va){
                            if (isset($goods_name[$goo_va])) {
                                $goods_string[] = $goods_name[$goo_va];
                            } else {
                                $goods_string[] = $goods_name[13];
                            }
                        }
                        $shop_data['shop_service_scope'] = implode(',',$goods_string);
                    }else{
                        $shop_data['shop_service_scope'] = '';
                    }
                    $shop_data['service_id'] = '';
                    if (isset($input['password'])) {
                        $shop_data['password'] = $input['password'];
                    }
                    if ($find_settle->inv_code) {//邀请码邀请来的
                        $find_fshop = DB::table('shop')
                            ->where('shop_code', $find_settle->inv_shop_code)
                            ->first();
                        $find_shic_data = DB::table('shop_invitate_code_config')
                            ->where('shic_code', $find_settle->inv_code)
                            ->first();
                        $shop_data['shop_invitation_config_price'] = $find_shic_data->shic_discount_price;
                        $shop_data['shop_invitation_time_long'] = $find_shic_data->shic_invitation_time_long;
                        $shop_data['shop_invitation_time_type'] = $find_shic_data->shic_invitation_time_type;
                        $shop_data['shop_gift_time'] = $find_shic_data->shic_gift_time;
                    } else {
                        $shop_data['shop_invitation_config_price'] = 0;
                        $shop_data['shop_invitation_time_long'] = 3;
                        $shop_data['shop_invitation_time_type'] = 3;
                        $shop_data['shop_gift_time'] = 3;
                    }
                    $ret = SettleInService::createAccount($shop_data,'pc');
                    if($ret['code'] != 200){
                        return response()->json(["code"=>500,'msg'=>$ret['msg'],'data'=>'']);
                    }
                    //如果账号存在，升级权限
                    $adm_phone = DB::table('admin_shop_role')
                        ->where('phone', $find_settle['phone'])
                        ->where('shop_id', $ret['data'])
                        ->first();
                    
                    $role_id = $adm_phone->role_id;

                    $adm_role = DB::table('role')
                        ->where('rol_id', $role_id)
                        ->first();
                    $role = json_decode($adm_role->rol_privilege_multiple,true);
                    if($role['pc'] == ''){
                        $applet_role = DB::table('privileges_technician_applet')
                            ->whereRaw("FIND_IN_SET('2', pri_default)")
                            ->get()->toArray();
                        $app_role = '';
                        if($applet_role){
                            foreach ($applet_role as $app_r_key => $app_r_value){
                                $app_role_arr[] = $app_r_value->pri_id;
                            }
                            $app_role = implode(',',$app_role_arr);
                        }
                        //$role['pc'] = '2,587,590,591,592,594,595,691,692,695,707,588,634,636,637,638,639,666,693,69,70,71,72,73,74,75,76,344,472,577,578,579,581,709,194,196,237,498,499,53,66,67,68,157,158,161,687,688,684,685,686,689,690,697,698,699,701,702,703,704,705,706,29,3,4,5,7,8,198,484,557,23,24,25,26,27,28,30,31,32,33,34,181,694,710,35,36,38,39,40,41,512,42,43,44,45,46,213,620,621,622,623,624,23,24,25,26,27,28,3,4,5,7,8,198,343,484,557,559,576,610,611,612,613,614,620,621,622,623,624,625,626,627,628,629,30,31,32,33,34,181,651,665,694,710,42,43,44,45,46,213,36,38,39,40,41,512';
                        //$role['pc'] = '2,587,589,590,591,592,593,594,595,663,668,691,692,695,707,588,634,635,636,637,638,639,666,693,696,640,641,642,643,644,645,646,647,683,69,70,71,72,73,74,75,76,344,577,578,579,581,156,159,160,194,196,237,398,399,400,403,404,459,460,465,470,409,410,411,498,499,355,654,655,672,53,60,61,62,63,64,66,67,68,687,688,107,108,109,110,111,684,685,686,689,690,697,698,699,701,702,703,704,705,706,29,3,4,5,7,8,198,484,557,23,24,25,26,27,28,30,31,32,33,34,181,665,694,35,36,38,39,40,41,512,42,43,44,45,46,213,610,611,612,613,614,620,621,622,623,624,625,626,627,628,629,709,710,615,616,617,618,619,604,605,606,607,608,609,78,79,80,81,82,83,84,85,86,87,346,347,348,349,350,351,354,364,365,391,527,708,345,718,495,719,720,726,727,721,722,723,724,725,715,729,730,731,732,733,734,739,162,163,238,239,241,251,518,521,737,738,736,767,768';
                        $pc_pri = DB::table('privileges')
                            ->where('pri_show', 1)
                            ->whereRaw("FIND_IN_SET('2', pri_shop_version)")
                            ->get()->toArray();
                        $pc_pri_role = '';
                        if($pc_pri){
                            foreach ($pc_pri as $pc_r_key => $pc_r_value){
                                $pc_pri_arr[] = $pc_r_value->pri_id;
                            }
                            $pc_pri_role = implode(',',$pc_pri_arr);
                        }
                        $role['pc'] = $pc_pri_role;
                        // $role['pc'] = '2,587,589,590,591,592,593,594,595,663,668,691,692,695,707,588,630,631,632,633,634,635,636,637,638,639,666,693,696,640,641,642,643,644,645,646,647,683,69,70,71,72,73,74,75,76,344,472,577,578,579,581,156,159,160,194,196,237,398,399,400,403,404,459,460,465,470,409,410,411,498,499,355,654,655,672,53,60,61,62,63,64,66,67,68,687,688,107,108,109,110,111,684,685,686,689,690,697,698,699,701,702,703,704,705,706,29,3,4,5,7,8,198,484,557,23,24,25,26,27,28,30,31,32,33,34,181,665,694,35,36,38,39,40,41,512,42,43,44,45,46,213,610,611,612,613,614,620,621,622,623,624,625,626,627,628,629,709,710,615,616,617,618,619,604,605,606,607,608,609,78,79,80,81,82,83,84,85,86,87,346,347,348,349,350,351,354,364,365,391,527,345,712,713,715,717,718,719,720,721,722,723,724,725,726,727,728,157,162,163,238,239,241,251,518,521,729,730,731,732,733,734,736,737,738,739,740,741,743,744,746,747,748,749,750,751,752,464,753,754,755,756,757,758,759,760,761,762,764,765,766,767,768,769,770,771,772,773,774,775,776,777,778,779,783,784,785,786,787,788,789,790,791,792,793,794,795,796,797,798,799,780,781,782,792,800,801,802,803,814,815,816,817';
                        
                        //$role_update['rol_privilege_multiple'] = '{"pc":"'.$role['pc'].'","applet":"'.$role['applet'].'"}';
                        $role_update['rol_privilege_multiple'] = '{"pc":"'.$role['pc'].'","applet":"'.$app_role.'"}';
                        $weus_res = DB::table('role')
                            ->where("rol_id", $role_id)
                            ->update($role_update);
                        //修改技师权限
                        $applet_role_jishi = DB::table('privileges_technician_applet')
                            ->whereRaw("FIND_IN_SET('3', pri_default)")
                            ->get()->toArray();
                        $app_role_jishi = '';
                        if($applet_role_jishi){
                            foreach ($applet_role_jishi as $app_j_key => $app_j_value){
                                $app_role_jishi_arr[] = $app_j_value->pri_id;
                            }
                            $app_role_jishi = implode(',',$app_role_jishi_arr);
                        }
                        $adm_role_jishi = DB::table('role')
                            ->where('rol_cid', $adm_role->rol_cid)
                            ->where('rol_shop_id', $adm_role->rol_shop_id)
                            ->where('rol_type', 3)
                            ->value('rol_id');
                        $role_update_jishi['rol_privilege_multiple'] = '{"pc":"","applet":"'.$app_role_jishi.'"}';
                        $weus_res = DB::table('role')
                            ->where("rol_id", $adm_role_jishi)
                            ->update($role_update_jishi);
                    }
                    //修改门店来源，多个用逗号隔开
                    $shop_source_identify_arr = [1];
                    $shop_ret = DB::table('shop')->where('shop_id',$ret['data'])->first();
                    if($shop_ret){
                        $shop_source_identify = $shop_ret->shop_source_identify;
                        if(!empty($shop_source_identify)){
                            $shop_source_identify_default = explode(',',$shop_source_identify);
                            $shop_source_identify_arr = array_merge($shop_source_identify_default,$shop_source_identify_arr);
                            $shop_source_identify_arr = array_unique($shop_source_identify_arr);
                        }
                    }
                    $shop_source_identify_new = implode(',',$shop_source_identify_arr);
                    DB::table('settle_in')->where('id',$input['id'])->update(['shop_id'=>$ret['data']]);
                    // DB::table('shop')->where('shop_id',$ret['data'])->update(['shop_opening_type'=>2,'shop_versions'=>2,'shop_source_identify'=>$shop_source_identify_new,'shop_opening_start_time'=>date('Y-m-d H:i:s'),'shop_opening_end_time'=>date('Y-m-d H:i:s',time()+24*7*3600)]);//店铺来源标识
                    if ($find_settle->inv_code) {
                        $find_inv_data = DB::table('shop_invitate_code_config')
                            ->where('shic_code', $find_settle->inv_code)
                            ->first();
                        if ($find_inv_data->shic_invitation_time_type == 1) {
                            $add_times = strtotime('+'.$find_inv_data->shic_invitation_time_long.' day');
                        } elseif ($find_inv_data->shic_invitation_time_type == 2) {
                            $add_times = strtotime('+'.$find_inv_data->shic_invitation_time_long.' week');
                        } elseif ($find_inv_data->shic_invitation_time_type == 3) {
                            $add_times = strtotime('+'.$find_inv_data->shic_invitation_time_long.' month');
                        } elseif ($find_inv_data->shic_invitation_time_type == 4) {
                            $add_times = strtotime('+'.$find_inv_data->shic_invitation_time_long.' year');
                        }
                        DB::table('shop')->where('shop_id',$ret['data'])->update(['shop_message_num'=>200,'shop_free_space'=>5,'shop_shpr_id'=>3,'shop_shve_id'=>2,'shop_opening_type'=>2,'shop_versions'=>2,'shop_source_identify'=>$shop_source_identify_new,'shop_opening_start_time'=>date('Y-m-d H:i:s'),'shop_opening_end_time'=>date('Y-m-d H:i:s',$add_times)]);//店铺来源标识
                    } else {
                        DB::table('shop')->where('shop_id',$ret['data'])->update(['shop_message_num'=>200,'shop_free_space'=>5,'shop_shpr_id'=>3,'shop_shve_id'=>2,'shop_opening_type'=>2,'shop_versions'=>2,'shop_source_identify'=>$shop_source_identify_new,'shop_opening_start_time'=>date('Y-m-d H:i:s'),'shop_opening_end_time'=>date('Y-m-d H:i:s',strtotime('+3 month'))]);//店铺来源标识
                    }
                }
                DB::commit();
                // Common::addLog($user_info, $input['ip'], '入驻管理','跟进进度','跟进进度：'.'成功');
                return response()->json(["code"=>200,'msg'=>'操作成功','data'=>'']);
            }else{
                DB::rollback();
                return response()->json(["code"=>500,'msg'=>'操作失败1','data'=>'']);
            }
        }


    }

    /*
     * @name 创建账号
     * @param string ju_ordernum 订单单号
     * @retrun array
     * @author Ma 2023/7/6 9:03
     *
    */
    public function createAcc($input){
        $message = [
            'id' => '入驻信息ID',
            'shop_store_name.required'=> '门店不能为空',
            'shop_store_name.unique'=> '门店名已存在',
            'shop_phone.required'=> '电话不能为空',
            'shop_phone.unique'=> '电话已存在',
            'shop_phone.regex'=> '电话号码不正确',
            'shop_name.required'=> '姓名不能为空',
            'shop_address.required'=> '地址不能为空',
            'goods_ids.required'=> '服务项目不能为空',
            'shop_password' => '密码不能为空',
            'shop_password.max'=> '登录密码长度不能超过15个字符',
            'shop_password.min'=> '登录密码长度不得小于6个字符',
        ];
        $rules = [
            'id' => 'required',
            'shop_name' =>'required|unique:shop,shop_store_name',
            'shop_phone' =>'required|unique:admin,shop_phone',
            'shop_phone' =>['regex:/^[1](([3][0-9])|([4][5-9])|([5][0-3,5-9])|([6][5,6])|([7][0-8])|([8][0-9])|([9][1,8,9]))[0-9]{8}$/'],
            'shop_address'=>'required',
            'goods_ids'=>'required',
            //'shop_password'=>'required',
            'shop_password' => 'required|string|min:6|max:15',
        ];

        $Validator = Validator::make($input,$rules,$message);
        if($Validator->fails()){
            return response()->json(['data'=>'','code'=>1003, 'msg'=>$Validator->errors()->first()]);exit;
        }
        return self::createAccount($input);
    }

    /**
     * @name 详情
     * @param $input
     * @return mixed
     * @author du
     * @date 2023/5/18
     * @Time: 11:39
     */
    public static function getInfo($input)
    {
        if (isset($input['phone'])) {
            $find_meca = SettleIn::where('phone', $input['phone'])->first();
        }
        if(isset($input['id'])){
            $find_meca = SettleIn::where('id', $input['id'])->first();
        }
        // 信息
        if($find_meca){
            $status_names = self::getSettleStatus();
            $find_meca['status_name'] = $status_names[$find_meca['status']];
            $wordshop_types = self::getSettleWorkshop();
            $find_meca['wordshop_name'] = $wordshop_types[$find_meca['workshop']];
            $wash_cars = self::getSettleWashCar();
            $find_meca['wash_car_name'] = $wash_cars[$find_meca['can_wash_car']];
            $pay_types = self::getPayType();
            $find_meca['payment_method_name'] = $pay_types[$find_meca['payment_method']];
            $ad_brands = self::getAdBrandsName(true);
            $data = explode(',', $find_meca['brands']);
            $brands = [];
            foreach ($data as $k => $v) {
                if(isset($ad_brands[$v])){
                    $brands[$k] = $ad_brands[$v];
                }
            }
            $find_meca['ad_brands_name'] = $brands;

            $goods_idsnames = self::getTypeName('all',true);
            $data = explode(',', $find_meca['goods_ids']);
            $goods = [];
            foreach ($data as $k => $v) {
                if(isset($goods_idsnames[$v])){
                    $goods[$k] = $goods_idsnames[$v];
                }
            }
            $find_meca['goods_name'] = $goods;
            //获取同盟信息
            $find_meca['information'] = [];
            $information_type = self::getSettleTypeName(true);
            $information_status = self::getSettleTypeStatus(true);
            $find_information = DB::table('settle_sync_information')->where('settle_in_id',$input['id'])->get()->toArray();
            if($find_information){
                foreach ($find_information as $key => $value){
                    $find_information[$key]->type_name = $information_type[$value->type];
                    $find_information[$key]->status_name = '待审核';
                    if(in_array($value->info_status,[1,2,3])){
                        $find_information[$key]->status_name = $information_status[$value->info_status];
                    }
                }
            }
            $find_meca['information'] = $find_information;


            return response()->json(['code'=> 200, 'msg'=>'获取成功', 'data'=>$find_meca]);
        }else{
            return response()->json(['code'=> 500, 'msg'=>'暂无数据', 'data'=>'']);
        }

    }

    /**
     * @name 创建账号和门店
     * @param $input
     * @return array|\Illuminate\Http\JsonResponse
     * @author du
     * @date 2023/5/19
     * @Time: 14:22
     */
    public static function createAccount($input,$type = NULL){
        $shop = true;
        if ($input['shop_phone']) {
            $store_ret = DB::table('shop')
                ->where('shop_phone',$input['shop_phone'])
                ->first();
            // 判断手机号是否是店长
            $adm_phone = DB::table('admin_shop_role')
                ->where('phone', $input['shop_phone'])
                ->where('adm_shop_leave', 1)
                ->first();
            if (!empty($adm_phone)) {
                $shre_id = DB::table('shop_relevance')
                    ->where("shre_relevance_shop_id",$input['service_id'])
                    ->where("shre_shop_id",$adm_phone->shop_id)
                    ->value('shre_id');
                if(empty($shre_id)) {
                    // 查询绑定关系表 是否绑定
                    $sarr['shre_relevance_shop_id'] = $input['service_id'];
                    $sarr['shre_shop_id'] = $adm_phone->shop_id;
                    $sarr['shre_relevance_type'] = 1;
                    $sarr['shre_state'] = 2;
                    DB::table('shop_relevance')->insert($sarr);
                }
                if ($store_ret) {
                    if ($store_ret->shop_source_identify == 5) {
                        $update_shop['shop_opening_start_time'] = date('Y-m-d H:i:s');
                        $update_shop['shop_opening_end_time'] = date('Y-m-d H:i:s',time()+24*365*2*3600);
                        $update_shop['shop_shpr_id'] = 3;
                        $update_shop['shop_shve_id'] = 2;
                        $update_shop['shop_source_identify'] = '1,5';
                        $shop_id = $store_ret->shop_id;
                        $update_shop_res = DB::table('shop')
                            ->where('shop_id', $shop_id)
                            ->update($update_shop);
                        $find_pc_pri = DB::table('privileges')
                            ->where('pri_shop_version', 'like', '%'.'2'.'%')
                            ->where('pri_show', 1)
                            ->select('pri_id')
                            ->get()->toArray();

                        $pc_pri = array_column($find_pc_pri, 'pri_id');

                        $find_applet_pri = DB::table('privileges_technician_applet')
                            ->where('pri_shop_version', 'like', '%'.'3'.'%')//企业版
                            ->where('pri_default', 'like', '%'.'2'.'%')//自家管理
                            ->where('pri_show', 1)
                            ->select('pri_id')
                            ->get()->toArray();

                        $applet_pri = array_column($find_applet_pri, 'pri_id');
                        $data_role['pc'] = implode(',',$pc_pri);
                        $data_role['applet'] = implode(',',$applet_pri);
                        $new_data = json_encode($data_role, true);
                        $update_role['rol_privilege_multiple'] = $new_data;
                        $update_role_res = DB::table('role')
                            ->where('rol_shop_id', $shop_id)
                            ->where('rol_type', 1)
                            ->update($update_role);
                        $app_data_role['pc'] = '';
                        $app_data_role['applet'] = implode(',',$applet_pri);
                        $new_app_data = json_encode($app_data_role, true);
                        $update_app_role['rol_privilege_multiple'] = $new_app_data;
                        $update_app_role_res = DB::table('role')
                            ->where('rol_shop_id', $shop_id)
                            ->where('rol_type', 3)
                            ->update($update_app_role);
                        DB::commit();
                        return ['code'=>200, 'msg'=>'门店创建成功', 'data'=>$shop_id];
                    }
                }
                return ['code'=>300, 'msg'=>'该手机号已是店长', 'data'=>'新增失败'];
            }
        } else {
            $store_ret = DB::table('shop')
                ->where('shop_adm_account',$input['adm_account'])
                ->first();
        }

        if ($store_ret) {
            $shop = false;//店铺存在，不需要创建
            $shop_id = $store_ret->shop_id;
            //return response()->json(['code'=>500, 'msg'=>'加盟店名称已存在', 'data'=>'']);
            $shop_source_identify_old = $store_ret->shop_source_identify;//现在的shop的来源
            if($type == 'pc'){
                $new_identify = [1];
            }else{
                $new_identify = [5];
            }
            $identify_arr = [];
            if(isset($shop_source_identify_old) && !empty($shop_source_identify_old)){
                $identify_arr = explode(",", $shop_source_identify_old);
            }
            $all_identify = array_merge($identify_arr,$new_identify);
            $identify = implode(",", array_unique($all_identify));
            //修改图片
            if((empty($store_ret->shop_image) || $store_ret->shop_image == config('apisystem.server_name_https') .'/image/pcImg/shop_default_img.png') && isset($input['shop_image'])){
                $shop_update['shop_image'] = $input['shop_image'];
            }
            $shop_update['shop_source_identify'] = $identify;
            DB::table('shop')->where('shop_id',$shop_id)->update($shop_update);//修改店铺来源
        }

//        if($admin == false && $shop == false){
//            return ['code'=>200, 'msg'=>'门店创建成功1', 'data'=>$shop_id];
//        }

        // 获取当前操作账号信息
        $input['api_token'] = $input['api_token']??'';
        $user_info = Common::getUserInfo($input['api_token'])??'';
        DB::beginTransaction();
        //改变状态
        /*$input['id'] = $input['id'];
        $input['status'] = 4;
        $input['remark'] = '';
        $input['type'] = 2;
        $input['ip'] = $_SERVER["REMOTE_ADDR"];
        $input['status_type'] = 1;
        self::editSchedule($input);*/
        /*$phone = DB::table('settle_in')->where('id',$input['id'])->value('phone');
        if($input['shop_phone']!=$phone){
            DB::table('settle_in')->where('id',$input['id'])->update(['phone'=>$input['shop_phone']]);
        }
        $charge_name = DB::table('settle_in')->where('id',$input['id'])->value('charge_name');
        if($input['shop_name']!=$charge_name){
            DB::table('settle_in')->where('id',$input['id'])->update(['charge_name'=>$input['shop_name']]);
        }*/
        if($shop){
            $shop_add_data = [
                'shop_cid'=>1,
                'shop_store_name'=>$input['shop_store_name'],
                'shop_name'=>$input['shop_name'],
                'shop_phone'=>$input['shop_phone'],
                'shop_adm_id'=>0,
                'shop_province'=>$input['shop_province']??'',
                'shop_city'=>$input['shop_city']??'',
                'shop_county'=>$input['shop_county']??'',
                'shop_address'=>$input['shop_address'],
                'shop_source_identify'=>5,//门店来源标识：1门店系统2半径小供应链3冠军供应链4中凯供应链 5入驻
                'shop_type'=>3,
                'shop_versions'=>2,
                'shop_image'=>$input['shop_image']??'',
                'shop_opening_time'=>$input['shop_opening_time']??'',
                'shop_longitude'=>$input['shop_longitude']??'',
                'shop_latitude'=>$input['shop_latitude']??'',
                'shop_service_scope'=>$input['shop_service_scope']??'',
                'shop_message_num'=>200,
                'shop_adm_account'=>$input['adm_account']??'',
                'shop_code' => 'S' . substr(time(),5,5)  . rand(10000, 99999),//门店编码
                'shop_invitation_config_price'=>$input['shop_invitation_config_price']??'',
                'shop_invitation_time_long'=>$input['shop_invitation_time_long']??'',
                'shop_invitation_time_type'=>$input['shop_invitation_time_type']??'',
                'shop_gift_time'=>$input['shop_gift_time']??'',
            ];
            if($type == 'pc'){
                $shop_add_data['shop_source_identify'] = '1';
            }else{
                $shop_add_data['shop_source_identify'] = '5';
            }
            // 新增加盟店
            $shop_id =  DB::table('shop')->insertGetId($shop_add_data);
             ShopService::addFestival($shop_id);
        }
        $applet_role = DB::table('privileges_technician_applet')
            ->whereRaw("FIND_IN_SET('4', pri_default)")//三方管理
            ->get()->toArray();
        $app_role = '';
        if($applet_role){
            foreach ($applet_role as $app_r_key => $app_r_value){
                $app_role_arr[] = $app_r_value->pri_id;
            }
            $app_role = implode(',',$app_role_arr);
        }
        $role_add_data = [
            'rol_cid'=>1,
            'rol_shop_id'=>$shop_id,
            'rol_type'=>1,
            'rol_name'=>'总管理',
            'rol_privilege_multiple'=> '{"pc":"","applet":"'.$app_role.'"}',//9,10,11,12,13,14,15,16,17,20,21,23,24,25,26,27,28,29,30,31
            'rol_privilege'=>config('apisystem.franchisee_shop'),
            'rol_creator_id'=>$user_info->adm_id??''
        ];
        // 新增角色
        $role_id =  DB::table('role')->insertGetId($role_add_data);
        $js_applet_role = DB::table('privileges_technician_applet')
            ->whereRaw("FIND_IN_SET('5', pri_default)")
            ->get()->toArray();
        $js_app_role = '';
        if($js_applet_role){
            foreach ($js_applet_role as $js_app_r_key => $js_app_r_value){
                $js_app_role_arr[] = $js_app_r_value->pri_id;
            }
            $js_app_role = implode(',',$js_app_role_arr);
        }
        $js_role_add_data = [
            'rol_cid'=>1,
            'rol_shop_id'=>$shop_id,
            'rol_type'=>3,
            'rol_name'=>'技师管理',
            'rol_privilege_multiple'=> '{"pc":"","applet":"'.$js_app_role.'"}',//13,14,15,16,25,26,27,28,29,30,31
            'rol_privilege'=>config('apisystem.franchisee_shop'),
            'rol_creator_id'=>$user_info->adm_id??''
        ];
        // 新增角色
        $js_role_id =  DB::table('role')->insertGetId($js_role_add_data);
        if (isset($input['password']) && $input['password']) {
            $word = $input['password'];
        } else {
            $word = substr($input['shop_phone'], 0,6);
        }
        if ($input['shop_phone']) {
            $adm_id = DB::table('admin')
                ->where('adm_phone', $input['shop_phone'])
                ->value('adm_id');
        } elseif ($input['adm_account']) {
            $adm_id = DB::table('admin')
                ->where('adm_account', $input['adm_account'])
                ->value('adm_id');
        }
        if(empty($adm_id)) {
            $admin_add_data = [
                'adm_cid'=>1,
                'adm_superior_shop_id'=>$shop_id,
                'adm_shop_id'=>$shop_id,
                'adm_leave'=>1,
                'adm_remind'=>1,
                'adm_phone'=>$input['shop_phone'],
                'adm_account'=>$input['adm_account'] ? $input['adm_account'] : 'os'.date('Ymd').substr(implode(NULL,array_map('ord',str_split(substr(uniqid(), 7, 13), 1))), 0, 8),//$input['adm_account']??$input['shop_name'],
                'adm_password'=>md5($word.'faster123456'),
                'adm_name'=>$input['shop_adm_name'],
                'adm_role'=>$role_id,
                'adm_creator_id'=>$user_info->adm_id??''
            ];
            // 新增账号
            $adm_id =  DB::table('admin')->insertGetId($admin_add_data);
        } else {
            if (isset($input['password']) && $input['password']) {
                $password = md5($word.'faster123456');
                DB::table('admin')->where('adm_id', $adm_id)->update(['adm_password'=>$password]);
            }
        }
        //新增账号门店权限关系表
        $insertAdminShopRoleData = [
            'adm_id' => $adm_id,
            'shop_cid' => 1,
            'superior_shop_id' => $shop_id,
            'shop_id' => $shop_id,
            'role_id' => $role_id,
            'adm_shop_leave' => 1,
            'login_shop' => 2,
            'phone' => $input['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')->insert($insertAdminShopRoleData);

        //修改店铺的admin_id
        $adms_res = DB::table('shop')->where('shop_id', $shop_id)->update(['shop_adm_id'=>$adm_id]);
        // 添加默认仓库分类
        $warehouse_class = config('apisystem.warehouse_class');
        foreach ($warehouse_class as $key => $value) {
            $warehouse_class[$key]['wacl_superior_shop_id'] = $shop_id;
            $warehouse_class[$key]['wacl_shop_id'] = $shop_id;
            $warehouse_class[$key]['wacl_cid'] = 1;
        }
        $class_res = DB::table('warehouse_class')->insert($warehouse_class);

        //如果是type = pc，需要创建默认仓库
        //if($type == 'pc'){
            // 新增仓库
            $ware_add_data = [
                'ware_cid' => 1,
                'ware_shop_id' => $shop_id,
                'ware_superior_shop_id' => $shop_id,
                'ware_name' => '默认仓库',
                'ware_type' => 1,
                'ware_default' => 2,
                'ware_leader_id' => $adm_id,
                'ware_address' => '',
                'ware_license' => '',
                'ware_freight_space' => '',
            ];
            $ware_res_id =  DB::table('warehouse')->insertGetId($ware_add_data);
            // 判断admin_set表中是否有 该员工的设置
            $adm_set = DB::table('admin_set')
                ->where('adms_adm_id', $adm_id)
                ->where('adms_shop_id', $shop_id)
                ->select('adms_id', 'adms_ware_id', 'adms_ware_ids', 'adms_myware_id')
                ->first();
            if ($adm_set) {
                $adms_data['adms_ware_id'] = $adm_set->adms_ware_id.','.$ware_res_id; //所绑定的仓库信息
                $adms_data['adms_ware_ids'] = $adm_set->adms_ware_ids.','.$ware_res_id; //仓库操作权限
                $adms_data['adms_myware_id'] = $adm_set->adms_myware_id.','.$ware_res_id; //我的仓库-仓库查看及相关操作权限
                $adms_data['adms_update_time'] = date('Y-m-d H:i:s'); //更新时间
                // 有该员工的设置编辑
                $adms_res = DB::table('admin_set')
                    ->where('adms_id', $adm_set->adms_id)
                    ->update($adms_data);
            } else {
                $adms_data['adms_ware_id'] = $ware_res_id; //所绑定的仓库信息
                $adms_data['adms_ware_ids'] = $ware_res_id; //仓库操作权限
                $adms_data['adms_myware_id'] = $ware_res_id; //我的仓库-仓库查看及相关操作权限
                $adms_data['adms_update_time'] = date('Y-m-d H:i:s'); //更新时间
                // 没有该员工的设置新增
                $adms_data['adms_adm_id'] = $adm_id; //员工id
                $adms_data['adms_shop_id'] = $shop_id;
                $adms_data['adms_province'] = $input['shop_province']??'';
                $adms_data['adms_city'] = $input['shop_city']??'';
                $adms_data['adms_county'] = $input['shop_county']??'';
                $adms_data['adms_address'] = $input['shop_address'];
                $adms_data['adms_update_time'] = date('Y-m-d H:i:s');
                $adms_res = DB::table('admin_set')->insert($adms_data);
            }
            // 新增仓库类别数据
            $waon_class = config('apisystem.WAREHOUSE_CLASS'); //  仓库类别：1货物仓2非货物仓3旧货仓4临时仓
            foreach ($waon_class as $key => $value) {
                $waon_data[$key]['waon_ware_id'] = $ware_res_id;
                $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);

            // 新增默认仓位
            $freight_data['wafr_shop_id'] = $shop_id; //仓位隶属门店id
            $freight_data['wafr_ware_id'] = $ware_res_id; //仓位隶属仓库id
            $freight_data['wafr_parent_id'] = 0; //仓位隶属上级id
            $freight_data['wafr_rank'] = 1; //仓位级别，第几级
            $freight_data['wafr_name'] = '默认仓位'; //仓位名称
            $freight_data['wafr_delete'] = 1; //是否删除1否2是
            $freight_data['wafr_first_parent_id'] = 0; //仓位所属一级id
            $wafr_id = DB::table('warehouse_freight')->insertGetId($freight_data);

            /*}else{
            //新增admin_set
        $admin_set_data = [
            'adms_adm_id'=>$adm_id,
            'adms_shop_id'=>$shop_id,
            'adms_province'=>$input['shop_province']??'',
            'adms_city'=>$input['shop_city']??'',
            'adms_county'=>$input['shop_county']??'',
            'adms_address'=>$input['shop_address'],
            'adms_update_time'=>date('Y-m-d H:i:s'),
        ];
        $adm_set =  DB::table('admin_set')->insertGetId($admin_set_data);
        }*/

        //新增一个异常数据
        $vacm_add_data = [
            'vacm_cid'=>$user_info->adm_cid??'',
            'vacm_shop_id'=>$shop_id,
            'vacm_superior_shop_id'=>$shop_id,
        ];
        $vacm_add_data['vacm_type'] = 1;
        // 新增异常数据

        $vacm_add_data['vacm_unusual_name'] = '仪表异常 （有故障码）';
        $vacm_res =  DB::table('wash_validate_car_manage')->insert($vacm_add_data);
        $vacm_add_data['vacm_unusual_name'] = '车内照明灯异常';
        $vacm_res =  DB::table('wash_validate_car_manage')->insert($vacm_add_data);
        $vacm_add_data['vacm_unusual_name'] = '车内缺点烟器';
        $vacm_res =  DB::table('wash_validate_car_manage')->insert($vacm_add_data);
        $vacm_add_data['vacm_unusual_name'] = '电动天窗异常';
        $vacm_res =  DB::table('wash_validate_car_manage')->insert($vacm_add_data);
        $vacm_add_data['vacm_unusual_name'] = '电动座椅异常';
        $vacm_res =  DB::table('wash_validate_car_manage')->insert($vacm_add_data);

        $vacm_add_data['vacm_type'] = 2;
        $vacm_add_data['vacm_unusual_name'] = '车头、侧身等灯具类破损或异常';
        $vacm_res =  DB::table('wash_validate_car_manage')->insert($vacm_add_data);
        $vacm_add_data['vacm_unusual_name'] = '车标、格栅、装饰条破损或损坏';
        $vacm_res =  DB::table('wash_validate_car_manage')->insert($vacm_add_data);
        $vacm_add_data['vacm_unusual_name'] = '胶皮密封条破损或异常';
        $vacm_res =  DB::table('wash_validate_car_manage')->insert($vacm_add_data);
        $vacm_add_data['vacm_unusual_name'] = '装饰件破损或异常';
        $vacm_res =  DB::table('wash_validate_car_manage')->insert($vacm_add_data);
        $date = date("Y-m-d H:i:s");
        // 新增质检数据
        $reward_punishment = [
            [
                'qurp_cid'=>$user_info->adm_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'=>$user_info->adm_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'=>$user_info->adm_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_id = DB::table('wash_quality_reward_punishment')->insert($reward_punishment);


        /*if(isset($input['goods_ids']) && !empty($input['goods_ids'])){

            $goodsids = explode(',',$input['goods_ids']);
            $service_scope = DB::table('service_scope')->whereIn('sesc_id',$goodsids)->get()->toarray();
            // 品类数据
            $cate_add_data['cate_cid'] = 1;
            $cate_add_data['cate_shop_id'] = $shop_id;
            $cate_add_data['cate_superior_shop_id'] = $shop_id;
            $cate_add_data['cate_parent_id'] = 0;
            $cate_add_data['cate_rank'] = 1;

            $caco['caco_shop_id'] = $shop_id;
            // 商品数据
            $goo_add_data['goo_cid'] = 1;
            $goo_add_data['goo_shop_id'] = $shop_id;
            $goo_add_data['goo_superior_shop_id'] = $shop_id;

            $goo_add_data['goo_type'] = 1;   //1正常商品2赠品商品3活动商品4旧货商品5无库存商品
            $goo_add_data['goo_goods_code'] = '';   //商品编号
            $goo_add_data['goo_goods_encode'] = '';   //检索编码
            $goo_add_data['goo_price'] = 100;   //商品零售价格
            $goo_add_data['goo_wholesale_price'] = 100;   //批发价
            $goo_add_data['goo_purchase_price'] = 100; //采购价
            $goo_add_data['goo_assign_state'] = $input['goo_assign_state']?? 1; //商品派单状态：1不允许派单2允许派单
            $goo_add_data['goo_system_code'] = str_pad(1, '4', '0', STR_PAD_RIGHT) . str_pad($shop_id, '5', '0', STR_PAD_RIGHT) . rand(10, 99) . rand(100000000, 999999999); //系统编码
            $goo_add_data['goo_unta_id'] = 3; //商品单位id
            $goo_add_data['goo_unit_conversion'] = ''; //商品单位换算每卷多少米
            $goo_add_data['goo_unit'] = '个'; //商品单位名称
            $goo_add_data['goo_commodity_propert'] = 1; //商品属性：1成品2原材料
            // 2 新增一个品类数据
            $cate_add_data['cate_name'] = '试用品类';
            $cate_res =  DB::table('category')->insertGetid($cate_add_data);
            $caco['caco_cate_id'] = $cate_res;
            $caco_res = DB::table('category_correlation')->insert($caco);
            // 2 新增一个商品数据
            $goo_add_data['goo_cate_id'] = $cate_res; //所属品类id
            $goo_add_data['goo_cate_name'] = '试用品类'; //品类名称

            // 2 新增一个服务项目数据
            $sepr_add_data = [
                'sepr_cid'=>1,
                'sepr_shop_id'=>$shop_id,
                'sepr_superior_shop_id'=>$shop_id,
                'sepr_money'=>100,
                'sepr_order_money'=>100,
                'sepr_order_type'=>1,
                'sepr_check_car'=>1,
                'sepr_sort'=>$input['sepr_sort']?? 0,
                'sepr_show_location'=>$input['sepr_show_location']??0,//显示位置
                'sepr_work_type'=>1,//流程分类1有工单2不生成工单
                'sepr_img'=>config('apisystem.server_name_https').'/storage/image/default_goo_img.png',
            ];
            $sepr_add_data['sepr_name'] = '试用服务';
            $goo_add_data['goo_name'] = '试用商品';
            // 新增服务项目
            $sepr_res =  DB::table('service_project')->insert($sepr_add_data);
            // 新增商品
            $goo_id =  DB::table('goods')->insertGetId($goo_add_data);
        } else {
            // 品类数据
            $cate_add_data['cate_cid'] = 1;
            $cate_add_data['cate_shop_id'] = $shop_id;
            $cate_add_data['cate_superior_shop_id'] = $shop_id;
            $cate_add_data['cate_parent_id'] = 0;
            $cate_add_data['cate_rank'] = 1;

            $caco['caco_shop_id'] = $shop_id;
            // 商品数据
            $goo_add_data['goo_cid'] = 1;
            $goo_add_data['goo_shop_id'] = $shop_id;
            $goo_add_data['goo_superior_shop_id'] = $shop_id;

            $goo_add_data['goo_type'] = 1;   //1正常商品2赠品商品3活动商品4旧货商品5无库存商品
            $goo_add_data['goo_goods_code'] = '';   //商品编号
            $goo_add_data['goo_goods_encode'] = '';   //检索编码
            $goo_add_data['goo_price'] = 100;   //商品零售价格
            $goo_add_data['goo_wholesale_price'] = 100;   //批发价
            $goo_add_data['goo_purchase_price'] = 100; //采购价
            $goo_add_data['goo_assign_state'] = $input['goo_assign_state']?? 1; //商品派单状态：1不允许派单2允许派单
            $goo_add_data['goo_system_code'] = str_pad(1, '4', '0', STR_PAD_RIGHT) . str_pad($shop_id, '5', '0', STR_PAD_RIGHT) . rand(10, 99) . rand(100000000, 999999999); //系统编码
            $goo_add_data['goo_unta_id'] = 3; //商品单位id
            $goo_add_data['goo_unit_conversion'] = ''; //商品单位换算每卷多少米
            $goo_add_data['goo_unit'] = '个'; //商品单位名称
            $goo_add_data['goo_commodity_propert'] = 1; //商品属性：1成品2原材料
            // 2 新增一个品类数据
            $cate_add_data['cate_name'] = '试用品类';
            $cate_res =  DB::table('category')->insertGetid($cate_add_data);
            $caco['caco_cate_id'] = $cate_res;
            $caco_res = DB::table('category_correlation')->insert($caco);
            // 2 新增一个商品数据
            $goo_add_data['goo_cate_id'] = $cate_res; //所属品类id
            $goo_add_data['goo_cate_name'] = '试用品类'; //品类名称

            // 2 新增一个服务项目数据
            $sepr_add_data = [
                'sepr_cid'=>1,
                'sepr_shop_id'=>$shop_id,
                'sepr_superior_shop_id'=>$shop_id,
                'sepr_money'=>100,
                'sepr_order_money'=>100,
                'sepr_order_type'=>1,
                'sepr_check_car'=>1,
                'sepr_sort'=>$input['sepr_sort']?? 0,
                'sepr_show_location'=>$input['sepr_show_location']??0,//显示位置
                'sepr_work_type'=>1,//流程分类1有工单2不生成工单
                'sepr_img'=>config('apisystem.server_name_https').'/storage/image/default_goo_img.png',
            ];
            $sepr_add_data['sepr_name'] = '试用服务';
            $goo_add_data['goo_name'] = '试用商品';
            // 新增服务项目
            $sepr_res =  DB::table('service_project')->insert($sepr_add_data);
            // 新增商品
            $goo_id =  DB::table('goods')->insertGetId($goo_add_data);
        }*/
        $add_data['msco_shop_id'] = $shop_id;
        $add_data['msco_is_send'] = 1;
        $add_data['msco_send_detail'] = 5;
        $add_data['msco_update_id'] = $user_info->adm_id??'';
        $add_data['msco_update_time'] = date('Y-m-d H:i:s');
        $add_res = DB::table('msg_config')->insert($add_data);
        if ($shop_id && $class_res && $admin_shop_role_id) {
            DB::commit();
            return ['code'=>200, 'msg'=>'门店创建成功', 'data'=>$shop_id];
        } else {
            DB::rollback();
            return ['code'=>500, 'msg'=>'门店创建失败', 'data'=>'新增失败'];
        }
    }

    /**
     * @name 获取最后一条审核信息
     * @param $input
     * @return \Illuminate\Http\JsonResponse
     * @author du
     * @date 2023/5/19
     * @Time: 10:29
     */
    public static function getScheduleinfo($input){
        // 验证数据
        $id = '';
        $reason = '';
        if(isset($input['phone'])){//公众号有phone参数，通过手机号查找id
            $id = SettleIn::where('phone',$input['phone'])->value('id');
        }else{//美装小程序
            //如果有店铺id
            if(isset($input['shop_id'])){
                $find_ret = SettleIn::where('shop_id', $input['shop_id'])->value('id');//申请入驻的信息
                if($find_ret){
                    $id = $find_ret;
                }else{
                    //查找店铺信息
                    $store_ret = DB::table('shop')
                        ->where('shop_id',$input['shop_id'])
                        ->select('shop_id', 'shop_store_name as shop_name', 'shop_phone as phone', 'shop_name as charge_name','shop_province','shop_city','shop_county','shop_address as address','shop_longitude as longitude','shop_latitude as latitude')
                        ->first();
                    if ($store_ret) {
                        $store_ret_arr = CommonService::dataToArray($store_ret);
                        $data['data'] = $store_ret_arr;
                        $data['data']['platform'] = '';
                        $data['log'] = '';
                        return response()->json(['code'=> 200, 'msg'=>'获取成功1', 'data'=>$data]);
                    }
                }
            }else{
                if (!isset($input['open_id'])) {
                    return response()->json(['code'=> 500, 'msg'=>'参数错误', 'data'=>'']);
                }
                if(isset($input['api_token'])){
                    $user_info = Common::wechatGetUserInfo($input['api_token']);
                }
                if(isset($user_info)){
                    $id = SettleIn::where('shop_id',$user_info->adm_shop_id)->value('id');
                }else{

                    $all_data = DB::table('settle_in as si')
                        ->leftJoin('settle_sync_information as o', 'si.id', '=', 'o.settle_in_id')
                        ->where('open_id', $input['open_id'])
                        ->where('shop_id', 0)
                        ->select('si.id', 'status', 'info_status', 'submit_end' ,'remark')
                        ->orderBy('si.id','desc')
                        ->get();
                    //$all_data = SettleIn::where('open_id', $input['open_id'])->orderBy('id','desc')->get()->toArray();
                    if($all_data){
                        $submit_id = 0;
                        foreach ($all_data as $ke => $va){
                            if($va->submit_end == 1){//未完成提交的
                                $submit_id = $va->id;
                            }else if(($va->status == 5 && ($va->info_status == 1 || $va->info_status == 3)) || ($va->status == 5 && $va->info_status == NULL )){
                                $no_id =  $va->id;
                                $reason_ret = DB::table('settle_in_schedule')
                                    ->where('s_status', 5)
                                    ->orderBy('id','desc')
                                    ->first();
                                $reason = $reason_ret->remark;
                            }else if( $va->info_status == 3 && $va->status != 4){
                                $no_id =  $va->id;
                                $reason = $va->remark;
                            }
                        }
                        if(!empty($submit_id)){
                            $id = $submit_id;
                        }else if(!empty($no_id)){
                            //如果是驳回的，修改step = 1
                            $se_ret = DB::table('settle_in')->where('id',$no_id)->update(['step'=>0]);//更新步骤
                            $id = $no_id;
                        }else{
                            $id = '';
                        }
                    }else{
                        $id = SettleIn::where('open_id', $input['open_id'])->where('status', 5)->value('id');
                    }
                }
            }

        }
        //$id = SettleIn::where('open_id',$input['open_id'])->value('id');
        $status_names = self::getSettleStatus();
        if(empty($id)){
            return response()->json(['code'=> 200, 'msg'=>'暂无数据', 'data'=>'']);
        }
        $find_ret = SettleIn::where('id', $id)->orderBy('id','desc')->first()->toArray();
        $log_ret = SettleInSchedule::where('settle_in_id', $id)->orderBy('id','desc')->get()->toArray();
        $information_ret = SettleInSyncInformation::where('settle_in_id', $id)->orderBy('id','desc')->get()->toArray();//同步信息
        $data['data'] = $find_ret;
        $data['data']['address'] = $find_ret['shop_province'].$find_ret['shop_city'].$find_ret['shop_county'].$find_ret['address'];
        $data['data']['platform'] = '';
        $data['data']['platform_no_edit'] = '';//不可以修改的同盟平台
        $platform_no_edit = '';
        if(!empty($information_ret)){
            foreach($information_ret as $key => $value){
                $platform_arr[] = $value['type'];
                if($value['type'] == 1){//智配贴装
                    if($value['is_push'] == 2 && in_array($value['info_status'], [1,2]) ){//完成同步，并且处于待审核或者已通过状态
                        $platform_no_edit_arr[] = 1;
                    }
                }
                if($value['type'] == 2){//autokoo
                    if($value['is_push'] == 2 && in_array($value['info_status'], [1,2]) ){//完成同步，并且处于待审核或者已通过状态
                        $platform_no_edit_arr[] = 2;
                    }
                }

            }
            $platform = implode(',', $platform_arr);
            $data['data']['platform'] = $platform;
            if(!empty($platform_no_edit_arr)){
                $platform_no_edit = implode(',',$platform_no_edit_arr);
            }

        }
        $data['data']['platform_no_edit'] = $platform_no_edit;
        $data['data']['reason'] = $reason;
        $data['log'] = $log_ret;
        if($find_ret){
            return response()->json(['code'=> 200, 'msg'=>'获取成功', 'data'=>$data]);
        }else{
            return response()->json(['code'=> 500, 'msg'=>'暂无数据', 'data'=>'']);
        }
        // 验证数据
        /*if (!isset($input['phone'])) {
            return response()->json(['code'=> 500, 'msg'=>'参数错误', 'data'=>'']);
        }
        $id = SettleIn::where('phone',$input['phone'])->value('id');
        $status_names = self::getSettleStatus();
        $ret = SettleInSchedule::where('settle_in_id', $id)->orderBy('id','desc')->select('remark','s_status')->first();

        if($ret){
            $ret['s_status_name'] = $status_names[$ret['s_status']];
            return response()->json(['code'=> 200, 'msg'=>'获取成功', 'data'=>$ret]);
        }else{
            return response()->json(['code'=> 500, 'msg'=>'暂无数据', 'data'=>'']);
        }*/
    }

    /**
     * @name 获取跟进状态
     * @return string[]
     * @author du
     * @date 2023/5/18
     * @Time: 11:53
     */
    public static function getSettleStatus($type = true){
        $data = [['type'=>1,'name'=>'待审核'],['type'=>'2','name'=>'不审核'],['type'=>'3','name'=>'已联系'],['type'=>'4','name'=>'已通过'],['type'=>'5','name'=>'已驳回']];
        if($type){
            $data = array_column($data, 'name','type');
        }
        return $data;

    }

    /*
     * @name 服务范围
     * @param array data_type 1 智配贴装  2  美装
     * @retrun array
     * @author Ma 2023/7/4 9:51
     *
    */
    public static function getTypeName ( $data_type , $type = false ){
        // $data = [['type'=>1,'name'=>'贴膜安装'],['type'=>'2','name'=>'汽车维修'],['type'=>'3','name'=>'电瓶安装'],['type'=>'5','name'=>'导航安装'],['type'=>'6','name'=>'刹车片安装'],['type'=>'7','name'=>'轮胎安装'],['type'=>'8','name'=>'护板安装'],['type'=>'9','name'=>'充电桩安装']];
        //$data = [['type'=>1,'name'=>'车窗膜'],['type'=>10,'name'=>'漆面保护膜'],['type'=>11,'name'=>'改色膜'],['type'=>12,'name'=>'彩绘膜'],['type'=>'2','name'=>'汽车维修'],['type'=>'3','name'=>'电瓶安装'],['type'=>'5','name'=>'导航安装'],['type'=>'6','name'=>'刹车片安装'],['type'=>'7','name'=>'轮胎安装'],['type'=>'8','name'=>'护板安装'],['type'=>'9','name'=>'充电桩安装']];
        $data = ['1'=>[['type'=>1,'name'=>'车窗膜'],['type'=>10,'name'=>'漆面保护膜']],'2'=>[['type'=>1,'name'=>'车窗膜'],['type'=>10,'name'=>'漆面保护膜'],['type'=>11,'name'=>'改色膜'],['type'=>12,'name'=>'彩绘膜'],['type'=>13,'name'=>'车衣膜']]];
        if(!empty($data_type)){
            if($data_type == 'all'){//返回全部服务范围
                $data_type = [1,2];
            }else{
                $data_type = explode(',', $data_type);
            }
            $data_list = [];//所有服务项目
            $data_ret = [];//服务项目
            $types = [];//服务项目的id
            foreach ($data_type as $key => $value){
                $data_list = array_merge($data_list,$data[$value]);
            }
            //数组去重
            foreach ($data_list as $k => $v){
                if(!in_array($v['type'],$types)){
                    $data_ret[] = $v;
                    $types[] = $v['type'];
                }
            }
            if($type){
                $data_ret = array_column($data_ret, 'name','type');
            }
            return $data_ret;
        }else{
            return [];
        }

    }

    /*
     * @name 服务范围
     * @param array data_type 1 智配贴装  2  美装
     * @retrun array
     * @author Ma 2023/7/4 9:51
     *
    */
    public static function getTypeNameOld ($type = false ){
        // $data = [['type'=>1,'name'=>'贴膜安装'],['type'=>'2','name'=>'汽车维修'],['type'=>'3','name'=>'电瓶安装'],['type'=>'5','name'=>'导航安装'],['type'=>'6','name'=>'刹车片安装'],['type'=>'7','name'=>'轮胎安装'],['type'=>'8','name'=>'护板安装'],['type'=>'9','name'=>'充电桩安装']];
        $data = [['type'=>1,'name'=>'车窗膜'],['type'=>10,'name'=>'漆面保护膜'],['type'=>11,'name'=>'改色膜'],['type'=>12,'name'=>'彩绘膜'],['type'=>'2','name'=>'汽车维修'],['type'=>'3','name'=>'电瓶安装'],['type'=>'5','name'=>'导航安装'],['type'=>'6','name'=>'刹车片安装'],['type'=>'7','name'=>'轮胎安装'],['type'=>'8','name'=>'护板安装'],['type'=>'9','name'=>'充电桩安装']];
        if ($type) {
            $data = array_column($data, 'name', 'type');
        }
        return $data;
    }

    /*
     * @name 智配贴装同步美装
     * @param string ju_ordernum 订单单号
     * @retrun array
     * @author Ma 2023/7/6 14:09
     *
    */
    public static function synchronousData($request){
        // 接收数据流
        $request = file_get_contents("php://input");
        $input = json_decode($request, true);
        $find_settle = DB::table('settle_in')->where('phone',$input['phone'])->first();//查找用户id
        $find_settle = json_decode(json_encode($find_settle),true);
        $id = $find_settle['id'];
        $update['info_status'] = $input['status'];
        $update['remark'] = $input['remark'];
        if(isset($input['third_id']) && !empty($input['third_id'])){
            $update['third_id'] = $input['third_id'];
        }
        $se_ret = DB::table('settle_sync_information')->where('settle_in_id',$id)->where('type',$input['type'])->update($update);//更新审核结果
        if($input['status'] == 2){//如果审核通过，创建店铺
            //$re_ret = DB::table('settle_in')->where('id',$id)->update(['shop_id'=>$update['third_id']]);//审核通过可以接单
            $shop_data['shop_store_name'] = $find_settle['shop_name'];
            $shop_data['shop_name'] = $find_settle['charge_name'];
            $shop_data['shop_phone'] = $find_settle['phone'];
            $shop_data['shop_province'] = $find_settle['shop_province'];
            $shop_data['shop_city'] = $find_settle['shop_city'];
            $shop_data['shop_county'] = $find_settle['shop_county'];
            $shop_data['shop_address'] = $find_settle['address'];
            $shop_data['goods_ids'] = $find_settle['goods_ids'];
            $shop_data['shop_adm_name'] = $find_settle['charge_name'];
            $word = substr($find_settle['phone'], -6);
            $shop_data['shop_password'] =  md5($word.'faster123456');
            if($find_settle['shop_pic']){
                $shop_data['shop_image'] = $find_settle['shop_pic'];
            }else{
                $shop_data['shop_image'] = config('apisystem.server_name_https') .'/image/pcImg/shop_default_img.png';
            }
            $shop_data['shop_opening_time'] = $find_settle['bussiness_time'];
            $shop_data['shop_longitude'] = $find_settle['longitude'];
            $shop_data['shop_latitude'] = $find_settle['latitude'];
            $shop_data['shop_service_scope'] = $find_settle['goods_ids'];
            if($find_settle['goods_ids']){
                $goods_ids = explode(',',$find_settle['goods_ids']);
                $goods_name = SettleInService::getTypeName('all',true);
                foreach ($goods_ids as $goo_ke => $goo_va){
                    $goods_string[] = $goods_name[$goo_va];
                }
                $shop_data['shop_service_scope'] = implode(',',$goods_string);
            }else{
                $shop_data['shop_service_scope'] = '';
            }
            $shop_data['service_id'] = $input['third_id'];
            $ret = SettleInService::createAccount($shop_data);
            if($ret['code'] != 200){
                if($ret['code'] == 300){
                    return response()->json(["code"=>200,'msg'=>'更新成功','data'=>'']);
                }
                return response()->json(["code"=>500,'msg'=>$ret['msg'],'data'=>'']);

            }
            DB::table('settle_in')->where('id',$id)->update(['shop_id'=>$ret['data'],'sd_admin_id'=>$input['third_id']]);
            DB::table('shop')->where('shop_id',$ret['data'])->update(['shop_is_receiving_orders'=>2]);//修改店铺可以接单
            //同步绑定智配贴装的id
            $sarr['shre_relevance_shop_id'] = $input['third_id'];
            $sarr['shre_shop_id'] = $ret['data'];
            $sarr['shre_relevance_type'] = 1;
            $sarr['shre_state'] = 2;
            DB::table('shop_relevance')->insert($sarr);
            return response()->json(['code'=> 200, 'msg'=>'更新成功', 'data'=>$ret['data']]);
        }
        if($se_ret){
            return response()->json(['code'=> 200, 'msg'=>'更新成功', 'data'=>'']);
        }else{
            return response()->json(['code'=> 500, 'msg'=>'更新失败', 'data'=>'']);
        }
    }

    /**
     * @name 获取品牌
     * @param false $type
     * @return array|\string[][]
     * @author du
     * @date 2023/6/8
     * @Time: 17:17
     */
    public static function getAdBrandsName($type = false )
    {
        $data = [['type' =>'115', 'name' => '龙膜'], ['type' => '116', 'name' => '量子'], ['type' => '117', 'name' => '3M'], ['type' => '290', 'name' => '海湾'], ['type' => '299', 'name' => '摩特'], ['type' => '300', 'name' => 'BBS'], ['type' => '303', 'name' => '阿特哥'], ['type' => '323', 'name' => 'UCOLOR'], ['type' => '325', 'name' => 'BOP'], ['type' => '328', 'name' => '探路者'], ['type' => '331', 'name' => '京安途'], ['type' => '334', 'name' => 'XPEL'], ['type' => '124', 'name' => '其他']];
        if ($type) {
            $data = array_column($data, 'name', 'type');
        }
        return $data;
    }
    /**
     * @name 获取车间类型
     * @return string[]
     * @author du
     * @date 2023/5/18
     * @Time: 11:53
     */
    public static function getSettleWorkshop($type = true){
        $data = [['type'=>1,'name'=>'普通车间'],['type'=>'2','name'=>'无尘车间']];
        if($type){
            $data = array_column($data, 'name','type');
        }
        return $data;

    }

    /**
     * @name 是否能洗车
     * @return string[]
     * @author du
     * @date 2023/5/18
     * @Time: 11:54
     */
    public static function getSettleWashCar($type = true){
        $data = [['type'=>1,'name'=>'能'],['type'=>'2','name'=>'否']];
        if($type){
            $data = array_column($data, 'name','type');
        }
        return $data;
    }

    /*
     * 获取同盟平台类型
     *
     */
    public static function getSettleTypeName($type = true){
        $data = [['type'=>1,'name'=>'智配贴装'],['type'=>'2','name'=>'AUTOKOO']];
        if($type){
            $data = array_column($data, 'name','type');
        }
        return $data;
    }

    /*
    * 获取同盟平台状态
    *
    */
    public static function getSettleTypeStatus($type = true){
        $data = [['type'=>1,'name'=>'待审核'],['type'=>2,'name'=>'通过'],['type'=>'3','name'=>'驳回']];
        if($type){
            $data = array_column($data, 'name','type');
        }
        return $data;
    }

    /**
     * @name 技师列表
     * @param $input
     * @param $pageSize
     * @return \Illuminate\Http\JsonResponse
     * @author du
     * @date 2023/5/19
     * @Time: 16:36
     */
    public static function listPerson($input,$pageSize){
        $user_info = Common::wechatGetUserInfo($input['api_token']);
        $list = DB::table('admin as a')
            ->leftJoin('admin_shop_role as asr', 'asr.adm_id', "=", "a.adm_id")
            ->where('asr.shop_id',$user_info->adm_shop_id);

        if(isset($input['adm_phone'])){
            $list = $list->where(function($query)use($input){
                $query->where('a.adm_phone','like','%'.$input["adm_phone"].'%')
                    ->orWhere(function($query)use($input){
                        $query->where('a.adm_name','like','%'.$input["adm_phone"].'%');
                    });
            });
        }
        $list = $list->orderBy('asr.adm_id','desc')->get();//paginate($pageSize);
        $list_items = CommonService::dataToArray($list);//$list->items();
        if ($list_items) {
            foreach ($list_items as $key => $value) {
                $rest = mb_substr($value['adm_name'], 0, 1, 'utf-8');
                if ($rest) {
                    $mb = mb_strlen($rest, 'utf-8');
                    $st = strlen($rest);
                    if ($st == $mb) { //英文
                        $list_items[$key]['firstLetter'] = strtoupper($rest);
                    } else { //汉字
                        $py = new Pinyin();
                        $list_items[$key]['firstLetter'] = substr(strtoupper($py->abbr($value['adm_name'])), 0, 1);
                    }
                } else {
                    $list_items[$key]['firstLetter'] = '';
                }

            }
        }

        /* $data_info['current_page'] = $list->currentPage();  //当前页面页码
         $data_info['last_page'] = $list->lastPage();        //表示最后一页的页码
         $data_info['total'] = $list->total();               //总数据个数
         $data_info['current_number'] = $pageSize;       //一页显示多少个*/
        $data_info['data'] = $list_items;                //返回数据

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

    /**
     * @name 技师编辑添加
     * @param $input
     * @return int
     * @author du
     * @date 2023/5/19
     * @Time: 16:36
     */
    public static function addShopPerson($input){
        // 获取当前操作账号信息
        $user_info = Common::wechatGetUserInfo($input['api_token']);
        $user_info = CommonService::dataToArray($user_info);
        DB::beginTransaction();
        $adm_id = false;
        if($input['type']!=3) {
            $admin_shop_role_id = true;
        }
        if($input['type']==1){
            //重置密码
            $ad_phone = DB::table('admin')->where('adm_id',$input['adm_id'])->value('adm_phone');
            $password = md5(substr(trim($ad_phone),0,6) . 'faster123456');
            $arr['adm_password'] = $password;
            $arr['adm_update_time'] = date('Y-m-d H:i:s');
            $adm_res = DB::table('admin')->where('adm_id',$input['adm_id'])->update($arr);
        }elseif($input['type']==2){
            //编辑 adm_id
            $re = DB::table('admin')->whereRaw('adm_phone='.$input["adm_phone"].' and adm_id <> '.$input["adm_id"])->value('adm_id');
            if($re){
                return response()->json(['code'=>500, 'msg'=>'手机号已存在', 'data'=>'']);
            }
            $data['adm_account'] = $input['adm_account']??$input['adm_name']; //用户名（登录账号）
            $data['adm_name'] = $input['adm_name']; //姓名名称
            $data['adm_phone'] = $input['adm_phone']; //手机号
            $data['adm_state'] = $input['adm_state']; //状态1在职2离职
            $adm_res = DB::table('admin')->where('adm_id',$input['adm_id'])->update($data);
        }elseif($input['type']==3){
            $adm_phone = DB::table('admin_shop_role')
                ->where('phone', trim($input['adm_phone']))
                ->where('shop_id', $user_info["adm_shop_id"])
                ->first();
            if ($adm_phone) {
                return response()->json(['code'=>500, 'msg'=>'当前门店手机号已存在', 'data'=>'']);
            }
            $adm_res = DB::table('admin')
                ->where('adm_phone', trim($input['adm_phone']))
                ->value('adm_id');
            if(empty($adm_res)) {
                //添加
                if($input['adm_password']){
                    $password = md5(trim($input['adm_password']). 'faster123456');
                }else{
                    $password = md5(substr(trim($input['adm_phone']),0,6) . 'faster123456');
                }

                $admin_add_data['adm_cid'] = $user_info['adm_cid']; //所属企业/品牌方id
                $admin_add_data['adm_shop_id'] = $user_info['adm_shop_id']; //门店id
                $admin_add_data['adm_superior_shop_id'] = $user_info['adm_shop_id']; //总店id
                $admin_add_data['adm_leave'] = 3; //级别1店长2普通员工3技师4业务员5技师和业务员
                $admin_add_data['adm_phone'] = trim($input['adm_phone']); //手机号
                //  $admin_add_data['adm_account'] = $input['adm_account']??$input['adm_name']; //用户名（登录账号）
                $admin_add_data['adm_account'] = 'os'.date('Ymd').substr(implode(NULL,array_map('ord',str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
                $admin_add_data['adm_password'] = $password; //登录密码
                $admin_add_data['adm_name'] = $input['adm_name']; //姓名名称
                $admin_add_data['adm_role'] = DB::table('role')->where('rol_shop_id',$user_info['adm_shop_id'])->where('rol_type',3)->value('rol_id')??''; //角色id
                $admin_add_data['adm_creator_id'] = $user_info['adm_id']; //操作人id
                $admin_add_data['adm_role_applet'] = 0; //小程序角色id

                // 新增账号
                $adm_res =  DB::table('admin')->insertGetid($admin_add_data);
            }

            //新增账号门店权限关系表
            $insertAdminShopRoleData = [
                'adm_id' => $adm_res,
                'shop_cid' => $user_info['adm_cid'],
                'superior_shop_id' => $user_info['adm_shop_id'],
                'shop_id' => $user_info['adm_shop_id'],
                'role_id' => DB::table('role')->where('rol_shop_id',$user_info['adm_shop_id'])->where('rol_type',3)->value('rol_id')??'',
                'adm_shop_leave' => 3,
                'login_shop' => 2,
                'phone' => trim($input['adm_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);


            $adm_id = SettleIn::where('phone',$input['adm_phone'])->value('sd_admin_id');
            /*  $role_add_data = [
                  'rol_cid'=>1,
                  'rol_shop_id'=>$user_info['adm_shop_id'],
                  'rol_type'=>3,
                  'rol_name'=>'小程序技师',
                  'rol_privilege_multiple'=> '{"applet":"9,10,11,12,13,14,15,16,17,20,21,22"}',
                  'rol_privilege'=>config('apisystem.franchisee_shop'),
                  'rol_creator_id'=>$user_info['adm_id']
              ];
              // 新增角色
              $role_id =  DB::table('role')->insertGetId($role_add_data);*/
        }elseif($input['type']==4){
            $password = md5(trim($input['adm_password_y']) . 'faster123456');
            $password_y = DB::table('admin')->where('adm_id', $input['adm_id'])->value('adm_password');
            if($password!=$password_y){
                return response()->json(['code'=> 201,'msg'=>'原密码不正确','data'=>'']);
            }
            $password = md5(trim($input['adm_password']). 'faster123456');
            $arr['adm_password'] = $password;
            $arr['adm_update_time'] = date('Y-m-d H:i:s');
            $adm_res = DB::table('admin')->where('adm_id',$input['adm_id'])->update($arr);
        }
        
        if($adm_res && $admin_shop_role_id) {
            if (config('apisystem.SYNC_STATE') && $adm_id) {
                if($input['type']==3){
                    // $url = config('apisystem.sd_server_name') . '/index.php/api/supplychain/SupplyMz/creatInstallPerson';
                    // $param['install_name'] = $input['adm_name'];
                    // $param['install_phone'] = $input['adm_phone'];
                    // $param['admin_id'] = SettleIn::where('phone',$input['adm_phone'])->value('sd_admin_id');
                    // $param['install_password1'] = $input['adm_password'];
                    // $param['install_password'] = $password;
                    // $doPost_res = Common::doPost($param, $url, 2);
                    // $doPost_res = json_decode($doPost_res,true);
                    if ($doPost_res['code'] != 200) {
                        DB::rollback();
                        return response()->json(['code'=>500, 'msg'=>'同步失败', 'data'=>$doPost_res]);
                    }
                }
            }
            DB::commit();

            return response()->json(['code'=> 200,'msg'=>'操作成功','data'=>$adm_res]);
        }else{
            return response()->json(['code'=> 500,'msg'=>'操作失败','data'=>'']);
        }
    }


    /**
     * @name 接单
     * @param $input
     * @return \Illuminate\Http\JsonResponse
     * @author du
     * @date 2023/5/23
     * @Time: 10:41
     */
    public static function orderReceiving($input)
    {
        $order_data = DB::table('order as o')
            ->leftjoin('order_client as oc', 'o.ord_id', '=', 'oc.orcl_ord_id')
            ->where('ord_id', $input['ord_id'])
            ->first(['ord_cid', 'ord_shop_id', 'ord_superior_shop_id', 'ord_other_system_number', 'ord_wor_state', 'ord_order_number', 'ord_type', 'orcl_join_wor_id']);
        if ($order_data->ord_wor_state != 7) {
            return response()->json(['code'=>500, 'msg'=>'不是待接单状态,不能接单', 'data'=>'不是待接单状态,不能接单']);
        }

        $user_info = Common::getUserInfo($input['api_token']);
        if(empty($user_info)){
            $user_info = Common::wechatGetUserInfo($input['api_token']);
        }

        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_type = 1;//$user_info->shop_superior_id ? 2 : 1; //接单类型：1总店接单2加盟店接单

        DB::beginTransaction();
        $order_update['ord_wor_state'] = 1;
        $order_update['ord_update_time'] = date('Y-m-d H:i:s');
        $order_res = DB::table('order')
            ->where('ord_id', $input['ord_id'])
            ->update($order_update);

        // 判断是否有预约时间
        if (!empty($input['appoint_time'])) {
            $param['daytime'] = $input['appoint_time']; //速电-预约时间

            $orcl_edit['orcl_appoint_time'] = $input['appoint_time'];
            $orcl_edit['orcl_appoint_remark'] = $input['appoint_remark'];
            $orcl_res =  DB::table('order_client')
                ->where('orcl_ord_id', $input['ord_id'])
                ->update($orcl_edit);

            // 预约备注内容
            $remark_data = '预约时间：' . $input['appoint_time'];
            if (!empty($input['appoint_remark'])) {
                $remark_data .= ' ' . $input['appoint_remark'];
            }
            $remark_res = orderRemark($user_info, $input['ord_id'], 0, $remark_data, '订单列表-接单预约');

            if ($orcl_res && $remark_res) {
                $appoint_res = true;
            } else {
                $appoint_res = false;
            }
        } else {
            $appoint_res = true;
        }

        $log_res = orderLog($user_info, $input['ord_id'], 0, '领取订单');
        if ($order_res && $log_res && $appoint_res) {
            // 判断总店、加盟店接单
            if (config('apisystem.SYNC_STATE') && $shop_type == 1) {
                // 总店接单，同步速电
                sdOrderLog($order_data, 0, $order_data->orcl_join_wor_id, '接受订单');///index.php/api/supplychain/SupplyMz/
                $url = config('apiconnect.ZPTZ_URL') . '/index.php/api/supplychain/SupplyMz/sync_receipt_status';
                $param['serial_number'] = $order_data->ord_other_system_number; //第三方工单号
                $param['type'] = 1;
                $param['ip'] = $input['ip'];
                $param['time'] = date('Y-m-d H:i:s'); //收货时间
                $param['token'] = md5(md5($param['time'] . config('apisystem.sd_token'))); //token
                $doPost_res = Common::doPost($param, $url, 2);
                $doPost_res = json_decode($doPost_res,true);
                if ($doPost_res['code'] != 200) {
                    DB::rollBack();
                    return response()->json(['code'=>500, 'msg'=>'同步失败－'.$doPost_res['msg'], 'data'=>$doPost_res]);
                }
            } else {
                // 加盟店接单
                $wory = DB::table('work_order')->where('wor_id', $order_data->orcl_join_wor_id)->first(['wor_cid as adm_cid', 'wor_superior_shop_id as shop_superior_id', 'wor_shop_id as adm_shop_id']);
                $store_name = DB::table('shop')->where('shop_id', $user_info->adm_shop_id)->value('shop_store_name');
                $wor = CommonService::dataToArray($wory);
                $wor['adm_name'] = $store_name;
                $wor['adm_id'] = 0;
                orderLog($wory, 0, $order_data->orcl_join_wor_id, '接受订单');
            }

            // 添加新增订单信息的提示
            $inhi_data['inhi_original_adm_id'] = 0; //原始单号创建人
            $inhi_data['inhi_original_id'] = $input['ord_id']; //原始单id
            $inhi_data['inhi_original_number'] = $order_data->ord_order_number; //原始单号
            $inhi_data['inhi_original_state'] = $order_update['ord_wor_state']; //原始单状态
            $inhi_data['inhi_original_operation'] = '门店接单'; //操作
            $inhi_data['inhi_operation_state'] = 18; //操作状态：18门店接单
            addInformationHint($user_info, $inhi_data, 3);

            Common::addLog($user_info, $input['ip'], '订单列表', '接单', '订单:' . $order_data->ord_order_number . ' 接单成功');
            DB::commit();
            return response()->json(['code'=>200, 'msg'=>'接单成功', 'data'=>'接单成功']);
        } else {
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'接单失败', 'data'=>'接单失败']);
        }
    }

    /**
     * @name 未出账单列表
     * @param $input
     * @author du
     * @date 2023/5/24
     * @Time: 9:40
     */
    public static function getSettlmOrder($input,$pageSize){
        $input['ord_orbi_id'] = $input['ord_orbi_id']??0;
        $user_info = Common::wechatGetUserInfo($input['api_token']);
        $user_info = CommonService::dataToArray($user_info);
        $Db = DB::table('order as o')->where('ord_shop_id',$user_info['adm_shop_id'])->where('ord_source',5); //->leftjoin('order_goods as og', 'o.ord_id', '=', 'og.orgo_ord_id')

        $Db =  $Db->where('ord_orbi_id',0);//未出账单
        /* if($input['ord_orbi_id']==0){
             $Db =  $Db->where('ord_orbi_id',0);//未出账单
         }else{
             $Db =  $Db->where('ord_orbi_id',$input['ord_orbi_id']);//已出账单
         }*/
        $Db =  $Db->whereIn('ord_wor_state',[1,2,3,4,5,6,7,12,16,17,18,20]);

        $con = $Db->select('o.ord_id','o.ord_shop_id','o.ord_order_number','o.ord_service_sepr_id','o.ord_actual_price','o.ord_create_time','o.ord_other_system_number','o.ord_order_price')->get();
        $con = CommonService::dataToArray($con);

        $Db =  $Db->select('o.ord_id','o.ord_shop_id','o.ord_order_number','o.ord_service_sepr_id','o.ord_actual_price','o.ord_create_time','o.ord_other_system_number','o.ord_order_price', 'ord_wor_state')->orderBy('ord_id','DESC')->paginate($pageSize);

        $list_items = $Db->items();
        if ($list_items) {
            $list_items = CommonService::dataToArray($list_items);
            foreach ($list_items as $key => $value) {
                $goods = DB::table('order_goods')->where('orgo_ord_id',$value['ord_id'])->get(['orgo_goo_name']);
                $godds_names = array_unique(array_column(CommonService::dataToArray($goods), 'orgo_goo_name'));
                if(count($godds_names)>1){
                    $list_items[$key]['orgo_goo_name'] = implode(',', $godds_names);
                }else{
                    $list_items[$key]['orgo_goo_name'] = $godds_names;
                }
                $orcl_data = DB::table('order_client')
                    ->where('orcl_ord_id', $value['ord_id'])
                    ->select('orcl_name', 'orcl_phone', 'orcl_car_brand_series')
                    ->first();
                $list_items[$key]['company_name'] = '智配贴装';
                if ($value['ord_wor_state'] == 7) {
                    $list_items[$key]['orcl_name'] = mb_substr($orcl_data->orcl_name,0,1,'utf-8').str_repeat("*",(strlen($orcl_data->orcl_name)/3-1));
                    $list_items[$key]['orcl_phone'] = substr($orcl_data->orcl_phone,0,3).'****'.substr($orcl_data->orcl_phone,-4);
                } else {
                    $list_items[$key]['orcl_name'] =$orcl_data->orcl_name;
                    $list_items[$key]['orcl_phone'] =$orcl_data->orcl_phone;
                }
                $list_items[$key]['orcl_car_brand_series'] = $orcl_data->orcl_car_brand_series;
            }
        }

        $data_info['total_price'] = array_sum(array_column($con, 'ord_order_price'));

        $data_info['current_page'] = $Db->currentPage();  //当前页面页码
        $data_info['last_page'] = $Db->lastPage();        //表示最后一页的页码
        $data_info['total'] = $Db->total();               //总数据个数
        $data_info['current_number'] = $pageSize;       //一页显示多少个
        $data_info['data'] = $list_items;                //返回数据

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

    }


    /**
     * @name 账单列表
     * @param $input
     * @param $pageSize
     * @return \Illuminate\Http\JsonResponse
     * @author du
     * @date 2023/5/24
     * @Time: 11:07
     */
    public static function getSdOrderBill($input,$pageSize){
        $user_info = Common::wechatGetUserInfo($input['api_token']);
        $Db = DB::table('sd_order_bill')->where('sdob_state', $input['sdob_state'])->where('sdob_shop_id',$user_info->adm_shop_id);

        $Db =  $Db->orderBy('sdob_id','DESC')->paginate($pageSize);


        $list_items = $Db->items();
        if ($list_items) {
            $list_items = CommonService::dataToArray($list_items);
            $state_names = ['0'=>'未确认','1'=>'结算中','2'=>'已撤销','3'=>'已结款'];
            foreach ($list_items as $key => $value) {
                $list_items[$key]['sdob_state_name'] = $state_names[$value['sdob_state']];
                $list_items[$key]['company_name'] = '智配贴装';
            }
        }

        $data_info['current_page'] = $Db->currentPage();  //当前页面页码
        $data_info['last_page'] = $Db->lastPage();        //表示最后一页的页码
        $data_info['total'] = $Db->total();               //总数据个数
        $data_info['current_number'] = $pageSize;       //一页显示多少个
        $data_info['data'] = $list_items;                //返回数据

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

    /**
     * @name 账单详情
     * @param $input
     * @param $pageSize
     * @return \Illuminate\Http\JsonResponse
     * @author du
     * @date 2023/6/7
     * @Time: 17:58
     */
    public static function billDetail($input,$pageSize){
        $id = intval($input['id']);
        $list = DB::table('sd_order_bill_details')->where('sobd_sdob_id',$id)->select('sobd_id','sobd_order_number','sobd_actual_price','sobd_create_time','sobd_goods_name', 'sobd_ord_id')->orderBy('sobd_id','DESC')->paginate($pageSize);

        $list_items = $list->items();
        if ($list_items) {
            foreach ($list_items as $key => $value) {
                $list_items[$key]->company_name = '智配贴装';
                $orcl_data = DB::table('order_client')
                    ->leftJoin('order', 'ord_id', '=', 'orcl_ord_id')
                    ->where('ord_other_system_number', $value->sobd_order_number)
                    ->select('orcl_name', 'orcl_phone', 'orcl_car_brand_series')
                    ->first();
                $list_items[$key]->orcl_name = !empty($orcl_data) ? $orcl_data->orcl_name:'';
                $list_items[$key]->orcl_phone = !empty($orcl_data) ? $orcl_data->orcl_phone:'';
                $list_items[$key]->orcl_car_brand_series = !empty($orcl_data) ? $orcl_data->orcl_car_brand_series:'';
            }
        }

        $data_info['current_page'] = $list->currentPage();  //当前页面页码
        $data_info['last_page'] = $list->lastPage();        //表示最后一页的页码
        $data_info['total'] = $list->total();               //总数据个数
        $data_info['current_number'] = $pageSize;       //一页显示多少个
        $data_info['data'] = $list_items;                //返回数据

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

    }



    /**
     * @name 获取发票类型
     * @return string[]
     * @author du
     * @date 2023/5/24
     * @Time: 14:02
     */
    public static function getInvType($type = true){
        $data = [['type'=>1,'name'=>'纸质发票'],['type'=>'2','name'=>'电子发票']];
        if($type){
            $data = array_column($data, 'name','type');
        }
        return $data;


    }

    /**
     * @name 获取付款方式
     * @return string[]
     * @author du
     * @date 2023/6/6
     * @Time: 10:06
     */
    public static function getPayType($type = true){
        $data = [['type'=>1,'name'=>'银行卡'],['type'=>'2','name'=>'支付宝'],['type'=>'3','name'=>'微信']];
        if($type){
            $data = array_column($data, 'name','type');
        }
        return $data;

    }

    /**
     * @name 上传发票
     * @param $input
     * @author du
     * @date 2023/5/24
     * @Time: 14:04
     */
    public static function uploadInv($input){

        $exsit = DB::table('invoice_table')->where('wat_num',$input['wat_num'])->value('id');
        if($exsit){
            return response()->json(['code'=> 500,'msg'=>'已存在','data'=>'']);
        }

        $user_info = Common::wechatGetUserInfo($input['api_token']);
        $data['inv_num'] = $input['inv_num'];
        $data['inv_img'] = $input['inv_img']??'';
        $data['express_num'] = $input['express_num']??'';
        $data['inv_type'] = $input['inv_type']??1;
        $data['admin_id'] = $user_info->adm_id;
        $data['shop_id'] = $user_info->adm_shop_id;
        $data['wat_num'] = $input['wat_num']; //速电账单号
        DB::beginTransaction();
        $ret = DB::table('invoice_table')->insertGetId($data);
        DB::table('sd_order_bill')->where('sdob_sd_bill_bumber',$input['wat_num'])->update(['sdob_is_inv'=>2]);
        if($ret){
            //同步智配　invoice_number 发票号　　wat_num　结算单号　invoice_pic　发票图片　courier_number　快递单号 url = config('apisystem.sd_server_name') . '/index.php/api/supplychain/SupplyMz/createServce';
            if (config('apisystem.SYNC_STATE')) {
                $url = config('apisystem.sd_server_name') . '/index.php/api/supplychain/SupplyMz/getInvByShop';
                $param['time'] = date('Y-m-d H:i:s'); //时间
                $param['ip'] = $input['ip'];
                $param['invoice_number'] = $input['inv_num']; //发票号
                $param['token'] = md5(md5($param['time'] . config('apisystem.sd_token'))); //token
                $param['wat_num'] = $input['wat_num']; //速电账单号
                $param['invoice_pic'] = $data['inv_img'];
                $param['courier_number'] = $data['express_num'];
                $doPost_res = Common::doPost($param, $url, 2);
                $doPost_res = json_decode($doPost_res);
                if ($doPost_res->code != 200) {
                    DB::rollback();
                    return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'同步失败']);
                }
            }
            DB::commit();
            return response()->json(['code'=> 200,'msg'=>'操作成功','data'=>$ret]);
        }else{
            DB::rollback();
            return response()->json(['code'=> 500,'msg'=>'操作失败','data'=>'']);
        }

    }

    /**
     * @name 获取发票信息
     * @param $input
     * @return \Illuminate\Http\JsonResponse
     * @author du
     * @date 2023/6/8
     * @Time: 11:54
     */
    public static function getInvImg($input){
        $info = DB::table('invoice_table')->where('wat_num',$input['wat_num'])->first();
        if($info){

            return response()->json(['code'=> 200,'msg'=>'获取成功','data'=>$info]);
        }else{

            return response()->json(['code'=> 500,'msg'=>'暂无数据','data'=>'']);
        }
    }

    /**
     * @name 确认账单
     * @param $input
     * @return \Illuminate\Http\JsonResponse
     * @author du
     * @date 2023/6/8
     * @Time: 10:32
     */
    public static function confirm($input){

        $bill_data = DB::table('sd_order_bill')
            ->where('sdob_id', $input['sdob_id'])
            ->first(['sdob_sd_bill_bumber', 'sdob_sd_bill_price', 'sdob_orbi_id', 'sdob_start_time', 'sdob_end_time', 'sdob_bill_price', 'sdob_orbi_number']);
        // 获取当前操作账号信息
        $user_infoy = Common::wechatGetUserInfo($input['api_token']);
        $user_info = CommonService::dataToArray($user_infoy);
        $shop_id = $user_info['shop_superior_id'] ??$user_info['adm_shop_id'];
        if($shop_id == 0){
            $shop_id = $user_info['adm_shop_id'];
        }

        DB::beginTransaction();

        $orbi_id = DB::table('sd_order_bill')
            ->where('sdob_id', $input['sdob_id'])
            ->value('sdob_orbi_id');

        if(empty($orbi_id)){
            // 2.订单账单表新增一条数据
            // $number = 'DZ' . time() . rand(10000000, 99999999);
            $number = $bill_data->sdob_orbi_number;
            $data['sdob_orbi_id'] = $number;//本系统账单id
            $add_data['orbi_cid'] = $user_info['adm_cid'];
            $add_data['orbi_shop_id'] = $user_info['adm_shop_id'];
            $add_data['orbi_superior_shop_id'] = $shop_id;
            $add_data['orbi_number'] = $number;//账单编号
            $add_data['orbi_start_time'] = $bill_data->sdob_start_time;//开始日期
            $add_data['orbi_end_time'] = $bill_data->sdob_end_time;//结束日期
            $add_data['orbi_state'] = 3; //待审核
            $add_data['orbi_type'] = 3; //类型：1会员零售2客户单位3速电网单4虚拟加盟店5加盟店
            $add_data['orbi_create_type'] = 2; //账单生成类型1手动生成2速电同步生成
            $order_number = [];//订单号(速电派工单号)
            // 查询速电同步账单详情表
            $sobd_id = DB::table('sd_order_bill_details')
                ->where('sobd_sdob_id', $input['sdob_id'])
                ->select('sobd_id', 'sobd_sdob_id', 'sobd_order_number', 'sobd_ord_order_number', 'sobd_ord_id', 'sobd_actual_price','sobd_goods_name')
                ->get()->toArray();
            $sobd_id = json_decode(json_encode($sobd_id), true);
            foreach ($sobd_id as $key => $value) {
                $order_number[] = $value['sobd_order_number'];//订单号(速电派工单号)
            }
            $order_count = count($sobd_id);
            $add_data['orbi_order_amount'] = $order_count;
            // 根据速电工单号(第三方系统单号)查询订单数据
            $order_info = DB::table('order')
                ->whereIn('ord_other_system_number', $order_number)
                ->where('ord_delete', 1)
                // ->where('ord_state', 1) //未结算
                ->whereIn('ord_wor_state', [4, 5, 8]) //无工单 已完成  撤销订单
                ->select('ord_goods_quantity', 'ord_collection_price', 'ord_actual_price', 'ord_state', 'ord_service_type', 'ord_plus_minus', 'ord_id', 'ord_other_system_number', 'ord_order_number')
                ->get()->toArray();
            $order_info = json_decode(json_encode($order_info), true);
            $add_data['orbi_collection_price'] = 0; //代收金额
            $add_data['orbi_goods_sum'] = 0; // 商品总量
            $original_number = []; //原始id，更改应收账款数据使用
            $ord_id = [];
            $sys_order_number = [];
            foreach ($order_info as $key => $value) {
                $ord_id[] = $value['ord_id'];
                $sys_order_number[] = $value['ord_other_system_number'];
                $add_data['orbi_collection_price'] += $value['ord_collection_price']; //代收金额
                $add_data['orbi_goods_sum'] += $value['ord_goods_quantity'];//商品总量
                foreach ($sobd_id as $k => $v) {
                    if ($value['ord_other_system_number'] == $v['sobd_order_number']) {
                        $sobd_id[$k]['order_number'] = $value['ord_order_number']; //本系统的订单单号
                        $sobd_id[$k]['order_id'] = $value['ord_id']; //本系统的订单id
                    }
                }
            }
            // 结算金额
            $goods_price = $bill_data->sdob_bill_price;
            // 如果是正数
            if ($goods_price >= 0) {
                $plus_minus = 1;
            } else {
                $plus_minus = 2;
            }

            $add_data['orbi_collection_price'] = 0; //代收金额为0
            $add_data['orbi_plus_minus'] = $plus_minus; //正数
            $add_data['orbi_state'] = 1; //账单状态1.未结款2.已结款3.待审核4.已驳回5.部分结款
            $add_data['orbi_merge_state'] = 2; //1是2否
            $add_data['orbi_total_price'] = $goods_price; //合计金额（单位：分）订单的结算
            $add_data['orbi_bill_price'] = $goods_price; //结算金额（单位：分）订单结算金额：商品总金额-回收总金额
            $add_data['orbi_actual_price'] = $goods_price; //实收金额（单位：分）订单结算金额-代收金额，实际应收金额
            $add_data['orbi_sd_affirm'] = 1; //速电账单确认状态 0未确认  1已确认
            $orbi_id = DB::table('order_bill')->insertGetId($add_data);

            if (!empty($order_info)) {
                // 3.修改订单表 账单id
                $sql = 'UPDATE `faster_order` SET ';
                $ord_orbi_id = ''; //账单id
                $ord_state = ''; //更改结算状态
                $update_time = ''; //调货时间
                $ord_id_str = "";
                foreach ($ord_id as $key => $value) {
                    // 更改账单id
                    $ord_orbi_id = $ord_orbi_id . ' WHEN ' . $value;
                    $ord_orbi_id = $ord_orbi_id . ' THEN ' . $orbi_id;
                    // 更改结算状态
                    $ord_state = $ord_state . ' WHEN ' . $value;
                    $ord_state = $ord_state . ' THEN 2';
                    // 更改时间
                    $update_time = $update_time . ' WHEN ' . $value;
                    $update_time = $update_time . ' THEN "' . date('Y-m-d H:i:s') . '"';
                    //要更改的订单id
                    $ord_id_str = $ord_id_str . $value . ',';
                }
                $sql = $sql . ' `ord_orbi_id`= CASE `ord_id` ' . $ord_orbi_id . ' END,';
                $sql = $sql . ' `ord_state`= CASE `ord_id` ' . $ord_state . ' END,';
                $sql = $sql . ' `ord_update_time`= CASE `ord_id` ' . $update_time . ' END';
                $sql = $sql . ' WHERE `ord_id` IN (' . trim($ord_id_str, ',') . ')';

                $save_order = DB::update($sql);
            } else {
                $save_order = true;
            }

            // 5. 生成应收账单
            $createBill = ReceivableBill::create(
                $user_infoy, //用户信息
                3, //类型：1.销售订单 2.预收款 3.订单账单 4.工单账单 5.采购账单 6.销售账单
                0, //应收账款id
                $orbi_id, //原始id(订单账单id)
                $number, //应收账款单号/原始号(订单账单编号)
                6, //客户类型：1.门店零售 2.来往单位
                0, //会员id/来往单位id
                '', //来往单位名称
                $goods_price, //实收金额
                date('Y-m-d H:i:s'), //结款时间
                0, //会计科目id
                0, //实际金额
                0, //抹零金额
                1, //状态：1.未核销 2.已核销
                2, //应收账单id是否是自己 1.不是 2.是
                '',  //备注
                0,  //已收金额
                '', //截止时间
                $plus_minus, //金额正负
                5, //显示类型：1订单收款 2受托代收（订单代收）3委托代收（工单代收）4工单费用（工单收款）5订单账单 6工单账单 7销售账单 8预收款
                date('Y-m-d H:i:s'),
                2 //是否合并代收：1是2否
            );

            // 6.账单下所有的订单为不统计状态
            $statistics_type_update = DB::table('receivable_credit')
                ->where('recr_cid', $user_info['adm_cid'])
                ->where('recr_shop_superior_id', $shop_id)
                ->where('recr_type', 3)
                ->where('recr_belongs_id', $orbi_id)
                ->update(['recr_statistics_type' => 2, 'recr_update_time' => date('Y-m-d H:i:s')]);
            if ($statistics_type_update || $statistics_type_update === 0) {
            } else {
                DB::rollBack();
                return response()->json(['code'=>203, 'msg'=>'生成账单失败']);
            }

            // 判断是否有本系统不存在的订单
            $diff_number = array_diff($order_number, $sys_order_number);
            if (!empty($diff_number)) {
                foreach ($diff_number as $key => $value) {
                    $price  = 0;
                    foreach ($sobd_id as $k => $v) {
                        if ($v['sobd_order_number'] == $value) {
                            $price = $v['sobd_actual_price'];
                        }
                    }
                    $rece[$key]['recr_cid'] = $user_info['adm_cid'];
                    $rece[$key]['recr_shop_id'] = $user_info['adm_shop_id'];
                    $rece[$key]['recr_shop_superior_id'] = $shop_id;
                    $rece[$key]['recr_type'] = 3; //类型：1.销售订单 2.预收款 3.订单账单 4.工单账单 5.采购账单 6.销售账单
                    $rece[$key]['recr_account_type'] = 5;
                    $rece[$key]['recr_number_id'] = $createBill; //应收账单id
                    $rece[$key]['recr_belongs_id'] = $orbi_id; //应收账单id
                    // $rece[$key]['recr_original_id'] = $recr_original_id; //与类型所对应的id
                    $rece[$key]['recr_original_number'] = $value; //与类型所对应的单号
                    $rece[$key]['recr_client_type'] = 6; //客户类型：1.门店零售 2.来往单位
                    $rece[$key]['recr_client_id'] = 0; //会员id/来往单位id
                    $rece[$key]['recr_client_name'] = config('apisystem.sd_chan_info')['name']; //来往单位名称
                    $rece[$key]['recr_settle_price'] = $price; //结算金额
                    $rece[$key]['recr_actual_price'] = $price; //实际金额
                    $rece[$key]['recr_state'] = 1; //状态：1.未核销 2.已核销
                    $rece[$key]['recr_plus_minus'] = 1; //金额正负值
                    $rece[$key]['recr_bill_type'] = 2; //1系统单  2非系统单
                }
                $recr_res = DB::table('receivable_credit')->insert($rece);
            } else {
                $recr_res = true;
            }

            $aaaa = 222;
        }else{
            $recr_res = true;
            $save_order = true;
            $createBill = DB::table('order_bill')
                ->where('orbi_id',$orbi_id)
                ->update(['orbi_sd_affirm'=>1,'orbi_update_time'=>date('Y-m-d H:i:s')]);
            $aaaa = 1111;
        }

        // 1.修改速电同步账单表状态
        $data['sdob_state'] = 1;//对比状态0未处理1已对比  2已撤销
        $data['sdob_update_time'] = date('Y-m-d H:i:s');
        $data['sdob_orbi_id'] = $orbi_id;//本系统账单id

        // 1.修改速电同步账单表状态
        $res = DB::table('sd_order_bill')
            ->where('sdob_id', $input['sdob_id'])
            ->update($data);
//echo 'res:'.$res.';-----$orbi_id:'.$orbi_id.';----$createBill:'.$createBill.';----$recr_res:'.$recr_res.';---$save_order:'.$save_order;

        $oid = DB::table('sd_order_bill_details')
            ->where('sobd_sdob_id', $input['sdob_id'])->pluck('sobd_order_number');
        $ores = DB::table('order')->whereIn('ord_other_system_number',$oid)->update(['ord_orbi_id'=>$orbi_id]);
        $aa = 'res:'.$res.';-----$orbi_id:'.$orbi_id.';----$createBill:'.$createBill.';----$recr_res:'.$recr_res.';---$save_order:'.$save_order.';---$ores:'.$ores.';----$aaaa'.$aaaa;

        //20230724  修改订单应收应付  //1现金、2支付宝、3微信、4银行卡
        $sd_detail_ret = DB::table('sd_order_bill_details')
            ->where('sobd_sdob_id', $input['sdob_id'])
            ->get()->toArray();
        foreach ($sd_detail_ret as $key => $value) {
            $sobd_order_number[] = $value->sobd_order_number;
            $sd_order_detail[$value->sobd_order_number] = $value;
        }
        if(isset($sobd_order_number)){
            $order_info = DB::table('order')
                ->whereIn('ord_other_system_number', $sobd_order_number)
                ->where('ord_delete', 1)
                ->select('ord_order_number','ord_other_system_number')
                ->get()->toArray();
            if($order_info){
                $order_info = CommonService::dataToArray($order_info);
                $order_number_arr = CommonService::jointArrayKey($order_info,'ord_other_system_number');
                foreach ($sobd_order_number as $number_key => $number_value){
                    if(isset($order_number_arr[$number_value])) {
                        $rec_info = DB::table('receivable_pay')
                            ->where('recpay_original_number', $order_number_arr[$number_value]['ord_order_number'])
                            ->first();
                        if($rec_info){
                            $sd_info = $sd_order_detail[$number_value];
                            //$rece_params['recpay_original_number'] = $number_value;//订单id
                            $rece_params['recpay_original_number'] = $order_number_arr[$number_value]['ord_order_number'];//订单id
                            $rece_params['recpay_receivable_price'] = $sd_info->sobd_actual_price / 100;//应收金额
                            $rece_params['recpay_actual_price'] = $sd_info->sobd_actual_price / 100;//实收金额
                            $rece_params['recpay_arrears_price'] = 0;//欠收金额
                            $rece_params['recpay_cost_price'] = 0;//成本
                            $rece_params['recpay_plus_minus'] = 1;
                            $rece_params['recpay_profit'] = $sd_info->sobd_actual_price / 100;//盈利金额
                            $rece_params['recpay_state'] = 2;
                            $rt = ReceivablePayService::edit($rece_params);
                            $rec_info = DB::table('order')
                                ->where('ord_order_number', $order_number_arr[$number_value]['ord_order_number'])
                                ->update(['ord_state' => 2, 'ord_actual_price' => $sd_info->sobd_actual_price, 'ord_settlement_time' => date('Y-m-d H:i:s'), 'ord_payment_money' => $sd_info->sobd_actual_price]);
                        }
                    }
                }
            }
        }
        if ($res && $orbi_id && $createBill && $recr_res && $save_order/* && $ores*/) {
            Common::addLog($user_infoy, $input['ip'], '账单对比', '确认', '速电账单确认：' . $bill_data->sdob_sd_bill_bumber . '成功');
            if (config('apisystem.SYNC_STATE')) {///index.php/api/supplychain/SupplyMz/
                $url = config('apisystem.sd_server_name') . '/index.php/api/supplychain/SupplyMz/dealWith';
                $param['time'] = date('Y-m-d H:i:s'); //收货时间
                $param['ip'] = $input['ip'];
                $param['apply_note'] = ''; //拒单备注
                $param['token'] = md5(md5($param['time'] . config('apisystem.sd_token'))); //token
                $param['wat_num'] = $bill_data->sdob_sd_bill_bumber; //速电账单号

                $doPost_res = Common::doPost($param, $url, 2);
                $doPost_res = json_decode($doPost_res,true);
                // dump($doPost_res);
                if ($doPost_res['code'] != 200) {
                    DB::rollBack();
                    return response()->json(['code'=>500, 'msg'=>'失败', 'data'=>$doPost_res]);
                }
            }
            DB::commit();
            return response()->json(['code'=>200, 'msg'=>'账单确认成功', 'data'=>$aa]);
        } else {
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'账单确认失败', 'data'=>$aa]);
        }

    }

    /**
     * @name 是否存在此定单
     * @param $input
     * @return \Illuminate\Http\JsonResponse
     * @author du
     * @date 2023/6/8
     * @Time: 15:36
     */
    public static function isExsitOrderNum($input){
        $info = DB::table('order')->where('ord_other_system_number',$input['ord_other_system_number'])->value('ord_id');
        if($info){
            return response()->json(['code'=>200, 'msg'=>'获取成功', 'data'=>$info]);
        } else {
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'无数据', 'data'=>'']);
        }
    }

    /**
     * @name 拒单
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @author du
     * @date 2023/6/12
     * @Time: 15:39
     */
    public static function orderRefuse($input)
    {
        if (empty($input['label_id']) || empty($input['ord_id']) || empty($input['label_name'])) {
            return response()->json(['code'=>500, 'msg'=>'参数错误', 'data'=>'参数错误']);
        }

        $user_infoy = Common::getUserInfo($input['api_token']);
        if(empty($user_infoy)){
            $user_infoy = Common::wechatGetUserInfo($input['api_token']);
        }
        //  $user_info = CommonService::dataToArray($user_infoy);
        $order_data = DB::table('order')
            ->where('ord_id', $input['ord_id'])
            ->first(['ord_other_system_number', 'ord_wor_state', 'ord_order_number', 'ord_type']);
        if (!in_array($order_data->ord_wor_state, [7])) {
            return response()->json(['code'=>500, 'msg'=>'当前订单不是待接单状态，无法拒单', 'data'=>'']);
        }

        DB::beginTransaction();
        $input['ord_remark'] = $input['label_name'].';'.$input['ord_remark'];
        $ord_data['ord_remark'] = $input['ord_remark']??'';
        $ord_data['ord_wor_state'] = 11;
        $ord_data['ord_update_time'] = date('Y-m-d H:i:s');
        $ord_res = DB::table('order')
            ->where('ord_id', $input['ord_id'])
            ->update($ord_data);
        if ($ord_res) {
            // 智配订单
            $url = config('apiconnect.ZPTZ_URL') . '/index.php/api/supplychain/SupplyMz/sync_receipt_status';
            $param['type'] = 2;
            $param['time'] = date('Y-m-d H:i:s'); //收货时间
            $param['ip'] = $input['ip'];
            $param['sin_bid'] = $input['label_id']; //拒单标签
            $param['sin_bcentent'] = $input['label_name']; //拒单标签名称
            $param['content'] = $input['ord_remark']; //拒单备注
            $param['token'] = md5(md5($param['time'] . config('apiconnect.ZPTZ_TOKEN'))); //token
            $param['serial_number'] = $order_data->ord_other_system_number; //第三方工单号
            $param_return = Common::doPost($param, $url, 2);
            $param_returns = $param_return;
            $param_return = json_decode($param_return, true);
            // dump($param);
            // dump($param_return);
            if ($param_return['code'] != 200) {
                DB::rollBack();
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>$param_returns]);
            }
            //取消应收应付
            $find_rece = DB::table('receivable_pay')
                ->where('recpay_original_id', $input['ord_id'])
                ->first();
            if($find_rece){
                $update_qrres = DB::table('receivable_pay')
                    ->where('recpay_original_id', $input['ord_id'])
                    ->update(['recpay_order_state'=>3]);
            }
            // 添加新增订单信息的提示
            // $inhi_data['inhi_original_adm_id'] = 0; //原始单号创建人
            // $inhi_data['inhi_original_id'] = $request['ord_id']; //原始单id
            // $inhi_data['inhi_original_number'] = $order_data->ord_order_number; //原始单号
            // $inhi_data['inhi_original_state'] = 0; //原始单状态
            // $inhi_data['inhi_original_operation'] = '门店拒单'; //操作
            // $inhi_data['inhi_operation_state'] = 19; //操作状态：19门店拒单
            // addInformationHint($user_info, $inhi_data, 3);

            Common::addLog($user_infoy, $input['ip'], '订单列表', '拒单', '订单:' . $order_data->ord_order_number . ' 拒单成功');
            DB::commit();
            return response()->json(['code'=>200, 'msg'=>'拒单成功', 'data'=>'拒单成功']);
        } else {
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'拒单失败', 'data'=>'拒单失败']);
        }
    }

    // 拒单标签
    public static function refuseLabel()
    {
        // 智配订单
        $url = config('apisystem.sd_server_name') . '/index.php/api/supplychain/SupplyMz/searchLable';
        $param['time'] = date('Y-m-d H:i:s');
        $param['type'] = 2;
        $param['token'] = md5(md5($param['time'] . config('apiconnect.ZPTZ_TOKEN'))); //token
        $param_return = Common::doPost($param, $url, 2);
        $param_return = json_decode($param_return, true);
        return response()->json($param_return);
    }




}

