<?php

namespace App\Services\WeChatApplet\User;

use Illuminate\Database\Eloquent\Model;
use App\Models\WeChatApplet\User\LoginUser;
use BlueCity\Core\Service\Service;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\DB;
//use App\Http\Requests\Validators\WeChatApplet\User\LoginUserValidator;
use BlueCity\Core\Inc\ErrorInc;
use Illuminate\Support\Facades\Crypt;
use App\Services\WeChatApplet\Technician\MemberService;

class LoginUserService extends Model
{
    public static $instance;
    public $modelMain = null;
    public $mainValidator = null;

    public function __construct()
    {
        $this->modelMain = new LoginUser();
        // $this->mainValidator = new LoginUserValidator();
    }

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

    /**
     * 自动登录
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2023-11-22
     * @param  [type]           $code2Session [description]
     * @param  [type]           $request      [description]
     * @return [type]                         [description]
     */
    public function weixinAuth($code2Session,$request)
    {
        // 根据openid查询用户id
        $weus_id = DB::table('weixin_user')
            ->where("weus_openid", $code2Session['openid'])
            ->value('weus_id');
        if ($weus_id) {
            //最后一次登录的账号
            $ussh_data = DB::table('user_shop')
                ->leftJoin('member', 'mem_id', '=', 'ussh_user_id')
                ->where('ussh_weus_id', $weus_id)
                ->where('ussh_now_login', 1)
                ->select('ussh_phone', 'ussh_user_id', 'mem_name', 'ussh_shop_id')
                ->orderBy('ussh_create_time', 'desc')
                ->first();
            if ($ussh_data) {
                $ussh_phone = $ussh_data->ussh_phone;
            } else {
                $ussh_phone = '';
            }
            $weus_data['weus_session_key'] = $code2Session['session_key'];
            $weus_data['weus_update_time'] = date('Y-m-d H:i:s');
            
            // 查询微信用户openid,手机号是否存在
            $find_weixin_data = DB::table('weixin_user')
                ->where('weus_id', $weus_id)
                ->select('weus_id', 'weus_phone', 'weus_nickmame', 'weus_headimgurl')
                ->first();
            $return_data = (array)$find_weixin_data;
            $return_data['weus_phone'] = $ussh_phone;
            $return_data['weus_nickmame'] = isset($ussh_data->mem_name) ? $ussh_data->mem_name : '';
            if ($request['new_shop_id']) {//根据shop_id查询是否绑定过门店
                $weus_data['weus_shop_id'] = $request['new_shop_id'];
                $find_user_info = DB::table('user_shop')
                    ->where('ussh_weus_id', $weus_id)
                    ->where('ussh_shop_id', $request['new_shop_id'])
                    ->select('ussh_user_id')
                    ->first();
                if (empty($find_user_info)) {//没有绑定门店
                    // $ussh_datas['ussh_weus_id'] = $weus_id;
                    // $ussh_datas['ussh_shop_id'] = $request['new_shop_id'] ? $request['new_shop_id'] : $request['shop_id'];
                    // $ussh_datas['ussh_user_type'] = 1;
                    // $ussh_datas['ussh_now_login'] = 2;
                    // $ussh_datas['ussh_phone'] = '';
                    // $ussh_datas['ussh_create_time'] = date('Y-m-d H:i:s');
                    // $ussh_datas['ussh_register_time'] = date('Y-m-d H:i:s');
                    // $ussh_id = DB::table('user_shop')->insertGetId($ussh_datas);
                    // if (!$ussh_id) {
                    //     return ['code'=>500, 'msg'=>'登录失败2', 'data'=>''];
                    // }
                    $return_data['ussh_user_id'] = '';
                    $return_data['meca_car_data'] = '';
                } else {
                    $return_data['ussh_user_id'] = $find_user_info->ussh_user_id;
                    $return_data['meca_car_data'] = DB::table('member_car')
                        ->where('meca_mem_id', $find_user_info->ussh_user_id)
                        ->where(function ($query) use ($request) { //门店id
                            if (!empty($request['new_shop_id'])) {
                                $query->where('meca_shop_id', $request['new_shop_id']);
                            }
                        })
                        ->where('meca_default', 1)
                        ->select('meca_car_num', 'meca_car_series', 'meca_car_model', 'meca_car_brand_series', 'meca_car_frame')
                        ->first();
                }
                $list_data = DB::table('shop')
                    ->where('shop_id', $request['new_shop_id'])
                    ->select('shop_id', 'shop_store_name', 'shop_phone', 'shop_province', 'shop_city', 'shop_county', 'shop_address', 'shop_image', 'shop_state', 'shop_longitude', 'shop_latitude', 'shop_versions')
                    ->first();
            } else {
                // 查询店铺信息
                $list_data = DB::table('weixin_user as a')
                    ->leftJoin('shop as b', 'a.weus_shop_id', '=', 'b.shop_id')
                    ->where('weus_id', $weus_id)
                    ->select('shop_id', 'shop_store_name', 'shop_phone', 'shop_province', 'shop_city', 'shop_county', 'shop_address', 'shop_image', 'shop_state', 'shop_longitude', 'shop_latitude', 'shop_versions')
                    ->first();

                if (empty($list_data)) {
                    $return_data['meca_car_data'] = '';
                    $return_data['ussh_user_id'] = '';
                } else {
                    $return_data['ussh_user_id'] = DB::table('user_shop')
                        ->where('ussh_weus_id', $weus_id)
                        ->where('ussh_shop_id', $list_data->shop_id)
                        ->where('ussh_now_login', 1)
                        ->value('ussh_user_id');
                    $return_data['meca_car_data'] = DB::table('member_car')
                        ->where(function ($query) use ($return_data) { //mem_id
                            if (!empty($return_data['ussh_user_id'])) {
                                $query->where('meca_mem_id', $return_data['ussh_user_id']);
                            }
                        })
                        ->where(function ($query) use ($list_data) { //门店id
                            if (!empty($list_data)) {
                                $query->where('meca_shop_id', $list_data->shop_id);
                            }
                        })
                        ->where('meca_default', 1)
                        ->select('meca_car_num', 'meca_car_series', 'meca_car_model', 'meca_car_brand_series', 'meca_car_frame')
                        ->first();
                }
            }
            $weus_res = DB::table('weixin_user')
                ->where("weus_id", $weus_id)
                ->update($weus_data);
            $return_data['shop_data'] = $list_data;
        } else {
            $ussh_phone = '';
            $weus_data['weus_openid'] = $code2Session['openid'];
            $weus_data['weus_session_key'] = $code2Session['session_key'];
            $weus_data['weus_shop_id'] = $request['new_shop_id'];
            $weus_data['weus_update_time'] = date('Y-m-d H:i:s');
            $weus_id = DB::table('weixin_user')->insertGetId($weus_data);
            // 查询微信用户openid,手机号是否存在
            $find_weixin_data = DB::table('weixin_user')
                ->where('weus_id', $weus_id)
                ->select('weus_id', 'weus_phone', 'weus_nickmame', 'weus_headimgurl')
                ->first();
            $return_data = (array)$find_weixin_data;

            if (!empty($request['new_shop_id'])) {
                // $ussh_datas['ussh_weus_id'] = $weus_id;
                // $ussh_datas['ussh_shop_id'] = $request['new_shop_id'];
                // $ussh_datas['ussh_user_type'] = 1;
                // $ussh_datas['ussh_now_login'] = 2;
                // $ussh_datas['ussh_phone'] = '';
                // $ussh_datas['ussh_create_time'] = date('Y-m-d H:i:s');
                // $ussh_datas['ussh_register_time'] = date('Y-m-d H:i:s');
                // $ussh_id = DB::table('user_shop')->insertGetId($ussh_datas);
                // if (!$ussh_id) {
                //     return ['code'=>500, 'msg'=>'登录失败2', 'data'=>''];
                // }
                $return_data['shop_data'] = DB::table('shop')
                    ->where('shop_id', $request['new_shop_id'])
                    ->select('shop_id', 'shop_store_name', 'shop_phone', 'shop_province', 'shop_city', 'shop_county', 'shop_address', 'shop_image', 'shop_state', 'shop_longitude', 'shop_latitude', 'shop_versions')
                    ->first();
            } else {
                // 查询店铺信息
                $return_data['shop_data'] = [];
            }
           
            $return_data['ussh_user_id'] = '';
            $return_data['meca_car_data'] = '';
        }
        if ($ussh_phone) {
            // 查询登录表id
            $login_id = DB::table('login_user_wechat_applet')
                ->where("openid", $code2Session['openid'])
                ->value('id');
            $unique_string = md5(uniqid(md5(microtime(true)) . rand(100000, 999999), true)); //生成唯一字符串
            $api_token = sha1($unique_string); //加密
            $crypt_api_token = Crypt::encrypt($api_token); //生成前台token
            if ($ussh_phone) {
                $old_login_res = DB::table('login_user_wechat_applet')
                    ->where('adm_phone', $ussh_phone)
                    ->update(['api_token'=>'']);
            }
            if ($login_id) {
                // 更新登录信息
                $login_data['session_key'] = $code2Session['session_key'];
                $login_data['adm_phone'] = $ussh_phone;
                $login_data['api_token'] = $api_token;
                $login_data['weus_id'] = $weus_id ? $weus_id : '';
                $login_data['last_login'] = time() + 4*60*60;//4个小时有效时间
                $login_res = DB::table('login_user_wechat_applet')
                    ->where("id", $login_id)
                    ->update($login_data);
            } else {
                // 插入登录信息
                $login_data['openid'] = $code2Session['openid'];
                $login_data['adm_phone'] = $ussh_phone;
                $login_data['weus_id'] = $weus_id ? $weus_id : '';
                $login_data['session_key'] = $code2Session['session_key'];
                $login_data['api_token'] = $api_token;
                $login_data['last_login'] = time() + 4*60*60;//4个小时有效时间
                $login_res = DB::table('login_user_wechat_applet')->insertGetId($login_data);
            }
        } else {
            $crypt_api_token = '';
        }

        $return_data['api_token'] = $crypt_api_token;
        $return_data['openid'] = $code2Session['openid'];
        $return_data['session_key'] = $code2Session['session_key'];
        return ['code'=>200, 'msg'=>'success', 'data'=>$return_data];
    }

    /*
     * @name 微信授权没有会员的时候添加会员
     * @param 微信用户信息
     * @retrun array
     * @author Ma 2023/10/19 14:41
     *
    */
    public static function addMemAuth($find_weixin_data,$shop_id,$phone){
        $find_mem_data = DB::table('member')
            ->where('mem_phone', $phone)
            ->where('mem_shop_id', $shop_id)
            ->select('mem_id', 'mem_name', 'mem_phone')
            ->first();
        if (empty($find_mem_data)) {
            $find_shop_cid = DB::table('shop')
                ->where('shop_id', $shop_id)
                ->value('shop_cid');
            // 新增门店会员
            $add_mem_data['mem_superior_shop_id'] = $shop_id;
            $add_mem_data['mem_cid'] = $find_shop_cid;
            $add_mem_data['mem_shop_id'] = $shop_id;
            $add_mem_data['mem_name'] =  $find_weixin_data->weus_nickmame;
            $add_mem_data['mem_phone'] =  $phone;
            $add_mem_data['mem_sex'] = 3;
            // $mem_id = DB::table('member')->insertGetId($add_mem_data);
            $mem_id = MemberService::addMember($add_mem_data);
        }else{
            $mem_id = $find_mem_data->mem_id;
        }
        return ['code'=>200, 'msg'=>'success', 'data'=>$mem_id];
    }

    // 微信授权
    public function pcweixinAuth($code2Session,$request)
    {
        // 根据openid查询用户id
        $adm_data = DB::table('admin as a')
            ->leftjoin('role', 'role.rol_id', '=', 'a.adm_role')
            ->where("adm_bjfw_openid", $code2Session['openid'])
            ->select('adm_id', 'adm_name', 'adm_account', 'adm_phone', 'adm_cid', 'adm_shop_id', 'adm_state', 'rol_state', 'rol_privilege', 'rol_privilege_multiple', 'adm_superior_shop_id', 'adm_bjfw_openid')
            ->first();
        $unique_string = md5(uniqid(md5(microtime(true)) . rand(100000, 999999), true)); //生成唯一字符串
        $api_token = sha1($unique_string); //加密
        $crypt_api_token = Crypt::encrypt($api_token); //生成前台token
        if ($adm_data) {//查询到此用户判断账号状态
            $update_adm_data['adm_session_key'] = $code2Session['session_key'];
            $update_adm_data['adm_update_time'] = date('Y-m-d H:i:s');
            $adm_res = DB::table('admin')
                ->where("adm_id", $adm_data->adm_id)
                ->update($update_adm_data);
            if (empty($adm_data->adm_phone)) {
                $return_data['adm_id'] = $adm_data->adm_id;
                $return_data['adm_phone'] = $adm_data->adm_phone;
                $return_data['adm_name'] = $adm_data->adm_name;
                $return_data['adm_bjfw_openid'] = $code2Session['openid'];
                $return_data['adm_session_key'] = $code2Session['session_key'];
                // $update_qrdata['shqr_scan_adm_id'] = $adm_data->adm_id;
                // $update_qrdata['shqr_state'] = 4;//二维码状态1未扫码2已扫码3取消失效4授权成功5过期失效
                // $update_qrdata['shqr_update_time'] = date('Y-m-d H:i:s');
                // $update_qrres = DB::table('shop_qr')
                //     ->where('shqr_number', $request['shqr_number'])
                //     ->update($update_qrdata);
                return ['code'=>300, 'msg'=>'请登录', 'data'=>$return_data, 'state'=>2];
            }
            $adm_id = $adm_data->adm_id;
            if ($adm_data->adm_state == 2) {
                return ['code'=>500, 'msg'=>'当前账号已被停用', 'data'=>'当前账号已被停用'];
            }
            // if ($adm_data->rol_state != 1) {
            //     return ['code'=>500, 'msg'=>'当前账号所属角色权限已被停用3', 'data'=>'当前账号所属角色权限已被停用'];
            // }
            // 查询微信用户openid,手机号是否存在
            // $return_data = (array)$adm_data;
            $return_data['adm_bjfw_openid'] = $code2Session['openid'];
            $return_data['adm_session_key'] = $code2Session['session_key'];
        } else {
            $adm_data['adm_bjfw_openid'] = $code2Session['openid'];
            $adm_data['adm_session_key'] = $code2Session['session_key'];
            $adm_data['adm_update_time'] = date('Y-m-d H:i:s');
            $adm_id = DB::table('admin')->insertGetId($adm_data);
            //添加账号门店权限关系
            $insertAdminShopRoleData = [
                'adm_id' => $adm_id,
                'shop_cid' => 1,
                'superior_shop_id' => 0,
                'shop_id' => 0,
                'role_id' =>  0,
                'adm_shop_leave' => 0,
                'phone' => 0,
                'login_shop' => 0,
                'create_time' => date("Y-m-d H:i:s", time()),
                'update_time' => date("Y-m-d H:i:s", time()),
            ];
            $insertAdminShopRoleDataRes = DB::table('admin_shop_role')->insert($insertAdminShopRoleData);
            // $update_qrdata['shqr_scan_adm_id'] = $adm_id;
            // $update_qrdata['shqr_state'] = 4;//二维码状态1未扫码2已扫码3取消失效4授权成功5过期失效
            // $update_qrdata['shqr_update_time'] = date('Y-m-d H:i:s');
            // $update_qrres = DB::table('shop_qr')
            //     ->where('shqr_number', $request['shqr_number'])
            //     ->update($update_qrdata);
            $return_data['adm_id'] = $adm_id;
            $return_data['adm_phone'] = '';
            $return_data['adm_name'] = '';
            $return_data['adm_bjfw_openid'] = $code2Session['openid'];
            $return_data['adm_session_key'] = $code2Session['session_key'];
            return ['code'=>200, 'msg'=>'success', 'data'=>$return_data];
        }

        // $update_qrdata['shqr_scan_adm_id'] = $adm_id;
        // $update_qrdata['shqr_state'] = 4;//二维码状态1未扫码2已扫码3取消失效4授权成功5过期失效
        // $update_qrdata['shqr_update_time'] = date('Y-m-d H:i:s');
        // $update_qrres = DB::table('shop_qr')
        //     ->where('shqr_number', $request['shqr_number'])
        //     ->update($update_qrdata);
        $return_data['adm_id'] = $adm_id;
        $return_data['adm_phone'] = '';
        $return_data['adm_name'] = '';
        $return_data['adm_bjfw_openid'] = $code2Session['openid'];
        $return_data['adm_session_key'] = $code2Session['session_key'];
        return ['code'=>200, 'msg'=>'success', 'data'=>$return_data];
        // 查询门店信息
        $find_shop = DB::table('shop')
            ->where('shop_id', $adm_data->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();
        if ($find_shop && $find_shop->shop_state != 1) {
            return ['code'=>500, 'msg'=>'当前账号所属门店已被停用', 'data'=>'当前账号所属门店已被停用'];
        }

        if (empty($adm_data->adm_shop_id)) {
            // 查询登录表id
            $find_login = DB::table('login_temporary')
                ->where('adm_id', '=', $adm_data->adm_id)
                ->select('adm_id', 'last_login')
                ->first();
            // 生成token
            $unique_string = md5(uniqid(md5(microtime(true)) . rand(100000, 999999), true)); //生成唯一字符串
            $api_token = sha1($unique_string); //加密
            if (empty($find_login)) {
                // 如果用户第一次登陆,将用户的登录状态保存到临时表
                $lote_data['adm_id'] = $adm_data->adm_id; //账号id
                $lote_data['last_login'] = time() + 2 * 60 * 60; //最后登陆时间
                $lote_data['api_token'] = $api_token; //api_token
                $lote_data['adm_name'] = $adm_data->adm_name; //账号姓名
                $lote_data['adm_phone'] = $adm_data->adm_phone; //手机号
                $lote_data['adm_cid'] = $adm_data->adm_cid; //公司id
                $lote_data['shop_versions'] = 0; //系统版本：0试用1门店版2运营中心版
                $lote_res = DB::table('login_temporary')->insert($lote_data);
                if (empty($lote_res)) {
                    return ['code'=>500, 'msg'=>'登录失败', 'data'=>'api_token写入失败'];
                }
            } else {
                // 修改登陆状态
                $lote_data['last_login'] = time() + 2 * 60 * 60; //最后登陆时间
                $lote_data['api_token'] = $api_token; //api_token
                $lote_data['adm_name'] = $adm_data->adm_name; //账号姓名
                $lote_data['adm_phone'] = $adm_data->adm_phone; //手机号
                $lote_data['adm_cid'] = $adm_data->adm_cid; //公司id
                $lote_data['adm_shop_id'] = $adm_data->adm_shop_id; //门店id
                $lote_data['shop_superior_id'] = $adm_data->adm_shop_id; //所属总店id
                $lote_data['shop_versions'] = 0; //系统版本：1门店版2运营中心版
                $lote_data['role_auth'] = ''; //当前账号所有角色权限
                $lote_data['auth_routes'] = ''; //当前账号所有角色权限路径
                $lote_res = DB::table('login_temporary')
                    ->where('adm_id', $adm_data->adm_id)
                    ->update($lote_data);
            }
            // 返回数据
            $return_data = [
                'api_token' => Crypt::encrypt($api_token), //生成前台token
                'default_url' => 'zhuce.com', //默认跳转页面
                'adm_id' => $adm_data->adm_id,
                'adm_name' => $adm_data->adm_name,
                'adm_phone' => $adm_data->adm_phone,
                'shop_id' => $adm_data->adm_shop_id,
                'shop_store_name' => '',
                'shop_type' => 0,
                'shop_province' => '',
                'shop_city' => '',
                'shop_county' => '',
                'shop_longitude' => '',
                'shop_latitude' => '',
                'shop_versions' => 0,
            ];
            return ['code'=>200, 'msg'=>'查询店铺信息失败，请完善信息', 'data'=>$return_data];
        }
        
        // 查询登录表id
        $find_login = DB::table('login_temporary')
            ->where('adm_id', '=', $adm_data->adm_id)
            ->select('adm_id', 'last_login')
            ->first();
        if (empty($find_login)) {
            // 获取用户对应角色权限
            $role_auth = $this->getRolePrivilege($adm_data);
            if (empty($role_auth['routes_auth']) || empty($role_auth['role_auth'])) {
                return ['code'=>500, 'msg'=>'请联系管理员设置员工角色权限！', 'data'=>'请联系管理员设置员工角色权限！'];
            }

            // 确认此账号默认跳转页面
            $default_url = $this->getDefaultPath($role_auth['role_auth']);

            // 如果用户第一次登陆,将用户的登录状态保存到临时表
            $lote_data['adm_id'] = $adm_data->adm_id; //账号id
            $lote_data['last_login'] = time() + 2 * 60 * 60; //最后登陆时间
            $lote_data['api_token'] = $api_token; //api_token
            $lote_data['adm_name'] = $adm_data->adm_name; //账号姓名
            $lote_data['adm_phone'] = $adm_data->adm_phone; //手机号
            $lote_data['adm_cid'] = $adm_data->adm_cid; //公司id
            $lote_data['adm_shop_id'] = $adm_data->adm_shop_id; //门店id
            $lote_data['shop_superior_id'] = $find_shop->shop_superior_id; //所属总店id
            $lote_data['shop_versions'] = $find_shop->shop_versions; //系统版本：1门店版2运营中心版
            $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_temporary')->insert($lote_data);
            if (empty($lote_res)) {
                return ['code'=>500, 'msg'=>'登录失败', 'data'=>'api_token写入失败'];
            }
            // 修改活动状态值
            /*$acti_start = $this->activityStart($adm_data, $shop_set_superior_id); //启动
            $acti_end = $this->activityTerminate($adm_data, $shop_set_superior_id); //终止*/
            // 返回数据
            $return_data = [
                'api_token' => Crypt::encrypt($api_token), //生成前台token
                'default_url' => $default_url, //默认跳转页面
                'adm_id' => $adm_data->adm_id,
                'adm_name' => $adm_data->adm_name,
                'adm_phone' => $adm_data->adm_phone,
                'shop_id' => $adm_data->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,
            ];
        }

        $now_time = time();

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

            // 确认此账号默认跳转页面
            $default_url = $this->getDefaultPath($role_auth['role_auth']);

            // 修改登陆状态
            $lote_data['last_login'] = time() + 2 * 60 * 60; //最后登陆时间
            $lote_data['api_token'] = $api_token; //api_token
            $lote_data['adm_name'] = $adm_data->adm_name; //账号姓名
            $lote_data['adm_phone'] = $adm_data->adm_phone; //手机号
            $lote_data['adm_cid'] = $adm_data->adm_cid; //公司id
            $lote_data['adm_shop_id'] = $adm_data->adm_shop_id; //门店id
            $lote_data['shop_superior_id'] = isset($find_shop->shop_superior_id) ? $find_shop->shop_superior_id : 0; //所属总店id
            $lote_data['shop_versions'] = isset($find_shop->shop_versions) ? $find_shop->shop_versions : 0; //系统版本：1门店版2运营中心版
            $lote_data['role_auth'] = json_encode($role_auth['role_auth']); //当前账号所有角色权限
            if (!isset($role_auth['routes_auth'])) {
                return ['code'=>500, 'msg'=>'此账号无权限', 'data'=>'此账号无权限'];
            }
            $lote_data['auth_routes'] = json_encode($role_auth['routes_auth']); //当前账号所有角色权限路径
            $lote_res = DB::table('login_temporary')
                ->where('adm_id', $adm_data->adm_id)
                ->update($lote_data);
            if (empty($lote_res)) {
                return ['code'=>500, 'msg'=>'登录失败', 'data'=>'api_token写入失败'];
            }
            // 修改活动状态值
            /*$acti_start = $this->activityStart($adm_data, $shop_set_superior_id); //启动
            $acti_end = $this->activityTerminate($adm_data, $shop_set_superior_id); //终止*/
            // 返回数据
            $return_data = [
                'api_token' => Crypt::encrypt($api_token), //生成前台token
                'default_url' => $default_url, //默认跳转页面
                'adm_id' => $adm_data->adm_id,
                'adm_name' => $adm_data->adm_name,
                'adm_phone' => $adm_data->adm_phone,
                'shop_id' => $adm_data->adm_shop_id
            ];
            if(!empty($find_shop)){
                $return_data['shop_store_name'] = $find_shop->shop_store_name;
                $return_data['shop_type'] = $find_shop->shop_type;
                $return_data['shop_province'] = $find_shop->shop_province;
                $return_data['shop_city'] = $find_shop->shop_city;
                $return_data['shop_county'] = $find_shop->shop_county;
                $return_data['shop_longitude'] = $find_shop->shop_longitude;
                $return_data['shop_latitude'] = $find_shop->shop_latitude;
                $return_data['shop_versions'] = $find_shop->shop_versions;
            }
        } else {
            return ['code'=>400, 'msg'=>'该用户已经登录', 'data'=>'该用户已经登录'];
        }

        $return_data['api_token'] = $crypt_api_token;
        $return_data['adm_bjfw_openid'] = $code2Session['openid'];
        $return_data['adm_session_key'] = $code2Session['session_key'];
        return ['code'=>200, 'msg'=>'success', 'data'=>$return_data, 'state'=>1];
    }

    /**
     * [getRolePrivilege 获取角色权限]
     * @param  [type] $find_admin [用户信息]
     * @return [type]                [description]
     */
    protected 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 ($value['pri_type'] == 1) {//我的任务
                // 角色权限
                $privileges_info['role_auth1'][] = $value;
            } elseif ($value['pri_type'] == 2) {
                $privileges_info['role_auth2'][] = $value;
            } else {
                $privileges_info['role_auth3'][] = $value;
            }
            // 权限路由
            $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 register($code2Session,$request)
    {
        // 根据openid查询用户id
        $weus_id = DB::table('weixin_user')
            ->where("weus_openid", $code2Session['openid'])
            ->value('weus_id');
        if ($weus_id) {
            $weus_data['weus_session_key'] = $code2Session['session_key'];
            $weus_data['weus_update_time'] = date('Y-m-d H:i:s');
            $weus_res = DB::table('weixin_user')
                ->where("weus_id", $weus_id)
                ->update($weus_data);
            // 查询微信用户openid,手机号是否存在
            $find_weixin_data = DB::table('weixin_user')
                ->where('weus_id', $weus_id)
                ->select('weus_id', 'weus_phone', 'weus_nickmame', 'weus_headimgurl')
                ->first();
            $return_data = (array)$find_weixin_data;
            if ($request['new_shop_id']) {//根据shop_id查询是否绑定过门店
                if ($find_weixin_data->weus_phone) {
                    $mem_ret = self::addMemAuth($find_weixin_data,$request['new_shop_id']);
                    if($mem_ret['code'] == 200){
                        $mem_id =  $mem_ret['data'];
                    }
                } else {
                    $mem_id = 0;
                }
                $find_user_info = DB::table('user_shop')
                    ->where('ussh_weus_id', $weus_id)
                    ->where('ussh_shop_id', $request['new_shop_id'])
                    ->select('ussh_user_id')
                    ->first();
                if (empty($find_user_info)) {//没有绑定门店
                    $ussh_data['ussh_user_id'] = $mem_id;
                    // 用户没有与当前门店绑定，把用户与当前门店绑定
                    $ussh_data['ussh_weus_id'] = $weus_id;
                    $ussh_data['ussh_shop_id'] = $request['new_shop_id'];
                    $ussh_data['ussh_user_type'] = 1;
                    $ussh_data['ussh_phone'] = $find_weixin_data->weus_phone;
                    $ussh_data['ussh_create_time'] = date('Y-m-d H:i:s');
                    $ussh_data['ussh_register_time'] = date('Y-m-d H:i:s');
                    $ussh_id = DB::table('user_shop')->insertGetId($ussh_data);
                    if (!$ussh_id) {
                        return ['code'=>500, 'msg'=>'登录失败2', 'data'=>''];
                    }

                    $return_data['ussh_user_id'] = $ussh_data['ussh_user_id'];
                    $return_data['meca_car_data'] = '';
                } else {
                    self::addMemAuth($find_weixin_data,$request['new_shop_id']);
                    $return_data['ussh_user_id'] = $find_user_info->ussh_user_id;
                    $return_data['meca_car_data'] = DB::table('member_car')
                        ->where('meca_mem_id', $find_user_info->ussh_user_id)
                        ->where(function ($query) use ($request) { //门店id
                            if (!empty($request['new_shop_id'])) {
                                $query->where('meca_shop_id', $request['new_shop_id']);
                            }
                        })
                        ->where('meca_default', 1)
                        ->select('meca_car_num', 'meca_car_series', 'meca_car_model', 'meca_car_brand_series', 'meca_car_frame')
                        ->first();
                    $update_user_shop = DB::table('user_shop')
                        ->where('ussh_weus_id', $weus_id)
                        ->where('ussh_shop_id', $request['new_shop_id'])
                        ->update(['ussh_create_time'=>date('Y-m-d H:i:s')]);
                }
            } else {
                // 查询店铺信息
                $list_data = DB::table('user_shop as a')
                    ->leftJoin('shop as b', 'a.ussh_shop_id', '=', 'b.shop_id')
                    ->where('ussh_weus_id', $weus_id)
                    ->select('shop_id', 'shop_store_name', 'shop_phone', 'shop_province', 'shop_city', 'shop_county', 'shop_address', 'shop_image', 'shop_state', 'shop_longitude', 'shop_latitude', 'shop_versions', 'ussh_user_id')
                    ->orderBy('ussh_create_time', 'desc')
                    ->first();
                if (empty($list_data)) {
                    $return_data['meca_car_data'] = '';
                    $return_data['ussh_user_id'] = '';
                } else {
                    $return_data['meca_car_data'] = DB::table('member_car')
                            ->where(function ($query) use ($list_data) { //mem_id
                                if (!empty($list_data)) {
                                    $query->where('meca_mem_id', $list_data->ussh_user_id);
                                }
                            })
                            ->where(function ($query) use ($list_data) { //门店id
                                if (!empty($list_data)) {
                                    $query->where('meca_shop_id', $list_data->shop_id);
                                }
                            })
                            ->where('meca_default', 1)
                            ->select('meca_car_num', 'meca_car_series', 'meca_car_model', 'meca_car_brand_series', 'meca_car_frame')
                            ->first();
                    $return_data['ussh_user_id'] = $list_data->ussh_user_id;
                }
            }
            $return_data['shop_data'] = $list_data;
        } else {
            $weus_data['weus_openid'] = $code2Session['openid'];
            $weus_data['weus_session_key'] = $code2Session['session_key'];
            $weus_data['weus_update_time'] = date('Y-m-d H:i:s');
            $weus_id = DB::table('weixin_user')->insertGetId($weus_data);
            // 查询微信用户openid,手机号是否存在
            $find_weixin_data = DB::table('weixin_user')
                ->where('weus_id', $weus_id)
                ->select('weus_id', 'weus_phone', 'weus_nickmame', 'weus_headimgurl')
                ->first();
            $return_data = (array)$find_weixin_data;

            if (!empty($request['new_shop_id'])) {
                $ussh_data['ussh_weus_id'] = $weus_id;
                $ussh_data['ussh_shop_id'] = $request['new_shop_id'];
                $ussh_data['ussh_user_type'] = 1;
                $ussh_data['ussh_phone'] = '';
                $ussh_data['ussh_create_time'] = date('Y-m-d H:i:s');
                $ussh_data['ussh_register_time'] = date('Y-m-d H:i:s');
                $ussh_id = DB::table('user_shop')->insertGetId($ussh_data);
                if (!$ussh_id) {
                    return ['code'=>500, 'msg'=>'登录失败2', 'data'=>''];
                }
                $return_data['shop_data'] = DB::table('shop')
                    ->where('shop_id', $request['new_shop_id'])
                    ->select('shop_id', 'shop_store_name', 'shop_phone', 'shop_province', 'shop_city', 'shop_county', 'shop_address', 'shop_image', 'shop_state', 'shop_longitude', 'shop_latitude', 'shop_versions')
                    ->first();
            } else {
                // 查询店铺信息
                $return_data['shop_data'] = DB::table('user_shop as a')
                    ->leftJoin('shop as b', 'a.ussh_shop_id', '=', 'b.shop_id')
                    ->where('ussh_weus_id', $weus_id)
                    ->select('shop_id', 'shop_store_name', 'shop_phone', 'shop_province', 'shop_city', 'shop_county', 'shop_address', 'shop_image', 'shop_state', 'shop_longitude', 'shop_latitude', 'shop_versions')
                    ->orderBy('ussh_create_time', 'desc')
                    ->first();
            }
           
            $return_data['ussh_user_id'] = '';
            $return_data['meca_car_data'] = '';
        }

        // 查询登录表id
        $login_id = DB::table('login_user_wechat_applet')
            ->where("openid", $code2Session['openid'])
            ->value('id');
        $unique_string = md5(uniqid(md5(microtime(true)) . rand(100000, 999999), true)); //生成唯一字符串
        $api_token = sha1($unique_string); //加密
        $crypt_api_token = Crypt::encrypt($api_token); //生成前台token
        if ($login_id) {
            // 更新登录信息
            $login_data['session_key'] = $code2Session['session_key'];
            $login_data['api_token'] = $api_token;
            $login_data['weus_id'] = $weus_id ? $weus_id : '';
            $login_data['last_login'] = time() + 4*60*60;//4个小时有效时间
            $login_res = DB::table('login_user_wechat_applet')
                ->where("id", $login_id)
                ->update($login_data);
        } else {
            // 插入登录信息
            $login_data['openid'] = $code2Session['openid'];
            $login_data['weus_id'] = $weus_id ? $weus_id : '';
            $login_data['session_key'] = $code2Session['session_key'];
            $login_data['api_token'] = $api_token;
            $login_data['last_login'] = time() + 4*60*60;//4个小时有效时间
            $login_res = DB::table('login_user_wechat_applet')->insertGetId($login_data);
        }

        $return_data['api_token'] = $crypt_api_token;
        $return_data['openid'] = $code2Session['openid'];
        $return_data['session_key'] = $code2Session['session_key'];
        return ['code'=>200, 'msg'=>'success', 'data'=>$return_data];
    }
}
