<?php
namespace App\Http\Controllers\WeChatApplet;

use App\Services\CommonService;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\WeChatApplet\Verify\VerifyLoginController;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Crypt;
use App\Http\Models\Api\Common;
use App\Services\LoginUserService;

class LoginController extends Controller
{
    // 登录
    public function login(Request $request)
    {
        // 记录日志
        $log_record['request'] = $request->all();
        $log_record['time'] = date('Y-m-d H:i:s');
        $log_record['function'] = 'login';
        logFileRecord($log_record, 'Login/login', 2);
        
        // 验证数据
        $verify_data = new VerifyLoginController;
        $error_message = $verify_data->loginValidator($request->all());
        if ($error_message) {
            $error_message = json_decode(json_encode($error_message,true), true);
            $message = '';
            foreach ($error_message as $key => $value) {
                $message = $value;
            }
            return response()->json(['code'=>500, 'msg'=>$message[0], 'data'=>'']);
        }
        $appid = config('apisystem.tea_appid');
        $appsecret = config('apisystem.tea_appsecret');
        if (isset($request['js_code'])) {
            $js_code = $request['js_code'];//小程序传值
            // 登录凭证校验。
            $url = "https://api.weixin.qq.com/sns/jscode2session?appid=".$appid."&secret=".$appsecret."&js_code=".$js_code."&grant_type=authorization_code";
            $result = file_get_contents($url);
            $code2Session = json_decode($result, true);//小程序登录返回的数据
            if(empty($code2Session['openid'])){
                return response()->json(['code'=>4000, 'msg'=>'登录凭证校验失败 '.$code2Session['errcode'], 'data'=>'']);
            }
        }
        $return_moudle_id = [];
        // 判断手机号正则
        $phone_preg = '/^0?1[3|4|5|6|7|8|9][0-9]\d{8}$/';
        $adm_pawd = md5($request['password'] . 'faster123456');
        if ($request['type'] == 1) {//技师登录
            // 查询账号信息
            $find_admin = DB::table('admin as adm')
                ->leftjoin('admin_shop_role as asr', 'asr.adm_id', '=', 'adm.adm_id')
                ->leftjoin('role', 'role.rol_id', '=', 'asr.role_id')
                ->leftjoin('shop', 'shop.shop_id', '=', 'asr.shop_id')
                ->leftJoin('msg_config', 'msco_shop_id', '=', 'asr.shop_id')
                ->where(function ($query) use ($request, $phone_preg) {
                    if (preg_match($phone_preg, $request['username'])) {
                        $query->where('adm_phone', $request['username']);
                    } else {
                        $query->where('adm_account', $request['username']);
                    }
                })
                ->where('adm_password', $adm_pawd)
                ->where('asr.create_source', 1)
                ->where('asr.login_shop_wechat', 1)
                ->select('adm.adm_id', 'adm_name', 'adm_account', 'adm_phone', 'asr.shop_cid as adm_cid', 'asr.shop_id as adm_shop_id', 'asr.adm_state',
                    'rol_state', 'rol_privilege', 'rol_privilege_multiple', 'asr.superior_shop_id as adm_superior_shop_id', 'adm_open_id', 'asr.adm_shop_leave as adm_leave',
                    'shop_source_identify', 'msco_send_detail', 'adm.adm_account')
                ->first();
                if (empty($find_admin)) {
                    $find_admin = DB::table('admin as adm')
                        ->leftjoin('admin_shop_role as asr', 'asr.adm_id', '=', 'adm.adm_id')
                        ->leftjoin('role', 'role.rol_id', '=', 'asr.role_id')
                        ->leftjoin('shop', 'shop.shop_id', '=', 'asr.shop_id')
                        ->leftJoin('msg_config', 'msco_shop_id', '=', 'asr.shop_id')
                        ->where(function ($query) use ($request, $phone_preg) {
                            if (preg_match($phone_preg, $request['username'])) {
                                $query->where('adm_phone', $request['username']);
                            } else {
                                $query->where('adm_account', $request['username']);
                            }
                        })
                        ->where('adm_password', $adm_pawd)
                        ->where('asr.create_source', 1)
                        ->select('adm.adm_id', 'adm_name', 'adm_account', 'adm_phone', 'asr.shop_cid as adm_cid', 'asr.shop_id as adm_shop_id', 'asr.adm_state',
                            'rol_state', 'rol_privilege', 'rol_privilege_multiple', 'asr.superior_shop_id as adm_superior_shop_id', 'adm_open_id', 'asr.adm_shop_leave as adm_leave',
                            'shop_source_identify', 'msco_send_detail','adm.adm_account')
                        ->orderBy('adm_state', 'asc')
                        ->orderBy('asr.id','desc')
                        ->first();
                    if (empty($find_admin)) {
                        return response()->json(['code'=>500, 'msg'=>'账号或密码错误', 'data'=>'账号或密码错误']);
                    }
                }

                $send = isSend($find_admin,6);


                if (isset($request['js_code']) && !empty($request['js_code'])) {
                    // 根据openid获取账号信息
                    if (empty($find_admin->adm_open_id)) {//没有绑定微信的 更新openid
                        $update_data['adm_open_id'] = $code2Session['openid'];
                        $update_data['adm_update_time'] = date('Y-m-d H:i:s');
                        $update_adm_res = DB::table('admin')
                            ->where('adm_id', $find_admin->adm_id)
                            ->update($update_data);
                    } else {//验证登录微信 更换微信的需要验证短信验证码
                        if ($code2Session['openid'] != $find_admin->adm_open_id && $send) {
                            if (!isset($request['phone_code']) || empty($request['phone_code'])) {
                                return response()->json(['code'=>201, 'msg'=>'检测到更换微信，请输入验证码', 'data'=>'检测到更换微信，请输入验证码']);
                            } else {
                                // 验证 验证码是否正确
                                $find_phone_code = DB::table('phone_code')
                                    ->where('phc_phone', $find_admin->adm_phone)
                                    ->where('phc_code', $request['phone_code'])
                                    ->first(['phc_id', 'phc_type', 'phc_expirationtime']);
                                if (empty($find_phone_code)) {
                                    return response()->json(['code'=>201, 'msg'=>'验证码错误', 'data'=>'验证码错误']);
                                }
                                if ($find_phone_code->phc_type != 1) {
                                    return response()->json(['code'=>201, 'msg'=>'当前验证码已使用，请重新获取验证码', 'data'=>'当前验证码已使用，请重新获取验证码']);
                                }
                                if ($find_phone_code->phc_expirationtime < date('Y-m-d H:i:s')) {
                                    return response()->json(['code'=>201, 'msg'=>'当前验证码已使用，请重新获取验证码', 'data'=>'当前验证码已过期失效，请重新获取验证码']);
                                }
                                // 更改验证码状态
                                $phc_res = DB::table('phone_code')
                                    ->where('phc_id', $find_phone_code->phc_id)
                                    ->update(['phc_type' => 2]);
                                $update_data['adm_open_id'] = $code2Session['openid'];
                                $update_data['adm_update_time'] = date('Y-m-d H:i:s');
                                $update_adm_res = DB::table('admin')
                                    ->where('adm_id', $find_admin->adm_id)
                                    ->update($update_data);
                            }
                        }
                    }
                    $find_admin_openid = DB::table('admin')
                        ->where('adm_open_id', $find_admin->adm_open_id)
                        ->select('adm_id', 'adm_name', 'adm_phone')
                        ->first();
                    $update_data['adm_open_id'] = $code2Session['openid'];
                    $update_data['adm_update_time'] = date('Y-m-d H:i:s');
                    $update_adm_res = DB::table('admin')
                        ->where('adm_id', $find_admin_openid->adm_id)
                        ->update($update_data);
                } else {
                }
                if (!empty($find_admin->msco_send_detail)) {
                    $msco_send_detail = explode(',',$find_admin->msco_send_detail);
                    if (in_array(1,$msco_send_detail)) {
                        $find_admin->msco_add_ord = 1;
                    } else {
                        $find_admin->msco_add_ord = 2;
                    }
                } else {
                    $find_admin->msco_add_ord = 2;
                }
                if ($find_admin->adm_leave == 1) {
                    $find_most = DB::table('moudle_statistics')
                        ->where('most_shop_id', $find_admin->adm_shop_id)
                        ->where('most_adm_id', $find_admin->adm_id)
                        ->get()->toArray();

                    if (empty($find_most)) {
                        $return_moudle[] = ['id'=>1, 'name'=>'快速开单'];
                        $return_moudle[] = ['id'=>2, 'name'=>'仓库管理'];
                        $return_moudle[] = ['id'=>3, 'name'=>'排班计划'];
                        $return_moudle[] = ['id'=>4, 'name'=>'技师动态'];
                        $return_moudle[] = ['id'=>5, 'name'=>'数据统计'];
                        foreach ($return_moudle as $key => $value) {
                            $add_most['most_shop_id'] = $find_admin->adm_shop_id;
                            $add_most['most_adm_id'] = $find_admin->adm_id;
                            $add_most['most_prompt_date'] = date('Y-m-d H:i:s', strtotime('+1 month'));
                            $add_most['most_create_time'] = date('Y-m-d H:i:s');
                            $add_most['most_moudle_id'] = $value['id'];
                            $add_most['most_moudle'] = $value['name'];
                            if ($value['id'] == 1) {
                                $add_most['most_nums'] = DB::table('order')
                                    ->where('ord_shop_id', $find_admin->adm_shop_id)
                                    ->where('ord_source', 3)
                                    ->count();
                            }
                            $add_res = DB::table('moudle_statistics')->insertGetId($add_most);
                        }
                    }
                    $return_moudle_data = DB::table('moudle_statistics')
                        ->where('most_shop_id', $find_admin->adm_shop_id)
                        ->where('most_adm_id', $find_admin->adm_id)
                        ->where('most_remind', 1)
                        ->select('most_moudle_id')
                        ->get()->toArray();
                    $return_moudle_id = array_column($return_moudle_data, 'most_moudle_id');
                }
        } else {
            // 查询企业客户
            $find_buac = DB::table('business_account')
                ->where(function ($query) use ($request, $phone_preg) {
                    if (preg_match($phone_preg, $request['username'])) {
                        $query->where('buac_phone', $request['username']);
                    }
                })
                ->where('buac_del', 1)
                ->where('buac_password', $adm_pawd)
                ->select('buac_id', 'buac_name', 'buac_phone', 'buac_cid', 'buac_shop_id', 'buac_bucl_id')
                ->first();
            if (empty($find_buac)) {
                return response()->json(['code'=>500, 'msg'=>'账号或密码错误', 'data'=>'账号或密码错误']);
            }
            // 查询门店信息
            $find_shop = DB::table('shop')
                ->where('shop_id', $find_buac->buac_shop_id)
                ->select('shop_state', 'shop_superior_id', 'shop_store_name', 'shop_type', 'shop_longitude', 'shop_latitude', 'shop_province', 'shop_city', 'shop_county', 'shop_address', 'shop_versions', 'shop_source_identify')
                ->first();
            if (empty($find_shop)) {
                return response()->json(['code'=>500, 'msg'=>'当前账号所属门店不存在', 'data'=>'当前账号所属门店不存在']);
            }
            if ($find_shop->shop_state != 1) {
                return response()->json(['code'=>500, 'msg'=>'当前账号所属门店已被停用', 'data'=>'当前账号所属门店已被停用']);
            }

            $find_bucl = DB::table('business_client')
                ->where('bucl_id', $find_buac->buac_bucl_id)
                ->where('bucl_del', 1)
                ->select('bucl_id', 'bucl_name', 'bucl_state')
                ->first();
            if (empty($find_bucl) || $find_bucl->bucl_state != 1) {
                return response()->json(['code'=>500, 'msg'=>'当前账号所属服务商已被停用', 'data'=>'当前账号所属服务商已被停用']);
            }
            if (isset($request['js_code'])) {
                $update_buac_data['buac_open_id'] = $code2Session['openid'];
                $update_buac_data['buac_update_time'] = date('Y-m-d H:i:s');
                $update_adm_res = DB::table('business_account')
                    ->where('buac_id', $find_buac->buac_id)
                    ->update($update_buac_data);
            }

            // 生成token
            $unique_string = md5(uniqid(md5(microtime(true)) . rand(100000, 999999), true)); //生成唯一字符串
            $api_token = sha1($unique_string); //加密
            $find_login = DB::table('login_wechat_applet')
                ->where('adm_id', $find_buac->buac_id)
                ->where('type', 2)
                ->select('adm_id', 'last_login')
                ->first();
            if (empty($find_login)) {
                // 如果用户第一次登陆,将用户的登录状态保存到临时表
                $lote_data['adm_id'] = $find_buac->buac_id; //账号id
                $lote_data['last_login'] = time() + 24 * 30 * 60 * 60; //最后登陆时间
                $lote_data['api_token'] = $api_token; //api_token
                $lote_data['adm_name'] = $find_buac->buac_name; //账号姓名
                $lote_data['adm_phone'] = $find_buac->buac_phone; //手机号
                $lote_data['adm_cid'] = $find_buac->buac_cid; //公司id
                $lote_data['adm_shop_id'] = $find_buac->buac_shop_id; //门店id
                $lote_data['type'] = 2; //合作商
                if (isset($request['js_code'])) {
                    $lote_data['opend_id'] = $code2Session['openid']; //openid
                }
                // $lote_data['opend_id'] = $code2Session['openid']; //openid
                $lote_res = DB::table('login_wechat_applet')->insert($lote_data);
                if (empty($lote_res)) {
                    return response()->json(['code'=>500, 'msg'=>'api_token写入失败', 'data'=>'api_token写入失败']);
                }
                // 返回数据
                $return_data = [
                    'api_token' => Crypt::encrypt($api_token), //生成前台token
                    'buac_id' => $find_buac->buac_id,
                    'buac_name' => $find_buac->buac_name,
                    'adm_phone' => $find_buac->buac_phone,
                    'shop_id' => $find_buac->buac_shop_id,
                    'shop_store_name' => $find_shop->shop_store_name,
                    'shop_type' => $find_shop->shop_type,
                    'shop_province' => $find_shop->shop_province,
                    'shop_city' => $find_shop->shop_city,
                    'shop_county' => $find_shop->shop_county,
                    'shop_longitude' => $find_shop->shop_longitude,
                    'shop_latitude' => $find_shop->shop_latitude,
                    'shop_versions' => $find_shop->shop_versions,
                    'shop_source_identify' => $find_shop->shop_source_identify,
                    'type' => $request['type'],
                ];
                return response()->json(['code'=>200, 'msg'=>'登录成功1', 'data'=>$return_data]);
            }

            $now_time = time();

            // 当前时间大于最后登陆时间，登录时间已过期，重新登录
            // login_type 值为1 强制登录
            if ($now_time > $find_login->last_login || $request['login_type'] == 1) {
                // 修改登陆状态
                $lote_data['last_login'] = time() + 24 * 30 * 60 * 60; //最后登陆时间
                $lote_data['api_token'] = $api_token; //api_token
                $lote_data['adm_name'] = $find_buac->buac_name; //账号姓名
                $lote_data['adm_phone'] = $find_buac->buac_phone; //手机号
                $lote_data['adm_cid'] = $find_buac->buac_cid; //公司id
                $lote_data['adm_shop_id'] = $find_buac->buac_shop_id; //门店id
                $lote_data['shop_versions'] = $find_shop->shop_versions; //系统版本：1门店版2运营中心版
                if (isset($request['js_code'])) {
                    $lote_data['opend_id'] = $code2Session['openid']; //openid
                }
                $lote_data['type'] = $request['type']; //openid
                $lote_res = DB::table('login_wechat_applet')
                    ->where('adm_id', $find_buac->buac_id)
                    ->where('type', 2)
                    ->update($lote_data);
                if (empty($lote_res)) {
                    return response()->json(['code'=>500, 'msg'=>'api_token写入失败', 'data'=>'api_token写入失败']);
                }
                // 返回数据
                $return_data = [
                    'api_token' => Crypt::encrypt($api_token), //生成前台token
                    'buac_id' => $find_buac->buac_id,
                    'buac_name' => $find_buac->buac_name,
                    'buac_phone' => $find_buac->buac_phone,
                    'shop_id' => $find_buac->buac_shop_id,
                    'shop_store_name' => $find_shop->shop_store_name,
                    'shop_type' => $find_shop->shop_type,
                    'shop_province' => $find_shop->shop_province,
                    'shop_city' => $find_shop->shop_city,
                    'shop_county' => $find_shop->shop_county,
                    'shop_longitude' => $find_shop->shop_longitude,
                    'shop_latitude' => $find_shop->shop_latitude,
                    'shop_source_identify' => $find_shop->shop_source_identify,
                    'shop_versions' => $find_shop->shop_versions,//系统版本：1门店版2运营中心版
                    'type' => 2,//类型1技师2合作商
                ];
                
                $data = [
                    'oplo_module'=>'合作商登录',
                    'oplo_action'=>'登录',
                    'oplo_content'=>$find_buac->buac_name . '登录成功',
                    'oplo_ip'=>getRealIp($request),
                    'order_number'=>'',
                    'work_number'=>'',
                    'data_source'=>2,//操作来源  1 PC  2 小程序
                ];
                $log = addNewLog($lote_data, $data);
                return response()->json(['code'=>200, 'msg'=>'登录成功2', 'data'=>$return_data]);
            } else {
                return response()->json(['code'=>400, 'msg'=>'此账号已登录，是否强制登录？', 'data'=>'此账号已登录，是否强制登录？']);
            }
        }
        if (empty($find_admin)) {
            return response()->json(['code'=>500, 'msg'=>'账号或密码错误', 'data'=>'账号或密码错误']);
        }
        if ($find_admin->adm_state == 2) {
            return response()->json(['code'=>500, 'msg'=>'当前账号已被停用', 'data'=>'当前账号已被停用']);
        }
        if ($find_admin->rol_state != 1) {
            return response()->json(['code'=>500, 'msg'=>'当前账号所属角色权限已被停用', 'data'=>'当前账号所属角色权限已被停用']);
        }
        $date = date('Y-m-d H:i:s');
        $find_online = DB::table('online_management')
            ->where('onma_state', 1)
            ->where('onma_start_time', '<=', $date)
            ->where('onma_end_time', '>=', $date)
            ->first();
        if ($find_online) {
            $adm_id = explode(',', $find_online->onma_adm_id);
            if (!in_array($find_admin->adm_id, $adm_id)) {
                return response()->json(['code'=>500, 'msg'=>$find_online->onma_name, 'data'=>'']);
            }
        }
        // 判断账号时效
        if (!in_array($find_admin->adm_shop_id, config('apisystem.NO_TIME_CHECK'))) {
            $sup_shop_info = DB::table('shop')
                ->where('shop_id', $find_admin->adm_shop_id)
                ->select('shop_opening_end_time', 'shop_opening_start_time', 'shop_on_trial_end_time', 'shop_on_trial_start_time')
                ->first();
            if ($sup_shop_info) {
                $time = time();
                // 判断试用是否到期
                if ($time > strtotime($sup_shop_info->shop_on_trial_end_time)) {
                    // 过期判断开通结束时间
                    if ($time > strtotime($sup_shop_info->shop_opening_end_time)) {
                        // 已过期 将权限隐藏
                        // 查询所有权限
                        $where['pri_show'] = 1;
                        $where['pri_type'] = 3;
                        $pri_res = DB::table('privileges')->where($where)->select('pri_id')->get()->toArray();
                        // 当前账号权限转为数组
                        $rol_privilege_arr = explode(',', $find_admin->rol_privilege);
                        foreach ($pri_res as $v) {
                            if (in_array($v->pri_id, $rol_privilege_arr)) {
                                $key = array_search($v->pri_id, $rol_privilege_arr);
                                unset($rol_privilege_arr[$key]);
                            } elseif (in_array(1, $rol_privilege_arr)) {
                                $key = array_search(1, $rol_privilege_arr);
                                unset($rol_privilege_arr[$key]);
                            } elseif (in_array(102, $rol_privilege_arr)) {
                                $key = array_search(102, $rol_privilege_arr);
                                unset($rol_privilege_arr[$key]);
                            }
                        }
                        $find_admin->rol_privilege = implode(',', $rol_privilege_arr);
                    }
                }
            } else {
                return response()->json(['code'=>500, 'msg'=>'查询总店信息失败', 'data'=>'查询总店信息失败']);
            }
        }

        // 查询账号设置表的经纬度
        $find_admin_set = DB::table('admin_set')
            ->where('adms_adm_id', $find_admin->adm_id)
            ->where('adms_shop_id', $find_admin->adm_shop_id)
            ->select('adms_province', 'adms_city', 'adms_county', 'adms_address', 'adms_longitude', 'adms_latitude')
            ->first();

        // 查询门店信息
        $find_shop = DB::table('shop')
            ->leftjoin('shop_relevance', 'shop.shop_id', '=', 'shop_relevance.shre_shop_id')
            ->where('shop_id', $find_admin->adm_shop_id)
            ->select('shop_state', 'shop_superior_id', 'shop_store_name', 'shop_type', 'shop_longitude', 'shop_latitude', 'shop_province', 'shop_city', 'shop_county', 'shop_address', 'shop_versions', 'shop_source_identify', 'shre_shop_id')
            ->first();
        if ($find_shop->shop_state != 1) {
            return response()->json(['code'=>500, 'msg'=>'当前账号所属门店已被停用', 'data'=>'当前账号所属门店已被停用1']);
        }
        if (!empty($find_shop->shre_shop_id)) {
            $is_bind = 1;
        } else {
            $is_bind = 2;
        }
        if (!empty($find_admin_set)) {
            if ($find_admin_set->adms_longitude != '0' && $find_shop->shop_longitude != '0') {
                $find_shop->shop_longitude = $find_admin_set->adms_longitude;
                $find_shop->shop_latitude = $find_admin_set->adms_latitude;
            }
            if (empty($find_shop->shop_province)) {
                $find_shop->shop_province = $find_admin_set->adms_province;
                $find_shop->shop_city = $find_admin_set->adms_city;
                $find_shop->shop_county = $find_admin_set->adms_county;
            }
        }
        // 查询账号所属门店是否停用
        if (!in_array($find_admin->adm_id, config('apisystem.pass_verification_admin'))) {
            if ($find_shop->shop_state != 1 && $find_shop->shop_type != 3) {
                return response()->json(['code'=>500, 'msg'=>'当前账号所属门店已停业', 'data'=>'当前账号所属门店已停业']);
            } elseif ($find_shop->shop_type == 3 && $find_shop->shop_state != 1) {
                return response()->json(['code'=>500, 'msg'=>'当前账号所属加盟店已停业', 'data'=>'当前账号所属加盟店已停业']);
            }
            if ($find_shop->shop_type == 3) {
                $shop_superior_id = $find_admin->adm_shop_id;
            } else {
                $shop_superior_id = $find_shop->shop_superior_id;
            }
            if ($find_shop->shop_superior_id == 0) {
                $shop_set_superior_id = $find_admin->adm_shop_id;
            } else {
                $shop_set_superior_id = $find_shop->shop_superior_id;
            }
        } else {
            $shop_superior_id = 0;
            $shop_set_superior_id = 1;
        }

        // 判断此账号是否绑定手机号
        // if (empty($find_admin->adm_phone)) {
        //     return response()->json(['code'=>600, 'msg'=>'账号未绑定手机号', 'data'=>'账号未绑定手机号']);
        // }

        // 生成token
        $unique_string = md5(uniqid(md5(microtime(true)) . rand(100000, 999999), true)); //生成唯一字符串
        $api_token = sha1($unique_string); //加密
        $find_login = DB::table('login_wechat_applet')
            ->where('adm_id', $find_admin->adm_id)
            ->select('adm_id', 'last_login')
            ->first();
        if (empty($find_login)) {
            // 获取用户对应角色权限
            $role_auth = $this->getRolePrivilege($find_admin);
            // 确认此账号默认跳转页面
            $default_url = $this->getDefaultPath($role_auth['role_auth']);

            // 如果用户第一次登陆,将用户的登录状态保存到临时表
            $lote_data['adm_id'] = $find_admin->adm_id; //账号id
            $lote_data['last_login'] = time() + 30 * 24 * 60 * 60; //最后登陆时间
            $lote_data['api_token'] = $api_token; //api_token
            $lote_data['adm_name'] = $find_admin->adm_name; //账号姓名
            $lote_data['adm_account'] = $find_admin->adm_account; //账号姓名
            $lote_data['adm_phone'] = $find_admin->adm_phone; //手机号
            $lote_data['adm_cid'] = $find_admin->adm_cid; //公司id
            $lote_data['adm_shop_id'] = $find_admin->adm_shop_id; //门店id
            $lote_data['shop_superior_id'] = $shop_superior_id; //所属总店id
            $lote_data['shop_versions'] = $find_shop->shop_versions; //系统版本：1门店版2运营中心版
            if (empty($role_auth['routes_auth']) || empty($role_auth['role_auth'])) {
                return response()->json(['code'=>500, 'msg'=>'请联系管理员设置员工角色权限！', 'data'=>'请联系管理员设置员工角色权限！']);
            }
            if (isset($request['js_code'])) {
                $lote_data['opend_id'] = $code2Session['openid']; //openid
            }
            // $lote_data['opend_id'] = $code2Session['openid']; //openid
            $lote_data['type'] = $request['type']; //type
            $lote_data['role_auth'] = json_encode($role_auth['role_auth']); //当前账号所有角色权限
            $lote_data['auth_routes'] = json_encode($role_auth['routes_auth']); //当前账号所有角色权限路径
            $lote_res = DB::table('login_wechat_applet')->insert($lote_data);
            if (empty($lote_res)) {
                return response()->json(['code'=>500, 'msg'=>'api_token写入失败', 'data'=>'api_token写入失败']);
            }

            DB::table('admin_shop_role')->where('adm_id', $find_admin->adm_id)->update(['login_shop_wechat'=>2]);
            DB::table('admin_shop_role')->where('adm_id', $find_admin->adm_id)->where('shop_id', $find_admin->adm_shop_id)->update(['login_shop_wechat'=>1]);
            // 返回数据
            $return_data = [
                'api_token' => Crypt::encrypt($api_token), //生成前台token
                'default_url' => $default_url, //默认跳转页面
                'adm_id' => $find_admin->adm_id,
                'adm_name' => $find_admin->adm_name,
                'adm_account' => $find_admin->adm_account,
                'adm_leave' => $find_admin->adm_leave,
                'adm_phone' => $find_admin->adm_phone,
                'msco_add_ord' => $find_admin->msco_add_ord,
                'shop_id' => $find_admin->adm_shop_id,
                'shop_store_name' => $find_shop->shop_store_name,
                'shop_type' => $find_shop->shop_type,
                'shop_province' => $find_shop->shop_province,
                'shop_city' => $find_shop->shop_city,
                'shop_county' => $find_shop->shop_county,
                'shop_longitude' => $find_shop->shop_longitude,
                'shop_latitude' => $find_shop->shop_latitude,
                'shop_source_identify' => $find_shop->shop_source_identify,
                'shop_versions' => $find_shop->shop_versions,
                'type' => $request['type'],
                'is_bind'=>$is_bind,
                'return_moudle_id'=>$return_moudle_id
            ];
            return response()->json(['code'=>200, 'msg'=>'登录成功3', 'data'=>$return_data]);
        }

        $now_time = time();

        // 当前时间大于最后登陆时间，登录时间已过期，重新登录
        // login_type 值为1 强制登录
        if ($now_time > $find_login->last_login || $request['login_type'] == 1) {
            // 查找此用户对应得角色权限
            $role_auth = $this->getRolePrivilege($find_admin);
            
            // 确认此账号默认跳转页面
            $default_url = $this->getDefaultPath($role_auth['role_auth']);

            // 修改登陆状态
            $lote_data['last_login'] = time() + 30 * 24 * 60 * 60; //最后登陆时间
            $lote_data['api_token'] = $api_token; //api_token
            $lote_data['adm_name'] = $find_admin->adm_name; //账号姓名
            $lote_data['adm_account'] = $find_admin->adm_account; //账号
            $lote_data['adm_phone'] = $find_admin->adm_phone; //手机号
            $lote_data['adm_cid'] = $find_admin->adm_cid; //公司id
            $lote_data['adm_shop_id'] = $find_admin->adm_shop_id; //门店id
            $lote_data['shop_superior_id'] = $shop_superior_id; //所属总店id
            $lote_data['shop_versions'] = $find_shop->shop_versions; //系统版本：1门店版2运营中心版
            $lote_data['role_auth'] = json_encode($role_auth['role_auth']); //当前账号所有角色权限
            if (!isset($role_auth['routes_auth'])) {
                return response()->json(['code'=>500, 'msg'=>'此账号无权限', 'data'=>'此账号无权限']);
            }
            if (isset($request['js_code'])) {
                $lote_data['opend_id'] = $code2Session['openid']; //openid
            }
            $lote_data['type'] = $request['type']; //type
            $lote_data['auth_routes'] = json_encode($role_auth['routes_auth']); //当前账号所有角色权限路径
            $lote_res = DB::table('login_wechat_applet')
                ->where('adm_id', $find_admin->adm_id)
                ->update($lote_data);
            if (empty($lote_res)) {
                return response()->json(['code'=>500, 'msg'=>'api_token写入失败', 'data'=>'api_token写入失败']);
            }
            DB::table('admin_shop_role')->where('adm_id', $find_admin->adm_id)->update(['login_shop_wechat'=>2]);
            DB::table('admin_shop_role')->where('adm_id', $find_admin->adm_id)->where('shop_id', $find_admin->adm_shop_id)->update(['login_shop_wechat'=>1]);
            // 返回数据
            $return_data = [
                'api_token' => Crypt::encrypt($api_token), //生成前台token
                'default_url' => $default_url, //默认跳转页面
                'adm_id' => $find_admin->adm_id,
                'adm_name' => $find_admin->adm_name,
                'adm_account' => $find_admin->adm_account,
                'adm_leave' => $find_admin->adm_leave,
                'adm_phone' => $find_admin->adm_phone,
                'msco_add_ord' => $find_admin->msco_add_ord,
                'shop_id' => $find_admin->adm_shop_id,
                'shop_store_name' => $find_shop->shop_store_name,
                'shop_type' => $find_shop->shop_type,
                'shop_province' => $find_shop->shop_province,
                'shop_city' => $find_shop->shop_city,
                'shop_county' => $find_shop->shop_county,
                'shop_longitude' => $find_shop->shop_longitude,
                'shop_source_identify' => $find_shop->shop_source_identify,
                'shop_latitude' => $find_shop->shop_latitude,
                'shop_versions' => $find_shop->shop_versions,//系统版本：1门店版2运营中心版
                'type' => $request['type'],
                'is_bind'=>$is_bind,
                'return_moudle_id'=>$return_moudle_id
            ];
            $user_info['adm_cid'] = $find_admin->adm_cid;
            $user_info['adm_shop_id'] = $find_admin->adm_shop_id;
            $user_info['adm_id'] = $find_admin->adm_id;
            $user_info['adm_name'] = $find_admin->adm_name;
            $user_info['adm_phone'] = $find_admin->adm_phone;
            $data = [
                'oplo_module'=>'技师登录',
                'oplo_action'=>'登录',
                'oplo_content'=>$find_admin->adm_name.' 使用：'. $request['osName'] . '登录成功',
                'oplo_ip'=>getRealIp($request),
                'order_number'=>'',
                'work_number'=>'',
                'data_source'=>2,//操作来源  1 PC  2 小程序
            ];
            $log = addNewLog($user_info, $data);
            return response()->json(['code'=>200, 'msg'=>'登录成功4', 'data'=>$return_data]);
        } else {
            return response()->json(['code'=>400, 'msg'=>'此账号已登录，是否强制登录？', 'data'=>'此账号已登录，是否强制登录？']);
        }
    }

    // 选择门点登录
    public function switchShopLogin(Request $request)
    {
        // 获取当前操作账号信息
        $user_info = Common::wechatGetUserInfo($request['api_token']);
        $shopId = $request['shop_id'];
        // 记录日志
        $log_record['request'] = $request->all();
        $log_record['time'] = date('Y-m-d H:i:s');
        $log_record['function'] = 'login';
        logFileRecord($log_record, 'Login/switchShopLogin', 2);

        // 验证数据
        $verify_data = new VerifyLoginController;
        $error_message = $verify_data->switchShopLogin($request->all());
        if ($error_message) {
            $error_message = json_decode(json_encode($error_message, true), true);
            $message = '';
            foreach ($error_message as $key => $value) {
                $message = $value;
            }
            return response()->json(['code' => 500, 'msg' => $message[0], 'data' => '']);
        }

        DB::beginTransaction();
        //退出当前登录门店
        $res = DB::table('login_wechat_applet')
            ->where('api_token', $request['api_token'])
            ->delete();
        if (empty($res)) {
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'退出当前门店失败']);
        }
        $return_moudle_id = [];
        //登录新门店
        if ($request['type'] == 1) {//技师登录
            $find_admin = DB::table('admin as adm')
                ->leftjoin('admin_shop_role as asr', 'asr.adm_id', '=', 'adm.adm_id')
                ->leftjoin('role', 'role.rol_id', '=', 'asr.role_id')
                ->leftjoin('shop', 'shop.shop_id', '=', 'asr.shop_id')
                ->leftJoin('msg_config', 'msco_shop_id', '=', 'asr.shop_id')
                ->where('asr.adm_id', $user_info->adm_id)
                ->where('asr.shop_id', $shopId)
                ->where('asr.create_source', 1)
                ->where('asr.adm_state', 1)
                ->select('adm.adm_id', 'adm_name', 'adm_account', 'adm_phone', 'asr.shop_cid as adm_cid', 'asr.shop_id as adm_shop_id', 'asr.adm_state','rol_state', 'rol_privilege', 'rol_privilege_multiple', 'asr.superior_shop_id as adm_superior_shop_id', 'adm_open_id', 'asr.adm_shop_leave as adm_leave','shop_source_identify', 'msco_send_detail','create_source')
                ->first();
            if (!empty($find_admin->msco_send_detail)) {
                $msco_send_detail = explode(',', $find_admin->msco_send_detail);
                if (in_array(1, $msco_send_detail)) {
                    $find_admin->msco_add_ord = 1;
                } else {
                    $find_admin->msco_add_ord = 2;
                }
            } else {
                $find_admin->msco_add_ord = 2;
            }
            if ($find_admin->adm_leave == 1) {
                $find_most = DB::table('moudle_statistics')
                    ->where('most_shop_id', $find_admin->adm_shop_id)
                    ->where('most_adm_id', $find_admin->adm_id)
                    ->get()->toArray();
                if (empty($find_most)) {
                    $return_moudle[] = ['id'=>1, 'name'=>'快速开单'];
                    $return_moudle[] = ['id'=>2, 'name'=>'仓库管理'];
                    $return_moudle[] = ['id'=>3, 'name'=>'排班计划'];
                    $return_moudle[] = ['id'=>4, 'name'=>'技师动态'];
                    $return_moudle[] = ['id'=>5, 'name'=>'数据统计'];
                    foreach ($return_moudle as $key => $value) {
                        $add_most['most_shop_id'] = $find_admin->adm_shop_id;
                        $add_most['most_adm_id'] = $find_admin->adm_id;
                        $add_most['most_prompt_date'] = date('Y-m-d H:i:s', strtotime('+1 month'));
                        $add_most['most_create_time'] = date('Y-m-d H:i:s');
                        $add_most['most_moudle_id'] = $value['id'];
                        $add_most['most_moudle'] = $value['name'];
                        $add_res = DB::table('moudle_statistics')->insertGetId($add_most);
                    }
                    $return_moudle_data = DB::table('moudle_statistics')
                        ->where('most_shop_id', $find_admin->adm_shop_id)
                        ->where('most_adm_id', $find_admin->adm_id)
                        ->where('most_remind', 1)
                        ->select('most_moudle_id')
                        ->get()->toArray();
                    $return_moudle_id = array_column($return_moudle_data, 'most_moudle_id');
                }
            }
            $date = date('Y-m-d H:i:s');
            $find_online = DB::table('online_management')
                ->where('onma_state', 1)
                ->where('onma_start_time', '<=', $date)
                ->where('onma_end_time', '>=', $date)
                ->first();
            if ($find_online) {
                $adm_id = explode(',', $find_online->onma_adm_id);
                if (!in_array($find_admin->adm_id, $adm_id)) {
                    DB::rollBack();
                    return response()->json(['code' => 500, 'msg' => $find_online->onma_name, 'data' => '']);
                }
            }
            // 判断账号时效
            if (!in_array($find_admin->adm_shop_id, config('apisystem.NO_TIME_CHECK'))) {
                $sup_shop_info = DB::table('shop')
                    ->where('shop_id', $find_admin->adm_shop_id)
                    ->select('shop_opening_end_time', 'shop_opening_start_time', 'shop_on_trial_end_time', 'shop_on_trial_start_time')
                    ->first();
                if ($sup_shop_info) {
                    $time = time();
                    // 判断试用是否到期
                    if ($time > strtotime($sup_shop_info->shop_on_trial_end_time)) {
                        // 过期判断开通结束时间
                        if ($time > strtotime($sup_shop_info->shop_opening_end_time)) {
                            // 已过期 将权限隐藏
                            // 查询所有权限
                            $where['pri_show'] = 1;
                            $where['pri_type'] = 3;
                            $pri_res = DB::table('privileges')->where($where)->select('pri_id')->get()->toArray();
                            // 当前账号权限转为数组
                            $rol_privilege_arr = explode(',', $find_admin->rol_privilege);
                            foreach ($pri_res as $v) {
                                if (in_array($v->pri_id, $rol_privilege_arr)) {
                                    $key = array_search($v->pri_id, $rol_privilege_arr);
                                    unset($rol_privilege_arr[$key]);
                                } elseif (in_array(1, $rol_privilege_arr)) {
                                    $key = array_search(1, $rol_privilege_arr);
                                    unset($rol_privilege_arr[$key]);
                                } elseif (in_array(102, $rol_privilege_arr)) {
                                    $key = array_search(102, $rol_privilege_arr);
                                    unset($rol_privilege_arr[$key]);
                                }
                            }
                            $find_admin->rol_privilege = implode(',', $rol_privilege_arr);
                        }
                    }
                } else {
                    DB::rollBack();
                    return response()->json(['code' => 500, 'msg' => '查询总店信息失败', 'data' => '查询总店信息失败']);
                }
            }

            // 查询账号设置表的经纬度
            $find_admin_set = DB::table('admin_set')
                ->where('adms_adm_id', $find_admin->adm_id)
                ->where('adms_shop_id', $find_admin->adm_shop_id)
                ->select('adms_province', 'adms_city', 'adms_county', 'adms_address', 'adms_longitude', 'adms_latitude')
                ->first();

            // 查询门店信息
            $find_shop = DB::table('shop')
                ->leftjoin('shop_relevance', 'shop.shop_id', '=', 'shop_relevance.shre_shop_id')
                ->where('shop_id', $find_admin->adm_shop_id)
                ->select('shop_state', 'shop_superior_id', 'shop_store_name', 'shop_type', 'shop_longitude', 'shop_latitude', 'shop_province', 'shop_city', 'shop_county', 'shop_address', 'shop_versions', 'shop_source_identify', 'shre_shop_id')
                ->first();
            if (!empty($find_shop->shre_shop_id)) {
                $is_bind = 1;
            } else {
                $is_bind = 2;
            }
            if (!empty($find_admin_set)) {
                if ($find_admin_set->adms_longitude != '0' && $find_shop->shop_longitude != '0') {
                    $find_shop->shop_longitude = $find_admin_set->adms_longitude;
                    $find_shop->shop_latitude = $find_admin_set->adms_latitude;
                }
                if (empty($find_shop->shop_province)) {
                    $find_shop->shop_province = $find_admin_set->adms_province;
                    $find_shop->shop_city = $find_admin_set->adms_city;
                    $find_shop->shop_county = $find_admin_set->adms_county;
                }
            }
            // 查询账号所属门店是否停用
            if (!in_array($find_admin->adm_id, config('apisystem.pass_verification_admin'))) {
                if ($find_shop->shop_type == 3) {
                    $shop_superior_id = $find_admin->adm_shop_id;
                } else {
                    $shop_superior_id = $find_shop->shop_superior_id;
                }
                if ($find_shop->shop_superior_id == 0) {
                    $shop_set_superior_id = $find_admin->adm_shop_id;
                } else {
                    $shop_set_superior_id = $find_shop->shop_superior_id;
                }
            } else {
                $shop_superior_id = 0;
                $shop_set_superior_id = 1;
            }

            // 生成token
            $unique_string = md5(uniqid(md5(microtime(true)) . rand(100000, 999999), true)); //生成唯一字符串
            $api_token = sha1($unique_string); //加密
            // 获取用户对应角色权限
            $role_auth = $this->getRolePrivilege($find_admin);
            // 确认此账号默认跳转页面
            $default_url = $this->getDefaultPath($role_auth['role_auth']);

            // 如果用户第一次登陆,将用户的登录状态保存到临时表
            $lote_data['adm_id'] = $find_admin->adm_id; //账号id
            $lote_data['last_login'] = time() + 30 * 24 * 60 * 60; //最后登陆时间
            $lote_data['api_token'] = $api_token; //api_token
            $lote_data['adm_name'] = $find_admin->adm_name; //账号姓名
            $lote_data['adm_phone'] = $find_admin->adm_phone; //手机号
            $lote_data['adm_cid'] = $find_admin->adm_cid; //公司id
            $lote_data['adm_shop_id'] = $find_admin->adm_shop_id; //门店id
            $lote_data['shop_superior_id'] = $shop_superior_id; //所属总店id
            $lote_data['shop_versions'] = $find_shop->shop_versions; //系统版本：1门店版2运营中心版
            $appid = config('apisystem.tea_appid');
            $appsecret = config('apisystem.tea_appsecret');
            if (isset($request['js_code'])) {
                $js_code = $request['js_code'];//小程序传值
                // 登录凭证校验。
                $url = "https://api.weixin.qq.com/sns/jscode2session?appid=".$appid."&secret=".$appsecret."&js_code=".$js_code."&grant_type=authorization_code";
                $result = file_get_contents($url);
                $code2Session = json_decode($result, true);//小程序登录返回的数据
                if(empty($code2Session['openid'])){
                    return response()->json(['code'=>4000, 'msg'=>'登录凭证校验失败 '.$code2Session['errcode'], 'data'=>'']);
                }else{
                    return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$code2Session['openid']]);
                }
            }
            $lote_data['type'] = $request['type']; //type
            $lote_data['role_auth'] = json_encode($role_auth['role_auth']); //当前账号所有角色权限
            $lote_data['auth_routes'] = json_encode($role_auth['routes_auth']); //当前账号所有角色权限路径
            $lote_res = DB::table('login_wechat_applet')->insert($lote_data);
            if (empty($lote_res)) {
                DB::rollBack();
                return response()->json(['code' => 500, 'msg' => 'api_token写入失败', 'data' => 'api_token写入失败']);
            }
            DB::table('admin_shop_role')->where('adm_id', $user_info->adm_id)->update(['login_shop_wechat'=>2]);
            DB::table('admin_shop_role')->where('adm_id', $user_info->adm_id)->where('shop_id', $shopId)->update(['login_shop_wechat'=>1]);

            // 返回数据
            DB::commit();
            $return_data = [
                'api_token' => Crypt::encrypt($api_token), //生成前台token
                'default_url' => $default_url, //默认跳转页面
                'adm_id' => $find_admin->adm_id,
                'adm_name' => $find_admin->adm_name,
                'adm_leave' => $find_admin->adm_leave,
                'adm_phone' => $find_admin->adm_phone,
                'msco_add_ord' => $find_admin->msco_add_ord,
                'shop_id' => $find_admin->adm_shop_id,
                'shop_store_name' => $find_shop->shop_store_name,
                'shop_type' => $find_shop->shop_type,
                'shop_province' => $find_shop->shop_province,
                'shop_city' => $find_shop->shop_city,
                'shop_county' => $find_shop->shop_county,
                'shop_longitude' => $find_shop->shop_longitude,
                'shop_latitude' => $find_shop->shop_latitude,
                'shop_source_identify' => $find_shop->shop_source_identify,
                'shop_versions' => $find_shop->shop_versions,
                'type' => $request['type'],
                'is_bind' => $is_bind,
                'return_moudle_id'=>$return_moudle_id
            ];
            return response()->json(['code' => 200, 'msg' => '登录成功', 'data' => $return_data]);

        }
    }

    public function getPri(Request $request)
    {
        request()->offsetSet('rt', 'wechat');
        $user_info = LoginUserService::getUser();
        // 查询账号信息
        $find_admin = DB::table('admin as adm')
             ->leftjoin('admin_shop_role as asr', 'asr.adm_id', '=', 'adm.adm_id')
            ->leftjoin('role', 'role.rol_id', '=', 'asr.role_id')
            ->leftjoin('shop', 'shop.shop_id', '=', 'asr.shop_id')
            ->where('adm.adm_id', $user_info->adm_id)
            ->where('asr.shop_id', $user_info->adm_shop_id)
            ->select('adm.adm_id', 'adm.adm_name', 'adm.adm_account', 'adm.adm_phone', 'asr.shop_cid as adm_cid', 'asr.shop_id as adm_shop_id', 'asr.adm_state', 'rol_state', 'rol_privilege', 'rol_privilege_multiple', 'asr.superior_shop_id as adm_superior_shop_id', 'shop_source_identify', 'adm_experience', 'adm_shop_leave', 'adm_remind')
            ->first();
        // 查找此用户对应得角色权限
        $role_auth = $this->getRolePrivilege($find_admin);
        $find_most = [];
        $new_data = [];
        if ($find_admin->adm_shop_leave != 1) {
            // $find_admin->adm_experience = 1;
            $find_admin->adm_remind = 2;
        } else {
            $update_data['most_nums'] = DB::table('order')
                ->where('ord_shop_id', $find_admin->adm_shop_id)
                ->where('ord_source', 3)
                ->count();
            if ($update_data['most_nums'] >= 3) {
                $update_data['most_remind'] = 2;
            }
            $update_data['most_update_time'] = date('Y-m-d H:i:s');
            $update_res = DB::table('moudle_statistics')
                ->where('most_shop_id', $find_admin->adm_shop_id)
                ->where('most_adm_id', $find_admin->adm_id)
                ->where('most_moudle_id', 1)
                ->update($update_data);
            $find_most = DB::table('moudle_statistics')
                ->leftjoin('moudle_data', 'moudle_id', '=', 'most_moudle_id')
                ->where('most_shop_id', $find_admin->adm_shop_id)
                ->where('most_adm_id', $find_admin->adm_id)
                ->where('most_remind', 1)
                ->where('most_prompt_date', '<', date('Y-m-d H:i:s'))
                ->select('most_moudle', 'most_moudle_id', 'image', 'text')
                ->get()->toArray();
            $most_moudle_id = array_column($find_most,'most_moudle_id');
            foreach ($role_auth['role_auth'] as $key => $value) {
                foreach ($find_most as $k => $v) {
                    if ($value['pri_id'] == 9 && $value['have_pri'] == 1 && $v->most_moudle_id == 1) {
                        $new_data[] = $v;
                    }
                    if ($value['pri_id'] == 17 && $value['have_pri'] == 1 && $v->most_moudle_id == 2) {
                        $new_data[] = $v;
                    }
                    if ($value['pri_id'] == 20 && $value['have_pri'] == 1 && $v->most_moudle_id == 3) {
                        $new_data[] = $v;
                    }
                    if ($value['pri_id'] == 11 && $value['have_pri'] == 1 && $v->most_moudle_id == 4) {
                        $new_data[] = $v;
                    }
                    if ($value['pri_id'] == 21 && $value['have_pri'] == 1 && $v->most_moudle_id == 5) {
                        $new_data[] = $v;
                    }
                }
            }
            $find_admin->adm_remind = 1;
        }
        $new_data = [];
        return response()->json(['code'=>200, 'msg'=>'技师权限', 'data'=>$role_auth, 'adm_experience'=>$find_admin->adm_experience, 'adm_remind'=>$find_admin->adm_remind, 'moudle_statistics'=>$new_data]);
    }

    /**
     * 获取更新提醒
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2023-07-31
     * @param  Request          $request [description]
     * @return [type]                    [description]
     */
    public function getReminder(Request $request)
    {
        request()->offsetSet('rt', 'wechat');
        $user_info = LoginUserService::getUser();
        $date = date('Y-m-d H:i:s');
        $find_online = DB::table('online_management')
            ->where('onma_state', 1)
            ->where('onma_start_time', '>', $date)
            ->first();
        if ($find_online) {
            // 查询账号是否关闭提示
            $find_admin = DB::table('update_reminder')
                ->where('upre_onma_id', $find_online->onma_id)
                ->where('upre_adm_id', $user_info->adm_id)
                ->first();
            if ($find_admin) {
                return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$find_online->onma_content, 'id'=>$find_online->onma_id, 'state'=>1]);
            } else {
                return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$find_online->onma_content, 'id'=>$find_online->onma_id, 'state'=>2]);
            }
        } else {
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'']);
        }
    }

    /**
     * 首页不再提醒引导
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2024-04-10
     * @param  Request          $request [description]
     * @return [type]                    [description]
     */
    public function unremind(Request $request) {
        request()->offsetSet('rt', 'wechat');
        $user_info = LoginUserService::getUser();
        $update_data['adm_remind'] = 2;
        $update_data['adm_update_time'] = date('Y-m-d H:i:s');
        $update_res = DB::table('admin')
            ->where('adm_id', $user_info->adm_id)
            ->update($update_data);
        return response()->json(['code'=>200, 'msg'=>'体验成功', 'data'=>'']);
    }

    /**
     * 立即体验
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2024-04-10
     * @param  Request          $request [description]
     * @return [type]                    [description]
     */
    public function experience(Request $request) {
        request()->offsetSet('rt', 'wechat');
        $user_info = LoginUserService::getUser();
        $update_data['adm_experience'] = 1;
        $update_data['adm_update_time'] = date('Y-m-d H:i:s');
        $update_res = DB::table('admin')
            ->where('adm_id', $user_info->adm_id)
            ->update($update_data);
        return response()->json(['code'=>200, 'msg'=>'体验成功', 'data'=>'']);
    }

    /**
     * 关闭更新提醒
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2023-07-31
     * @param  Request          $request [description]
     * @return [type]                    [description]
     */
    public function closeReminder(Request $request)
    {
        request()->offsetSet('rt', 'wechat');
        $user_info = LoginUserService::getUser();
        $find_admin = DB::table('update_reminder')
            ->where('upre_onma_id', $request['id'])
            ->where('upre_adm_id', $user_info->adm_id)
            ->first();
        if ($find_admin) {
            return response()->json(['code'=>500, 'msg'=>'此提醒已关闭', 'data'=>'']);
        }
        $add_data['upre_onma_id'] = $request['id'];
        $add_data['upre_adm_id'] = $user_info->adm_id;
        $add_data['upre_create_time'] = date('Y-m-d H:i:s');
        $add_res = DB::table('update_reminder')->insert($add_data);
        if ($add_res) {
            return response()->json(['code'=>200, 'msg'=>'关闭成功', 'data'=>'']);
        } else {
            return response()->json(['code'=>500, 'msg'=>'关闭失败', 'data'=>'']);
        }
    }

    public function getToken(Request $request)
    {
        $appid = config('apisystem.tea_appid');
        $appsecret = config('apisystem.tea_appsecret');
        $js_code = $request['js_code'];//小程序传值
        // 登录凭证校验。
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=".$appid."&secret=".$appsecret."&js_code=".$js_code."&grant_type=authorization_code";
        $result = file_get_contents($url);
        $code2Session = json_decode($result, true);//小程序登录返回的数据
        if(empty($code2Session['openid'])){
            return response()->json(['code'=>500, 'msg'=>'登录凭证校验失败 '.$code2Session['errcode'], 'data'=>'']);
        }
        // 根据openid获取账号信息
        $find_admin_openid = DB::table('login_wechat_applet')
            ->where('opend_id', $code2Session['openid'])
            ->select('adm_id', 'adm_name', 'type', 'api_token')
            ->first();
        if ($find_admin_openid) {
            if ($find_admin_openid->type == 1) {
                // 查询账号信息
                $find_admin = DB::table('admin as adm')
                     ->leftjoin('admin_shop_role as asr', 'asr.adm_id', '=', 'adm.adm_id')
                    ->leftjoin('role', 'role.rol_id', '=', 'asr.role_id')
                    ->where('adm.adm_id', $find_admin_openid->adm_id)
                    ->select('adm.adm_id', 'adm.adm_name', 'adm.adm_account', 'adm.adm_phone', 'asr.shop_cid as adm_cid', 'asrt.shop_id as adm_shop_id', 'asr.adm_state', 'rol_state', 'rol_privilege', 'rol_privilege_multiple', 'asr.superior_shop_id as adm_superior_shop_id')
                    ->first();
                // 查询门店信息
                $find_shop = DB::table('shop')
                    ->where('shop_id', $find_admin->adm_shop_id)
                    ->select('shop_state', 'shop_superior_id', 'shop_store_name', 'shop_type', 'shop_longitude', 'shop_latitude', 'shop_province', 'shop_city', 'shop_county', 'shop_address', 'shop_versions')
                    ->first();
            } else {
                // 查询企业客户
                $find_buac = DB::table('business_account')
                    ->where('buac_id', $find_admin_openid->adm_id)
                    ->where('buac_del', 1)
                    ->select('buac_id', 'buac_name', 'buac_phone', 'buac_cid', 'buac_shop_id', 'buac_bucl_id')
                    ->first();
                // 查询门店信息
                $find_shop = DB::table('shop')
                    ->where('shop_id', $find_buac->buac_shop_id)
                    ->select('shop_state', 'shop_superior_id', 'shop_store_name', 'shop_type', 'shop_longitude', 'shop_latitude', 'shop_province', 'shop_city', 'shop_county', 'shop_address', 'shop_versions')
                    ->first();
            }

            if ($find_admin_openid) {
                if ($find_admin_openid->type == 1) {
                    // 返回数据
                    $return_data = [
                        'api_token' => Crypt::encrypt($find_admin_openid->api_token), //生成前台token
                        'adm_id' => $find_admin->adm_id,
                        'adm_name' => $find_admin->adm_name,
                        'adm_phone' => $find_admin->adm_phone,
                        'shop_id' => $find_admin->adm_shop_id,
                        'shop_store_name' => $find_shop->shop_store_name,
                        'shop_type' => $find_shop->shop_type,
                        'shop_province' => $find_shop->shop_province,
                        'shop_city' => $find_shop->shop_city,
                        'shop_county' => $find_shop->shop_county,
                        'shop_longitude' => $find_shop->shop_longitude,
                        'shop_latitude' => $find_shop->shop_latitude,
                        'shop_versions' => $find_shop->shop_versions,//系统版本：1门店版2运营中心版
                        'type' => $find_admin_openid->type
                    ];
                } else {
                    // 返回数据
                    $return_data = [
                        'api_token' => Crypt::encrypt($find_admin_openid->api_token), //生成前台token
                        'buac_id' => $find_buac->buac_id,
                        'buac_name' => $find_buac->buac_name,
                        'buac_phone' => $find_buac->buac_phone,
                        'shop_id' => $find_buac->buac_shop_id,
                        'shop_store_name' => $find_shop->shop_store_name,
                        'shop_type' => $find_shop->shop_type,
                        'shop_province' => $find_shop->shop_province,
                        'shop_city' => $find_shop->shop_city,
                        'shop_county' => $find_shop->shop_county,
                        'shop_longitude' => $find_shop->shop_longitude,
                        'shop_latitude' => $find_shop->shop_latitude,
                        'shop_versions' => $find_shop->shop_versions,//系统版本：1门店版2运营中心版
                        'type' => 2,//类型1技师2合作商
                    ];
                }
                return response()->json(['code'=>200, 'msg'=>'登录成功', 'data'=>$return_data]);
            } else {
                return response()->json(['code'=>500, 'msg'=>'未登录,请先登录', 'data'=>'未登录,请先登录']);
            }
        } else {
            return response()->json(['code'=>500, 'msg'=>'未查询到技师', 'data'=>'未查询到技师']);
        }
    }

    // 退出
    public function quit(Request $request)
    {
        try {
            $api_token = Crypt::decrypt($request['api_token']);
        } catch (\Exception $e) {
            return response()->json(['code'=>500, 'msg'=>'api_token失效', 'data'=>'api_token失效']);
        }
        DB::beginTransaction();
        $find_admin = DB::table('login_wechat_applet')
            ->where('api_token', $api_token)
            ->select('adm_id')
            ->first();
        if ($find_admin) {
            // 更改最后登录时间
            $res = DB::table('login_wechat_applet')
                ->where('api_token', $api_token)
                ->update(['last_login' => 0, 'type' => '', 'opend_id' => '']);
            if ($request['type'] == 1) {
                // 更改技师openid
                $adm_res = DB::table('admin')
                    ->where('adm_id', $find_admin->adm_id)
                    ->update(['adm_open_id' => '', 'adm_update_time'=>date('Y-m-d H:i:s')]);
            } else {
                // 更改合作商openid
                $adm_res = DB::table('business_account')
                    ->where('buac_id', $find_admin->adm_id)
                    ->update(['buac_open_id' => '']);
            }
        } else {
            $res = true;
            $adm_res = true;
        }
        
        if ($res && $adm_res) {
            DB::commit();
            return response()->json(['code'=>200, 'msg'=>'退出成功', 'data'=>'退出成功']);
        } else {
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'退出失败', 'data'=>'退出失败']);
        }
    }

    /**
     * 更换微信 获取验证码
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2024-07-04
     * @param  Request          $request [description]
     * @return [type]                    [description]
     */
    public function getSmsCode(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyLoginController;
        $error_message = $verify_data->getCodeValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 判断手机号是否存在于该系统中
        $user_info = DB::table('admin as a')
            ->leftjoin('admin_shop_role as asr', 'asr.adm_id', '=', 'a.adm_id')
            ->leftjoin('role', 'role.rol_id', '=', 'asr.role_id')
            ->where('a.adm_phone', $request['adm_phone'])
            ->select('a.adm_id', 'a.adm_name', 'rol_state', 'asr.shop_cid as adm_cid', 'asr.shop_id as adm_shop_id', 'asr.adm_state', 'rol_state')
            ->first();
        if (empty($user_info)) {
            return response()->json(['code'=>202, 'msg'=>'您的手机号码未注册，是否前往注册', 'data'=>'您的手机号码未注册，是否前往注册']);
        }
        if ($user_info->adm_state == 2) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'该手机号已被停用']);
        }
        if ($user_info->rol_state != 1) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前账号所属角色权限已被停用']);
        }

        $code = mt_rand(100000, 999999); //生成六位验证码
        $message = "【半径服务】您所使用的半径美装小程序正在更换微信，账号的验证码为".$code."，十分钟内有效。"; //短信信息
        $now_time = date('Y-m-d H:i:s');
        $phc_data['phc_phone'] = $request['adm_phone'];
        $phc_data['phc_code'] = $code;
        $phc_data['phc_type'] = 1;
        $phc_data['phc_creacttime'] = $now_time;
        $phc_data['phc_expirationtime'] = date('Y-m-d H:i:s', strtotime($now_time) + 600); //过期时间

        // 查看是否发送验证码
        $find_phone_code = DB::table('phone_code')
            ->where('phc_type', 1)
            ->where('phc_phone', $request['adm_phone'])
            ->orderBy('phc_id', 'desc')
            ->first(['phc_id', 'phc_code', 'phc_type', 'phc_expirationtime']);
        $need_send = false;
        if ($find_phone_code) {
            if ($find_phone_code->phc_type == 1 && $find_phone_code->phc_expirationtime > date('Y-m-d H:i:s')) {
                return response()->json(['code'=>200, 'msg'=>'短信验证码已发送，十分钟内到期。', 'data'=>'短信验证码已发送，十分钟内到期。']);
            } else {
                $need_send =true;
            }
        } else {
            $need_send =true;
        }
        DB::beginTransaction();
        if(isset($request['send_type']) && $request['send_type']==1){
            $send = true;
        }else {
            $send = isSend($user_info, 6);
        }
        if ($send && $need_send) {
            // 2.给技师发送短信
            $phone = $request['adm_phone'];
            if (preg_match("/^1[3456789]\d{9}$/", $phone)) {
                $find_shop_data = DB::table('shop')
                    ->where('shop_id', $user_info->adm_shop_id)
                    ->first();
                if ($find_shop_data->shop_message_num <= 0 && (!isset($request['send_type']) || $request['send_type']!=1)) {
                    $send_state = 2;
                    $send_res = 0;
                } else {
                    if ($find_shop_data->shop_message_num <= 0 && isset($request['send_type']) && $request['send_type']==1) {
                        $user_info->adm_shop_id = 2;
                    }
                    $msg_remind_log = DB::table('msg_remind_log')
                        ->where('mrlo_shop_id', $user_info->adm_shop_id)
                        ->where('mrlo_state', 2)
                        ->first();
                    if ($msg_remind_log) {//已提醒过
                        if ($find_shop_data->shop_message_num > $find_shop_data->shop_msg_remind) {
                            $update_remind['mrlo_state'] = 1;
                            $msg_remind_log = DB::table('msg_remind_log')
                                ->where('mrlo_shop_id', $user_info->adm_shop_id)
                                ->where('mrlo_state', 2)
                                ->update($update_remind);
                        }
                    }

                    // 短信不足提醒
                    if (($find_shop_data->shop_message_num-1) <= $find_shop_data->shop_msg_remind && empty($msg_remind_log) && $find_shop_data->shop_msg_adm_id) {
                        $adm_data = DB::table('admin')->where('adm_id', $find_shop_data->shop_msg_adm_id)->first();
                        // $wechat_msg['pushtype'] = 5; //短信预警
                        // $wechat_msg['adm_id'] = $find_shop_data->shop_msg_adm_id; //推送人
                        // $wechat_msg['user_data'] = $adm_data->adm_name; //姓名
                        // $wechat_msg['tittle'] = '剩余短信不足'.$find_shop_data->shop_msg_remind.'条，请及时充值'; //提醒消息
                        // $wechat_msg['remark'] = '短信不足预警';
                        // $CashierDesk = new CashierDesk;
                        // $wechat_msg_res = $CashierDesk->inforPush($wechat_msg);
                        $remind_phone = $adm_data->adm_phone;
                        $remind_content = '【半径服务】 您的门店短信余额不足'.$find_shop_data->shop_msg_remind.'条，请及时充值';
                        $remind_send_res = sendSmsCode($remind_phone, $remind_content);
                        if ($remind_send_res > 0) {
                            $send_state = 1;
                            $add_remind['mrlo_shop_id'] = $user_info->adm_shop_id;
                            $add_remind['mrlo_state'] = 2;//未充值，
                            $add_remind['mrlo_adm_id'] = $find_shop_data->shop_msg_adm_id;
                            $add_remind['mrlo_num'] = $find_shop_data->shop_msg_remind;
                            $add_remind['mrlo_create_time'] = date('Y-m-d H:i:s');
                            $add_remind['mrlo_create_id'] = $user_info->adm_id;
                            $reming_res = DB::table('msg_remind_log')->insertGetId($add_remind);
                        } else {
                            $send_state = 2;
                        }
                        // 短信模块日志
                        $seme_data['seme_cid'] = $user_info->adm_cid; //公司id
                        $seme_data['seme_shop_id'] =$user_info->adm_shop_id; //门店id
                        $seme_data['seme_wor_id'] = 0; //订单id
                        $seme_data['seme_name'] = '短信不足预警'; //模板名称
                        $seme_data['seme_phone'] = $remind_phone; //手机号
                        $seme_data['seme_content'] = $remind_content; //内容
                        $seme_data['seme_row'] = 1; //条数
                        $seme_data['seme_status_code'] = $remind_send_res; //短信状态码
                        $seme_data['seme_state'] = $send_state; //状态：1成功2失败
                        $seme_data['seme_ip'] = getRealIp($request); //ip地址
                        $seme_data['seme_adm_id'] = $user_info->adm_id; //创建人id
                        $seme_id = DB::table('send_message')->insert($seme_data);
                    }
                    $send_res = sendSmsCode($phone, $message);
                    if ($send_res > 0) {
                        $send_state = 1;
                        $update_shop = DB::table('shop')
                            ->where('shop_id', $user_info->adm_shop_id)
                            ->update(['shop_message_num'=>$find_shop_data->shop_message_num - 1]);
                    } else {
                        $send_state = 2;
                    }
                }
                // 短信模块日志
                $seme_data['seme_cid'] = $user_info->adm_cid; //公司id
                $seme_data['seme_shop_id'] =$user_info->adm_shop_id; //门店id
                $seme_data['seme_wor_id'] = 0; //订单id
                $seme_data['seme_name'] = '技师登录更换微信下发验证码'; //模板名称
                $seme_data['seme_phone'] = $phone; //手机号
                $seme_data['seme_content'] = $message; //内容
                $seme_data['seme_row'] = 1; //条数
                $seme_data['seme_status_code'] = $send_res; //短信状态码
                $seme_data['seme_state'] = $send_state; //状态：1成功2失败
                $seme_data['seme_ip'] = getRealIp($request);; //ip地址
                $seme_data['seme_adm_id'] = $user_info->adm_id; //创建人id
                $seme_id = DB::table('send_message')->insert($seme_data);

                
                $add_log['smlo_shop_id'] = $user_info->adm_shop_id;
                $add_log['smlo_mem_type'] = 1;//1业务人员2会员
                $add_log['smlo_mem_id'] = $user_info->adm_id;
                $add_log['smlo_mem_name'] = $user_info->adm_name;
                $add_log['smlo_mem_phone'] = $phone;
                $add_log['smlo_type'] = 2;
                $add_log['smlo_create_time'] = date('Y-m-d H:i:s');
                $add_log['smlo_state'] = $send_state;
                $add_log['smlo_msg_type'] = 4;
                $add_log['smlo_num'] = 1;
                $add_log['smlo_content'] = $message; //内容
                $add_log_res = DB::table('sms_log')->insertGetId($add_log);
            } else {
                $send_res = false;
            }
            if ($send_res) {
                $phc_res = DB::table('phone_code')->insertGetId($phc_data);
            } else {
                $phc_res = false;
            }
            if ($phc_res && $send_res > 0) {
                DB::commit();
                Common::addLog($user_info, getRealIp($request), '忘记密码', '获取验证码', $request['adm_phone'] . '发送验证码成功');
                return response()->json(['code'=>200, 'msg'=>'验证码发送成功', 'data'=>'验证码发送成功']);
            } else {
                DB::rollBack();
                return response()->json(['code'=>500, 'msg'=>'验证码发送失败,请联系管理员', 'data'=>['phc_res'=>$phc_res,'send_res'=>$send_res]]);
            }
        } else {
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'验证码发送失败,请联系管理员', 'data'=>['send'=>$send,'need_send'=>$need_send]]);
        }
    }

    // 忘记密码--获取验证码
    public function getCode(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyLoginController;
        $error_message = $verify_data->getCodeValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 判断手机号是否存在于该系统中
        $user_info = DB::table('admin as adm')
             ->leftjoin('admin_shop_role as asr', 'asr.adm_id', '=', 'adm.adm_id')
            ->leftjoin('role', 'role.rol_id', '=', 'asrt.role_id')
            ->where('adm.adm_phone', $request['adm_phone'])
            ->select('adm.adm_id', 'adm.adm_name', 'rol_state', 'asr.shop_cid as adm_cid', 'asr.shop_id as adm_shop_id', 'asr.adm_state', 'rol_state')
            ->first();
        if (empty($user_info)) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'该手机号不存在于系统中']);
        }
        if ($user_info->adm_state == 2) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'该手机号已被停用']);
        }
        if ($user_info->rol_state != 1) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前账号所属角色权限已被停用']);
        }

        $code = mt_rand(100000, 999999); //生成六位验证码
        $message = "您所使用的\"门店助手系统\"账号的验证码为{$code}，十分钟内有效。"; //短信信息
        $now_time = date('Y-m-d H:i:s');
        $phc_data['phc_phone'] = $request['adm_phone'];
        $phc_data['phc_code'] = $code;
        $phc_data['phc_type'] = 1;
        $phc_data['phc_creacttime'] = $now_time;
        $phc_data['phc_expirationtime'] = date('Y-m-d H:i:s', strtotime($now_time) + 600); //过期时间

        // 查看是否发送验证码
        $find_phone_code = DB::table('phone_code')
            ->where('phc_phone', $request['adm_phone'])
            ->first(['phc_id', 'phc_code', 'phc_type', 'phc_expirationtime']);

        DB::beginTransaction();
        if ($find_phone_code) {
            if ($find_phone_code->phc_type == 1 && $find_phone_code->phc_expirationtime > date('Y-m-d H:i:s')) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'短信验证码已发送，十分钟内到期。']);
            } else {
                $send_res = sendSmsCode($request['adm_phone'], $message);
                $phc_data['phc_send_code'] = $send_res; //短信发送返回值
                $phc_res = DB::table('phone_code')
                    ->where('phc_id', $find_phone_code->phc_id)
                    ->update($phc_data);
            }
        } else {
            $send_res = sendSmsCode($request['adm_phone'], $message);
            $phc_data['phc_send_code'] = $send_res; //短信发送返回值
            $phc_res = DB::table('phone_code')->insert($phc_data);
        }

        if ($phc_res && $send_res != -5) {
            DB::commit();
            Common::addLog($user_info, getRealIp($request), '忘记密码', '获取验证码', $request['adm_phone'] . '发送验证码成功');
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'验证码发送成功']);
        } else {
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'验证码发送失败']);
        }
    }

    // 忘记密码--提交
    public function forgetPwd(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyLoginController;
        $error_message = $verify_data->forgetPwdValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 验证 验证码是否正确
        $find_phone_code = DB::table('phone_code')
            ->where('phc_phone', $request['adm_phone'])
            ->where('phc_code', $request['code'])
            ->first(['phc_id', 'phc_type', 'phc_expirationtime']);
        if (empty($find_phone_code)) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'验证码错误']);
        }
        if ($find_phone_code->phc_type != 1) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前验证码已使用，请重新获取验证码']);
        }
        if ($find_phone_code->phc_expirationtime < date('Y-m-d H:i:s')) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前验证码已过期失效，请重新获取验证码']);
        }

        DB::beginTransaction();
        // 更改验证码状态
        $phc_res = DB::table('phone_code')
            ->where('phc_id', $find_phone_code->phc_id)
            ->update(['phc_type' => 2]);
        // 更改密码
        $user_info = DB::table('admin')
            ->leftJoin('admin_shop_role as asr', 'asr.adm_id', '=', 'admin.adm_id')
            ->where('admin.adm_phone', $request['adm_phone'])
            ->first(['admin.adm_id', 'asr.shop_cid as adm_cid', 'asr.shop_id as adm_shop_id', 'admin.adm_name', 'admin.adm_phone', 'asrt.adm_state']);
        $edit_pwd['adm_password'] = md5($request['pwd'] . 'faster123456');
        $edit_pwd['adm_update_time'] = date('Y-m-d H:i:s');
        $adm_res = DB::table('admin')
            ->where('adm_id', '=', $user_info->adm_id)
            ->update($edit_pwd);

        if ($phc_res && $adm_res) {
            DB::commit();
            Common::addLog($user_info, getRealIp($request), '忘记密码', '重设密码', $request['adm_phone'] . '重设密码成功');
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'重设成功']);
        } else {
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'重设失败']);
        }
    }

    /**
     * [getRolePrivilege 获取角色权限]
     * @param  [type] $find_admin [用户信息]
     * @return [type]                [description]
     */
    public function getRolePrivilege($find_admin)
    {   
        // 判断是否使用新的角色权限字段
        if ($find_admin->rol_privilege_multiple) {
            // 新的权限ID字段
            $rol_privilege = json_decode($find_admin->rol_privilege_multiple, true);
            $rol_privilege = $rol_privilege['applet'];//小程序端权限
        } else {
            // 之前的权限ID字段
            $rol_privilege = $find_admin->rol_privilege;
        }
        $pri_id = explode(',', $rol_privilege);
        // 查询权限id对应的权限数据
        $privileges = DB::table('privileges_technician_applet')
            // ->whereIn('pri_id', $pri_id)
            ->where('pri_show', 1)
            ->get()->toArray();
        $privileges = json_decode(json_encode($privileges), true);
        $privileges = array_values($privileges);
        $privileges_info['role_auth1'] = [];
        $privileges_info['role_auth2'] = [];
        $privileges_info['role_auth3'] = [];
        foreach ($privileges as $key => $value) {
            if ($find_admin->shop_source_identify == '5' && in_array($value['pri_id'],$pri_id)) {//入驻的门店
                $applet_role = DB::table('privileges_technician_applet')
                    ->whereRaw("FIND_IN_SET('4', pri_default)")
                    ->whereNotIn('pri_id',[37,38,39,40,41,42,10])
                    ->get()->toArray();
                $app_role_arr = [9,11,17,20,21];
                if($applet_role){
                    foreach ($applet_role as $app_r_key => $app_r_value){
                        $app_role_arr[] = intval($app_r_value->pri_id);
                    }
                }
                if (in_array($value['pri_id'],$app_role_arr)) {
                    $value['have_pri'] = 2;//技师是否有此权限1是2否
                    $privileges[$key]['have_pri'] = 1;
                } else {
                    $value['have_pri'] = 1;
                    $privileges[$key]['have_pri'] = 2;
                }
                if ($value['pri_position'] == 1) {//我的任务
                    // 角色权限
                    $privileges_info['role_auth1'][] = $value;
                } elseif ($value['pri_position'] == 2) {
                    $privileges_info['role_auth2'][] = $value;
                } elseif ($value['pri_position'] == 3) {
                    $privileges_info['role_auth3'][] = $value;
                } elseif ($value['pri_position'] == 5) {
                    $privileges_info['role_auth5'][] = $value;
                } else {
                    $privileges_info['role_auth4'][] = $value;
                }
            } else {
                if (in_array($value['pri_id'],$pri_id)) {
                    $value['have_pri'] = 1;//技师是否有此权限1是2否
                    $privileges[$key]['have_pri'] = 1;
                    if ($value['pri_position'] == 1) {//我的任务
                        // 角色权限
                        $privileges_info['role_auth1'][] = $value;
                    } elseif ($value['pri_position'] == 2) {
                        $privileges_info['role_auth2'][] = $value;
                    } elseif ($value['pri_position'] == 3) {
                        $privileges_info['role_auth3'][] = $value;
                    } elseif ($value['pri_position'] == 5) {
                        $privileges_info['role_auth5'][] = $value;
                    } else {
                        $privileges_info['role_auth4'][] = $value;
                    }
                } else {
                    $value['have_pri'] = 2;//技师是否有此权限1是2否
                    $privileges[$key]['have_pri'] = 2;
                }
            }
            if ($value['have_pri'] == 1) {
                // 权限路由
                $privileges_info['routes_auth'][] = 'App\Http\Controllers\\'.$value['pri_controller'].'Controller'.'@'.$value['pri_operate_method'].',';
            }
        }
        $privileges_info['role_auth'] = $privileges;
        return $privileges_info;
    }

    // 获取页面默认跳转路径
    protected function getDefaultPath($arr)
    {
        $first['controller'] = '';
        $first['pri_id'] = 0;
        foreach ($arr as $key => $value) {
            if ($value['pri_id'] == 1) {
                // 有工作台权限，直接返回
                return $value['pri_controller'];
            }
            if ($value['pri_fid'] == 0) {
                // 第一个一级栏目
                $first['controller'] = $value['pri_controller'];
                $first['pri_id'] = $value['pri_id'];
                break;
            }
        }
        foreach ($arr as $key => $value) {
            if ($value['pri_fid'] == $first['pri_id']) {
                // 获取一级栏目下的列表方法，拼接成vue路由
                $vue_route = ltrim(strstr($value['pri_controller'], '\\'), '\\') . $value['pri_operate_method'];
                // 返回vue路由
                return $first['controller'] . '/' . $vue_route;
            }
        }
    }

    // 左侧一级二级导航
    public function leftList(Request $request)
    {
        // 获取路由信息
        $role_info = DB::table('login_wechat_applet')
            ->where('api_token', '=', $request['api_token'])
            ->select('role_auth')
            ->first();
        if (empty($role_info)) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'api_token已过期']);
        }

        // 对象转数组
        $role_info  = json_decode($role_info->role_auth, true);
        foreach ($role_info as $k => $v) {
            $role_info[$k]['name'] = $v['pri_controller'] . $v['pri_operate_method'];
            $role_info[$k]['path'] = $v['pri_controller'] . $v['pri_operate_method'];
            $role_info[$k]['meta']['title'] = $v['pri_method_name'];
            $role_info[$k]['meta']['pri_id'] = $v['pri_id'];
            unset($role_info[$k]['pri_method_name']);
            unset($role_info[$k]['pri_controller']);
            unset($role_info[$k]['pri_operate_method']);
        }
        // 获取二级两级导航栏
        //正则替换/
        foreach($role_info as $key => $value){
            $role_info[$key]['name']=preg_replace("/\w+\\\/",'',$value['name']);
            $role_info[$key]['path']=preg_replace("/\w+\\\/",'',$value['path']);
        }
        // 将数据分类
        $navigation_category = $this->navigation_category($role_info);

        // 将数据根据数据库中的pri_sord从小到大排序
        // pri_type = 1的排序
        $last_names = array_column($navigation_category, 'pri_sord');
        array_multisort($last_names, SORT_ASC, $navigation_category);
        //pri_type = 2的排序
        foreach ($navigation_category as $key => $value) {
            if (!empty($value['children'])) {
                $last_names = array_column($value['children'], 'pri_sord');
                array_multisort($last_names, SORT_ASC, $value['children']);
                $navigation_category[$key]['children'] = $value['children'];
            }
        }

        foreach ($navigation_category as $key => $value) {
            $navigation_category[$key]['component'] = 'Layout';
        }
        foreach ($navigation_category as $key => $value) {
            // if($value['pri_id'] == 1)
            // {
            //     $navigation_category[$key]['redirect'] = $value['name'];
            //     $navigation_category[$key]['children'][] = $value;
            //     foreach($value as $k=>$v)
            //     {
            //         $navigation_category[$key]['children'][$key]['component'] = $value['name'];
            //     }
            // }
            if ($value['pri_fid'] !== 0) {
                unset($value['pri_img']);
            }
        }
        if (!$navigation_category) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'导航获取失败']);
        }
        return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$navigation_category]);
    }

    // 导航栏分类
    protected function navigation_category($arr)
    {
        $refer = array();
        $list = array();
        foreach ($arr as $k => $v) {
            $refer[$v['pri_id']] = &$arr[$k]; //创建主键的数组引用
        }
        foreach ($arr as $k => $v) {
            $fid = $v['pri_fid'];  //获取当前分类的父级id
            if ($fid == 0) {
                $list[] = &$arr[$k];  //顶级栏目
            } else {
                if (isset($refer[$fid])) {
                    $refer[$fid]['children'][] = $arr[$k]; //如果存在父级栏目，则添加进父级栏目的子栏目数组中
                    foreach ($refer[$fid]['children'] as $key => $value) {
                        $refer[$fid]['children'][$key]['component'] = $value['name'];
                    }
                }
            }
        }
        return $list;
    }

    //获取open_id
    public function getOpenId(Request $request){
        $appid = config('apisystem.tea_appid');
        $appsecret = config('apisystem.tea_appsecret');
        if (isset($request['js_code'])) {
            $js_code = $request['js_code'];//小程序传值
            // 登录凭证校验。
            $url = "https://api.weixin.qq.com/sns/jscode2session?appid=".$appid."&secret=".$appsecret."&js_code=".$js_code."&grant_type=authorization_code";
            $result = file_get_contents($url);
            $code2Session = json_decode($result, true);//小程序登录返回的数据
            if(empty($code2Session['openid'])){
                return response()->json(['code'=>4000, 'msg'=>'登录凭证校验失败 '.$code2Session['errcode'], 'data'=>'']);
            }else{
                return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$code2Session['openid']]);
            }
        }
        return response()->json(['code'=>500, 'msg'=>'参数错误', 'data'=>'']);
    }
    /**|---------------------------------------------------------------------------------
     * @name 忘记密码
     * @param string phone 手机号
     * @param string phone_code 验证码
     * @param string password 验证码  $adm_pawd = md5($request['password'] . 'faster123456');
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2024/8/15 15:46
     * |---------------------------------------------------------------------------------
    */
    public function forgotPassword ( Request $request ){
        if(!isset($request['phone']) || empty($request['phone']) || !isset($request['phone_code']) || empty($request['phone_code']) || !isset($request['password']) || empty($request['password']) || !isset($request['signature']) || empty($request['signature']) || !isset($request['timestamp']) || empty($request['timestamp'])){
            return response()->json(['code'=>500, 'msg'=>'参数错误', 'data'=>'']);
        }else{
            $signature =  md5($request['phone'].$request['password'].$request['phone_code'].$request['timestamp'].'bjmz');
//            if($signature!=$request['signature']){
//                return response()->json(['code'=>500, 'msg'=>'签名错误', 'data'=>'签名错误']);
//            }
            $find_admin = DB::table('admin')->where('adm_phone',$request['phone'])->first();
            if($find_admin){
                $find_admin = CommonService::dataToArray($find_admin);
                // 验证 验证码是否正确
                $find_phone_code = DB::table('phone_code')
                    ->where('phc_phone', $request['phone'])
                    ->where('phc_code', $request['phone_code'])
                    ->first(['phc_id', 'phc_type', 'phc_expirationtime']);
                if (empty($find_phone_code)) {
                    return response()->json(['code'=>201, 'msg'=>'验证码错误', 'data'=>'验证码错误']);
                }
                if ($find_phone_code->phc_type != 1) {
                    return response()->json(['code'=>201, 'msg'=>'当前验证码已使用，请重新获取验证码', 'data'=>'当前验证码已使用，请重新获取验证码']);
                }
                if ($find_phone_code->phc_expirationtime < date('Y-m-d H:i:s')) {
                    return response()->json(['code'=>201, 'msg'=>'当前验证码已过期失效，请重新获取验证码', 'data'=>'当前验证码已过期失效，请重新获取验证码']);
                }
                DB::beginTransaction();
                // 更改验证码状态
                $phc_res = DB::table('phone_code')
                    ->where('phc_id', $find_phone_code->phc_id)
                    ->update(['phc_type' => 2]);
                $edit_pwd['adm_password'] = md5($request['password'] . 'faster123456');
                $edit_pwd['adm_update_time'] = date('Y-m-d H:i:s');
                $adm_res = DB::table('admin')->where('adm_id',$find_admin['adm_id'])->where('adm_phone',$request['phone'])->update($edit_pwd);
                if ($phc_res && $adm_res) {
                    DB::commit();
                    $add_data = [
                        'oplo_cid'=>0,
                        'oplo_shop_id'=>0,
                        'oplo_adm_id'=>0,
                        'oplo_adm_name'=>$request['phone'],
                        'oplo_module'=>'忘记密码',
                        'oplo_action'=>'重设密码',
                        'oplo_content'=>$request['phone'] . '重设密码成功',
                        'oplo_ip'=>getRealIp($request)
                    ];
                    DB::table('operation_log')->insert($add_data);
                    return response()->json(['code'=>200, 'msg'=>'重设密码成功', 'data'=>'重设成功']);
                } else {
                    DB::rollBack();
                    return response()->json(['code'=>500, 'msg'=>'重设密码失败', 'data'=>'重设失败']);
                }
            }else{
                return response()->json(['code'=>202, 'msg'=>'您的手机号码未注册，是否前往注册', 'data'=>'']);
            }
        }
    }
}
