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

use App\Http\Controllers\Api\Verify\SystemsManage\VerifyPersonalController;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Api\Verify\VerifyLoginController;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Crypt;
use App\Http\Models\Api\Common;

class LoginController extends Controller
{
    // 登录
    public function login(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyLoginController;
        $error_message = $verify_data->loginValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>$error_message]);
        }

        // 判断手机号正则
        $phone_preg = '/^0?1[3|4|5|6|7|8|9][0-9]\d{8}$/';
        $adm_pawd = md5($request['password'] . 'faster123456');
        // 查询账号信息  登录必须使用自主创建账号无法使用分店浏览账号
        $find_admin = DB::table('admin as a')
            ->leftjoin('admin_shop_role', 'admin_shop_role.adm_id', '=', 'a.adm_id')
            ->leftjoin('role', 'role.rol_id', '=', 'admin_shop_role.role_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('create_source', 1)
            ->where('adm_password', $adm_pawd)
            ->where('admin_shop_role.login_shop', 1)
            ->select('a.adm_id', 'adm_name', 'adm_account', 'adm_phone', 'admin_shop_role.shop_cid as adm_cid',
                'admin_shop_role.shop_id as adm_shop_id', 'admin_shop_role.adm_state as adm_state', 'rol_state',
                'rol_privilege', 'rol_privilege_multiple', 'admin_shop_role.superior_shop_id as adm_superior_shop_id')
            ->first();
        if (empty($find_admin)) {
            $find_admin = DB::table('admin as a')
                ->leftjoin('admin_shop_role', 'admin_shop_role.adm_id', '=', 'a.adm_id')
                ->leftjoin('role', 'role.rol_id', '=', 'admin_shop_role.role_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('create_source', 1)
                ->where('adm_password', $adm_pawd)
                ->select('a.adm_id', 'adm_name', 'adm_account', 'adm_phone', 'admin_shop_role.shop_cid as adm_cid',
                    'admin_shop_role.shop_id as adm_shop_id', 'admin_shop_role.adm_state as adm_state', 'rol_state',
                    'rol_privilege', 'rol_privilege_multiple', 'admin_shop_role.superior_shop_id as adm_superior_shop_id')
                ->orderBy('adm_state', 'asc')
                ->orderBy('admin_shop_role.id','desc')
                ->first();
            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'=>'当前账号所属角色权限已被停用']);
        }
        $time_over = false;
        // 判断账号时效
        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', 'shop_opening_type')
                ->first();
            $time_over = false;
            if ($sup_shop_info) {
                $time = time();
                // 判断试用是否到期
                if ($time > strtotime($sup_shop_info->shop_on_trial_end_time) && $sup_shop_info->shop_opening_type == 1) {
                    $time_over = true;
                    // 过期判断开通结束时间
                    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_versions', 'shve_id', '=', 'shop_shve_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_opening_type', 'shop_on_trial_end_time', 'shop_opening_end_time', 'shop_source_identify', 'shop_shve_id', 'shve_name')
            ->first();
        if ($find_shop->shop_source_identify == 5) {
            //return response()->json(['code'=>500, 'msg'=>'当前账号无PC端登录权限', 'data'=>'当前账号无PC端登录权限']);
        }
        if ($find_shop->shop_state != 1) {
            return response()->json(['code'=>500, 'msg'=>'当前账号所属门店已被停用', 'data'=>'当前账号所属门店已被停用']);
        }
        $shop_surply_day = 0;
        if ($find_shop->shop_opening_type == 1) {//开通类型1免费试用2正式开通
            $shop_on_trial_end_time = strtotime($find_shop->shop_on_trial_end_time);
            // if (time()>$shop_on_trial_end_time) {
            //     return response()->json(['code'=>500, 'msg'=>'试用时间结束，请购买正式版本', 'data'=>'试用时间结束，请购买正式版本']);
            // }
            $shop_surply_day = ceil(($shop_on_trial_end_time - time())/86400);
        } elseif ($find_shop->shop_opening_type == 2) {
            $shop_opening_end_time = strtotime($find_shop->shop_opening_end_time);
            // if (time()>$shop_opening_end_time) {
            //     return response()->json(['code'=>500, 'msg'=>'已到期，请续费', 'data'=>'已到期，请续费']);
            // }
            $shop_surply_day = ceil(($shop_opening_end_time - time())/86400);
        }
        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;
            }
        }
        $find_settle = DB::table('settle_in')
            ->where('shop_id', $find_admin->adm_shop_id)
            ->first();
        if ($find_settle) {
            if ($find_settle->inv_shop_code == 'S9485341921') {
                $find_shop->shve_name = '顶新·集团版';
            }
        }
        // if ($find_shop->shop_type != 1) {
        //     return response()->json(['code'=> 500,'msg'=>'error','data'=>'当前账号所属门店暂未开通，无法登陆']);
        // }
        // 查询账号所属门店是否停用
        if (!in_array($find_admin->adm_id, config('apisystem.pass_verification_admin'))) {
            // 判断总店是否需要验证登录设备
            // if (in_array($find_admin->adm_superior_shop_id, config('apisystem.verification_shop'))) {
            //     // 验证登录设备
            //     if (empty($request['facility'])) {
            //         return response()->json(['code'=>500, 'msg'=>'当前计算机设备尚未验证，无法登录', 'data'=>'当前计算机设备尚未验证，无法登录']);
            //     }

            //     // 查询登录设备数据
            //     $find_lode = DB::table('login_device')
            //         ->where('lode_shop_superior_id', $find_admin->adm_superior_shop_id)
            //         ->where('lode_unique_identifier', rtrim($request['facility'], '&state'))
            //         ->select('lode_id', 'lode_state')
            //         ->first();
            //     if (empty($find_lode)) {
            //         // 添加设备信息
            //         $lode_data['lode_adm_id'] = $find_admin->adm_id;
            //         $lode_data['lode_shop_id'] = $find_admin->adm_shop_id;
            //         $lode_data['lode_shop_superior_id'] = $find_admin->adm_superior_shop_id;
            //         $lode_data['lode_unique_identifier'] = rtrim($request['facility'], '&state');
            //         $find_lode = DB::table('login_device')->insert($lode_data);
            //         return response()->json(['code'=>500, 'msg'=>'当前计算机设备正在审核中，请稍等', 'data'=>'当前计算机设备正在审核中，请稍等']);
            //     }
            //     // lode_state 1待审核2通过3启用4禁用
            //     if ($find_lode->lode_state == 1) {
            //         return response()->json(['code'=>500, 'msg'=>'当前计算机设备正在审核中，请稍等', 'data'=>'当前计算机设备正在审核中，请稍等']);
            //     }
            //     if ($find_lode->lode_state == 4) {
            //         return response()->json(['code'=>500, 'msg'=>'当前计算机设备已禁用，请联系管理员', 'data'=>'当前计算机设备已禁用，请联系管理员']);
            //     }
            // }

            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 = $find_shop->shop_superior_id;
            $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_temporary')
            ->where('adm_id', '=', $find_admin->adm_id)
            ->select('adm_id', 'last_login')
            ->first();
        if (empty($find_login)) {
            // 获取用户对应角色权限
            $role_auth = $this->getRolePrivilege($find_admin);
            if (empty($role_auth['routes_auth']) || empty($role_auth['role_auth'])) {
                return response()->json(['code'=>500, 'msg'=>'请联系管理员设置员工角色权限！', 'data'=>'请联系管理员设置员工角色权限！']);
            }

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

            // 如果用户第一次登陆,将用户的登录状态保存到临时表
            $lote_data['adm_id'] = $find_admin->adm_id; //账号id
            $lote_data['last_login'] = time() + 2 * 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运营中心版
            $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 response()->json(['code'=>500, 'msg'=>'登录失败', 'data'=>'api_token写入失败']);
            }
            DB::table('admin_shop_role')->where('adm_id', $find_admin->adm_id)->update(['login_shop'=>2]);
            DB::table('admin_shop_role')->where('adm_id', $find_admin->adm_id)->where('shop_id', $find_admin->adm_shop_id)->update(['login_shop'=>1]);
            // 修改活动状态值
            $acti_start = $this->activityStart($find_admin, $shop_set_superior_id); //启动
            $acti_end = $this->activityTerminate($find_admin, $shop_set_superior_id); //终止
            // 返回数据
            $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_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,
                'shop_opening_type' => $find_shop->shop_opening_type,
                'shop_on_trial_end_time' => $find_shop->shop_on_trial_end_time,
                'shop_opening_end_time' => $find_shop->shop_opening_end_time,
                'shop_surply_day' => $shop_surply_day,
                'shop_address' => $find_shop->shop_address ? $find_shop->shop_address : '',
                'shop_shve_id' => $find_shop->shop_shve_id,
                'shve_name' => $find_shop->shve_name,
            ];
            if ($time_over) {
                return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$return_data]);
            } else {
                return response()->json(['code'=>200, 'msg'=>'success', '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() + 2 * 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运营中心版
            $lote_data['role_auth'] = json_encode($role_auth['role_auth']); //当前账号所有角色权限
            if (!isset($role_auth['routes_auth'])) {
                return response()->json(['code'=>500, 'msg'=>'此账号无权限1', 'data'=>'此账号无权限']);
            }
            $lote_data['auth_routes'] = json_encode($role_auth['routes_auth']); //当前账号所有角色权限路径
            $lote_res = DB::table('login_temporary')
                ->where('adm_id', $find_admin->adm_id)
                ->update($lote_data);
            if (empty($lote_res)) {
                return response()->json(['code'=>500, 'msg'=>'登录失败', 'data'=>'api_token写入失败']);
            }
            DB::table('admin_shop_role')->where('adm_id', $find_admin->adm_id)->update(['login_shop'=>2]);
            DB::table('admin_shop_role')->where('adm_id', $find_admin->adm_id)->where('shop_id', $find_admin->adm_shop_id)->update(['login_shop'=>1]);
            // 修改活动状态值
            $acti_start = $this->activityStart($find_admin, $shop_set_superior_id); //启动
            $acti_end = $this->activityTerminate($find_admin, $shop_set_superior_id); //终止
            // 返回数据
            $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_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运营中心版
                'shop_opening_type' => $find_shop->shop_opening_type,
                'shop_on_trial_end_time' => $find_shop->shop_on_trial_end_time,
                'shop_opening_end_time' => $find_shop->shop_opening_end_time,
                'shop_surply_day' => $shop_surply_day,
                'shop_address' => $find_shop->shop_address ? $find_shop->shop_address : '',
                'shop_shve_id' => $find_shop->shop_shve_id,
                'shve_name' => $find_shop->shve_name,
            ];
            if ($time_over) {
                return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$return_data]);
            } else {
                return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$return_data]);
            }
        } else {
            return response()->json(['code'=>400, 'msg'=>'该用户已经登录', 'data'=>'该用户已经登录']);
        }
    }

    //选择门点登录
    public function switchShopLogin(Request $request) {
        // 验证数据
        $verify_data = new VerifyLoginController;
        $error_message = $verify_data->switchShopLoginValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        $shopId = $request['shop_id'];
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        $shop_state = DB::table('shop')
            ->where('shop_id', $shopId)
            ->value('shop_state');
        if ($shop_state == 2) {
            return response()->json(['code' => 500, 'msg' => '当前分店已被停用', 'data' => '当前分店已被停用']);
        }
        //登录新门店
        $find_admin = DB::table('admin_shop_role as asr')
            ->leftjoin('admin as a', 'asr.adm_id', '=', 'a.adm_id')
            ->leftjoin('role', 'role.rol_id', '=', 'asr.role_id')
            ->where('asr.adm_id', $user_info->adm_id)
            ->where('asr.shop_id', $shopId)
            ->where('asr.adm_state', 1)
            ->select('a.adm_id', 'a.adm_name', 'a.adm_account', 'a.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','create_source')
            ->first();
        //判定是否有分店登录权限
        if($user_info->shop_superior_id<1){
            $shop_superior_id = $user_info->adm_shop_id;
        }else{
            $shop_superior_id = $user_info->shop_superior_id;
        }
        if($find_admin && $find_admin->create_source == 2) {
            $login_bind_shop = DB::table('admin_shop_role')
                ->where('shop_id', $shop_superior_id)
                ->where('adm_id',$user_info->adm_id)
                ->where('adm_state',1)
                ->where('login_bind_shop', 1)
                ->value('id');
            if (empty($login_bind_shop)) {
                return response()->json(['code' => 500, 'msg' => '当前账号无登录分店权限', 'data' => '退出当前门店失败']);
            }
        }
        //无账号判定是否可以创建分店登录
        if (empty($find_admin)) {
            $login_bind_shop = DB::table('admin_shop_role')
                ->where('shop_id', $shop_superior_id)
                ->where('adm_id',$user_info->adm_id)
                ->where('adm_state',1)
                ->where('login_bind_shop', 1)
                ->value('id');
            if (empty($login_bind_shop)) {
                return response()->json(['code' => 500, 'msg' => '当前账号无登录分店权限', 'data' => '退出当前门店失败']);
            }
            //创建等点登录账号
            $rol_id = DB::table('role')
                ->where('rol_shop_id', $shopId)
                ->where('rol_type', 1)
                ->value('rol_id');
            //添加账号门店权限关系
            $insertAdminShopRoleData = [
                'adm_id' => $user_info->adm_id,
                'shop_cid' => $user_info->adm_cid,
                'superior_shop_id' => $shop_superior_id,
                'shop_id' => $shopId,
                'role_id' =>  $rol_id,
                'adm_shop_leave' => 2,
                'phone' => $user_info->adm_phone,
                'login_shop' => 2,
                'login_shop_wechat' => 2,
                'create_source' => 2,
                '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);
            if($insertAdminShopRoleDataRes){
                //创建成功重新登录
                $find_admin = DB::table('admin_shop_role as asr')
                    ->leftjoin('admin as a', 'asr.adm_id', '=', 'a.adm_id')
                    ->leftjoin('role', 'role.rol_id', '=', 'asr.role_id')
                    ->where('asr.adm_id', $user_info->adm_id)
                    ->where('asr.shop_id', $shopId)
                    ->where('asr.adm_state', 1)
                    ->select('a.adm_id', 'a.adm_name', 'a.adm_account', 'a.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','create_source')
                    ->first();
                if (empty($find_admin)) {
                    return response()->json(['code'=>500, 'msg'=>'切换门店失败-002', 'data'=>'切换门店失败']);
                }
            }else{
                return response()->json(['code'=>500, 'msg'=>'切换门店失败-001', 'data'=>'切换门店失败']);
            }
        }
        DB::beginTransaction();
        //退出当前登录门店
        $res = DB::table('login_temporary')
            ->where('api_token', $request['api_token'])
            ->delete();
        if (empty($res)) {
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'error', '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 (!empty($sup_shop_info)) {
                // 判断试用是否到期
                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,
                            '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_versions', 'shve_id', '=', 'shop_shve_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_opening_type', 'shop_on_trial_end_time', 'shop_opening_end_time', 'shop_source_identify', 'shop_shve_id', 'shve_name')
            ->first();
        $shop_surply_day = 0;
        if ($find_shop->shop_opening_type == 1) {//开通类型1免费试用2正式开通
            $shop_on_trial_end_time = strtotime($find_shop->shop_on_trial_end_time);
            $shop_surply_day = ceil(($shop_on_trial_end_time - time())/86400);
        } elseif ($find_shop->shop_opening_type == 2) {
            $shop_opening_end_time = strtotime($find_shop->shop_opening_end_time);
            $shop_surply_day = ceil(($shop_opening_end_time - time())/86400);
        }
        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);
        if (empty($role_auth['routes_auth']) || empty($role_auth['role_auth'])) {
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'请联系管理员设置员工角色权限！', 'data'=>[]]);
        }

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

        // 如果用户第一次登陆,将用户的登录状态保存到临时表
        $lote_data['adm_id'] = $find_admin->adm_id; //账号id
        $lote_data['last_login'] = time() + 2 * 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运营中心版
        $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)) {
            DB::rollBack();
            return response()->json(['code'=>500, 'msg'=>'用户的登录状态保存到临时表失败', 'data'=>[]]);
        }
        DB::table('admin_shop_role')->where('adm_id', $user_info->adm_id)->update(['login_shop'=>2]);
        DB::table('admin_shop_role')->where('adm_id', $user_info->adm_id)->where('shop_id', $shopId)->update(['login_shop'=>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_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,
            'shop_opening_type' => $find_shop->shop_opening_type,
            'shop_on_trial_end_time' => $find_shop->shop_on_trial_end_time,
            'shop_opening_end_time' => $find_shop->shop_opening_end_time,
            'shop_surply_day' => $shop_surply_day,
            'shop_address' => $find_shop->shop_address,
            'shop_shve_id' => $find_shop->shop_shve_id,
            'shve_name' => $find_shop->shve_name,
        ];
        // 删除订单和工单临时商品信息
        DB::commit();
        Common::addLog($user_info, getRealIp($request), '登录', '切换门店登录', '切换门店id： ' . $shopId);
        return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$return_data]);
    }

    public function getPri(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyLoginController;
        $error_message = $verify_data->getPriValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>$error_message]);
        }
        // 查询账号信息
        $find_admin = 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_id', $request['adm_id'])
            ->select('a.adm_id', 'a.adm_name', 'a.adm_account', 'a.adm_phone', 'asr.shop_cid as adm_cid',
                'asr.shop_id as adm_shop_id', 'asr.adm_state', 'rol_state', 'rol_privilege', 'asr.superior_shop_id as adm_superior_shop_id')
            ->first();
        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'=>'当前账号所属角色权限已被停用']);
        }
        // 查找此用户对应得角色权限
        $role_auth = $this->getRolePrivilege($find_admin);
        return response()->json(['code'=>500, 'msg'=>'获取成功', 'data'=>$role_auth]);
    }

    // 供应链一键登录
    public function ocLogin(Request $request)
    {
        // 获取当前操作账号信息
        $login_tem = DB::table('login_temporary')
            ->where('api_token', $request['token'])
            ->select('adm_id')
            ->first();
        if (!$login_tem) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'token失效']);
        }
        // 查询账号信息
        $find_admin = 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_id', $login_tem->adm_id)
            ->select('a.adm_id', 'a.adm_name', 'a.adm_account', 'a.adm_phone', 'asr.shop_cid as adm_cid', 'asr.shop_id as adm_shop_id',
                'asr.adm_state', 'rol_state', 'rol_privilege', 'asr.superior_shop_id as adm_superior_shop_id')
            ->first();

        if (empty($find_admin)) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'账号密码错误']);
        }
        if ($find_admin->adm_state == 2) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前账号已被停用']);
        }
        if ($find_admin->rol_state != 1) {
            return response()->json(['code'=>500, 'msg'=>'error', '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')
            ->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();
        if ($find_shop->shop_state != 1) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前账号所属门店已被停用']);
        }
        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 ($find_shop->shop_type != 1) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前账号所属门店暂未开通，无法登陆']);
        }
        // 查询账号所属门店是否停用
        if (!in_array($find_admin->adm_id, config('apisystem.pass_verification_admin'))) {
            // 判断总店是否需要验证登录设备
            if (in_array($find_admin->adm_superior_shop_id, config('apisystem.verification_shop'))) {
                // 验证登录设备
                if (empty($request['facility'])) {
                    return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前计算机设备尚未验证，无法登录']);
                }

                // 查询登录设备数据
                $find_lode = DB::table('login_device')
                    ->where('lode_shop_superior_id', $find_admin->adm_superior_shop_id)
                    ->where('lode_unique_identifier', rtrim($request['facility'], '&state'))
                    ->select('lode_id', 'lode_state')
                    ->first();
                if (empty($find_lode)) {
                    // 添加设备信息
                    $lode_data['lode_adm_id'] = $find_admin->adm_id;
                    $lode_data['lode_shop_id'] = $find_admin->adm_shop_id;
                    $lode_data['lode_shop_superior_id'] = $find_admin->adm_superior_shop_id;
                    $lode_data['lode_unique_identifier'] = rtrim($request['facility'], '&state');
                    $find_lode = DB::table('login_device')->insert($lode_data);
                    return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前计算机设备正在审核中，请稍等']);
                }
                // lode_state 1待审核2通过3启用4禁用
                if ($find_lode->lode_state == 1) {
                    return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前计算机设备正在审核中，请稍等']);
                }
                if ($find_lode->lode_state == 4) {
                    return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前计算机设备已禁用，请联系管理员']);
                }
            }

            if ($find_shop->shop_state != 1 && $find_shop->shop_type != 3) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前账号所属门店已停业']);
            } elseif ($find_shop->shop_type == 3 && $find_shop->shop_state != 1) {
                return response()->json(['code'=>500, 'msg'=>'error', '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'=>'error', 'data'=>'账号未绑定手机号']);
        }

        // 生成token
        $unique_string = md5(uniqid(md5(microtime(true)) . rand(100000, 999999), true)); //生成唯一字符串
        $api_token = sha1($unique_string); //加密


        // login_type 值为1 强制登录
        $login_type = 1;

        // 查找此用户对应得角色权限
        $role_auth = $this->getRolePrivilege($find_admin);

        // 确认此账号默认跳转页面
        $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'] = $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运营中心版
        $lote_data['role_auth'] = json_encode($role_auth['role_auth']); //当前账号所有角色权限
        if (!isset($role_auth['routes_auth'])) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'此账号无权限']);
        }
        $lote_data['auth_routes'] = json_encode($role_auth['routes_auth']); //当前账号所有角色权限路径
        $lote_res = DB::table('login_temporary')
            ->where('adm_id', $find_admin->adm_id)
            ->update($lote_data);
        if (empty($lote_res)) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'api_token写入失败']);
        }
        // 修改活动状态值
        $acti_start = $this->activityStart($find_admin, $shop_set_superior_id); //启动
        $acti_end = $this->activityTerminate($find_admin, $shop_set_superior_id); //终止
        // 返回数据
        $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_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,
        ];
        // 删除订单和工单临时商品信息
        $find_orgt_id = DB::table('order_goods_temporary')
            ->where('orgt_adm_id', $find_admin->adm_id)
            ->delete();

        return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$return_data]);
    }

    // 退出
    public function quit(Request $request)
    {
        try {
            $api_token = Crypt::decrypt($request['api_token']);
        } catch (\Exception $e) {
            return response()->json(['code'=>500, 'msg'=>'登录失效', 'data'=>'api_token失效']);
        }

        // 更改最后登录时间
        $res = DB::table('login_temporary')
            ->where('api_token', $api_token)
            ->delete();
        if ($res) {
            return response()->json(['code'=>200, 'msg'=>'退出成功', 'data'=>'退出成功']);
        } else {
            return response()->json(['code'=>500, 'msg'=>'退出失败', 'data'=>'退出失败']);
        }
    }

    // 忘记密码--获取验证码
    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 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'=>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 bindingPhone(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyLoginController;
        $error_message = $verify_data->bindingPhoneGetCodeValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        if ($request['type'] == 1) {
            // 判断手机号是否存在于该系统中
            $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_account', $request['adm_account'])
                ->select('a.adm_id', 'a.adm_name', 'rol_state', 'a.shop_cid as adm_cid', 'asr.shop_id as adm_shop_id', 'asr.adm_state', 'rol_state', 'a.adm_phone')
                ->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'=>'当前账号所属角色权限已被停用']);
            }
            if (!empty($user_info->adm_phone)) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'该账号已绑定手机号']);
            }

            // 判断手机号是否存在于该系统中
            $adm_id = DB::table('admin')
                ->where('adm_phone', $request['adm_phone'])
                ->select('adm_id')
                ->first();
            if (!empty($adm_id)) {
                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'=>'验证码发送失败']);
            }
        }
        // 验证数据
        $verify_data = new VerifyLoginController;
        $error_message = $verify_data->bindingPhoneValidator($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'=>'当前验证码已过期失效，请重新获取验证码']);
        }
        // 用户数据
        $user_info = DB::table('admin')
            ->leftJoin('admin_shop_role as asr', 'asr.adm_id', '=', 'admin.adm_id')
            ->where('admin.adm_account', $request['adm_account'])
            ->first(['admin.adm_id', 'asr.shop_cid as adm_cid', 'asr.shop_id as adm_shop_id', 'admin.adm_name', 'admin.adm_phone', 'asr.adm_state']);
        if (!empty($user_info->adm_phone)) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'该账号已绑定手机号']);
        }
        // 更改验证码状态
        $phc_res = DB::table('phone_code')
            ->where('phc_id', $find_phone_code->phc_id)
            ->update(['phc_type' => 2]);
        $edit_phone['adm_phone'] = $request['adm_phone'];
        $edit_phone['adm_update_time'] = date('Y-m-d H:i:s');

        $edit_shop_phone['shop_phone'] = $request['adm_phone'];
        $edit_shop_phone['shop_update_time'] = date('Y-m-d H:i:s');
        // 绑定手机号
        $edit_phone_res = DB::table('admin')
            ->where('adm_account', $request['adm_account'])
            ->update($edit_phone);
        //更新账号门店权限关系表
        $admin_shop_roleres = DB::table('admin_shop_role')
            ->where('adm_id', $user_info->adm_id)
            ->where('shop_id', $user_info->adm_shop_id)
            ->update(['phone'=>$request['adm_phone']]);

        $edit_shop_res = DB::table('shop')
            ->where('shop_id', $user_info->adm_shop_id)
            ->update($edit_shop_phone);
        if ($edit_phone_res && $edit_shop_res && $admin_shop_roleres) {
            DB::commit();
            Common::addLog($user_info, getRealIp($request), '登陆', '绑定手机号', '账号:' . $request['adm_account'] . ' 绑定手机号:' . $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'=>'当前验证码已过期失效，请重新获取验证码']);
        }
        
        $user_info = Common::getUserInfo($request['api_token']);

        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('asr.phone', $request['adm_phone'])
            ->where('asr.shop_id', $user_info->adm_shop_id)
            ->first(['admin.adm_id', 'asr.shop_cid as adm_cid', 'asr.shop_id as adm_shop_id', 'admin.adm_name', 'admin.adm_phone', 'asr.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['pc'];//pc端权限
            // $rol_privilege_applet = $rol_privilege['applet'];//pc端权限
        } else {
            // 之前的权限ID字段
            $rol_privilege = $find_admin->rol_privilege;
        }
        $pri_id = explode(',', $rol_privilege);
        // $pri_id_applet = explode(',', $rol_privilege_applet);
        // 查询权限id对应的权限数据
        $privileges = DB::table('privileges')
            ->whereIn('pri_id', $pri_id)
            ->where('pri_show', 1)
            ->get();
        // // 查询权限id对应的权限数据
        // $privileges_applet = DB::table('privileges_technician_applet')
        //     ->whereIn('pri_id', $pri_id_applet)
        //     ->where('pri_show', 1)
        //     ->get();
        $privileges = json_decode(json_encode($privileges), true);
        // $privileges_applet = json_decode(json_encode($privileges_applet), true);

        $privileges = array_values($privileges);
        // $privileges_applet = array_values($privileges_applet);
        foreach ($privileges as $key => $value) {
            // 权限路由
            $privileges_info['routes_auth'][] = 'App\Http\Controllers\\' . $value['pri_controller'] . 'Controller' . '@' . $value['pri_operate_method'] . ',';
        }

        // 角色权限
        $privileges_info['role_auth'] = $privileges;
        return $privileges_info;
    }

    // 获取页面默认跳转路径
    public 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 deviceSent($find_admin, $shop_id, $facility)
    {
        $lode_state = DB::table('login_device')
            // ->where('lode_adm_id',$find_admin->adm_id)
            ->where('lode_shop_id', $find_admin->adm_shop_id)
            ->where('lode_shop_superior_id', $shop_id)
            ->where('lode_unique_identifier', md5($facility))
            ->value('lode_state');
        if (!empty($lode_state)) {
            if ((int)$lode_state == 1) {
                return '此账号正在登陆审核中';
            }
            if ((int)$lode_state == 4) {
                return '此账号已经被禁用';
            }
            return;
        }
        // 登录设备信息
        $lode_data['lode_adm_id'] = $find_admin->adm_id;          //账号id
        $lode_data['lode_shop_id'] = $find_admin->adm_shop_id;    //门店id
        $lode_data['lode_shop_superior_id'] = $shop_id;           //所属总店id
        $lode_data['lode_unique_identifier'] = md5($facility);    //唯一标识
        $lode_data['lode_state'] = 1;    //待审核
        $lode_data['lode_create_time'] = date('Y-m-d H:i:s');
        $lode_res = DB::table('login_device')->insert($lode_data);

        if (empty($lode_res)) {
            return '登录设备信息写入失败';
        }
        return '登陆请求成功,请等待管理员通过请求';
    }

    // 保存验证设备唯一标识
    public function saveValidation(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyLoginController;
        $error_message = $verify_data->deviceValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>$error_message, 'data'=>'']);
        }

        $dein_info = DB::table('login_device_info')
            ->where('dein_info', $request['facility'])
            ->first(['dein_info', 'dein_state']);
        $time = date('Y-m-d H:i:s');
        if (empty($dein_info)) {
            $data['dein_info'] = $request['facility'];
            $data['dein_state'] = 1; //默认为未访问
            $data['dein_create_time'] = $time; //默认为未访问
            $data['dein_update_time'] = $time; //默认为未访问
            $res = DB::table('login_device_info')->insert($data);
            if (empty($res)) {
                return response()->json(['code'=>500, 'msg'=>'保存失败', 'data'=>'']);
            }
        } else {
            $res = DB::table('login_device_info')
                ->where('dein_info', $request['facility'])
                ->update(['dein_state' => 1, 'dein_update_time' => $time]);
            if (empty($res)) {
                return response()->json(['code'=>500, 'msg'=>'保存失败', 'data'=>'']);
            }
        }
        $url = config('apisystem.server_name') . '/index.html?facility=' . $request['facility'] . '&state=1';
        // $url = 'http://localhost:9100/index.html?facility='.$request['facility'].'&state=1';
        return response()->json(['code'=>200, 'msg'=>'成功', 'data'=>$url]);
    }

    // 修改访问状态
    public function alterValidation(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyLoginController;
        $error_message = $verify_data->deviceValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=>500, 'msg'=>$error_message, 'data'=>'1']);
        }

        if (empty($request['state'])) {
            return response()->json(['code'=>500, 'msg'=>'登陆失效', 'data'=>'2']);
        }
        if ($request['state'] != 1) {
            return response()->json(['code'=>500, 'msg'=>'登陆失效', 'data'=>'3']);
        }
        $find_dein = DB::table('login_device_info')
            ->where('dein_info', rtrim($request['facility'], '&state'))
            ->where('dein_state', 1)
            ->select('dein_update_time', 'dein_id')
            ->first();
        $update_time = $find_dein->dein_update_time;
        if (empty($update_time)) {
            return response()->json(['code'=>500, 'msg'=>'登陆失效', 'data'=>'4']);
        }

        // 判断是否过期  一分钟
        $update_time = date('Y-m-d H:i:s', strtotime('+1 minute', strtotime($update_time)));
        if ($update_time < date('Y-m-d H:i:s')) {
            return response()->json(['code'=>500, 'msg'=>'登陆时间过期', 'data'=>'5']);
        }

        $res = DB::table('login_device_info')
            ->where('dein_id', $find_dein->dein_id)
            ->update(['dein_state' => 2, 'dein_update_time' => date('Y-m-d H:i:s')]);
        if (empty($res)) {
            return response()->json(['code'=>500, 'msg'=>'保存失败', 'data'=>'']);
        }
        return response()->json(['code'=>200, 'msg'=>'成功', 'data'=>'']);
    }

    // 左侧一级二级导航
    public function leftList(Request $request)
    {
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        if (empty($user_info->adm_id)) {
            $adm_id = $request['adm_id'];
            $adm_shop_id = $request['adm_shop_id'];
        } else {
            $adm_id = $user_info->adm_id;
            $adm_shop_id = $user_info->adm_shop_id;
        }
        // 查询账号信息
        $find_admin = 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_id', $adm_id)
            ->where('asr.shop_id', $adm_shop_id)
            ->select('a.adm_id', 'a.adm_name', 'a.adm_account', 'a.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')
            ->first();
        if (empty($find_admin)) {
            $shop_superior_id = DB::table('shop')
                ->where('shop_id', $adm_shop_id)
                ->value('shop_superior_id');
            if ($shop_superior_id) {
                //总店
                $find_admin_sup = DB::table('admin_shop_role as asr')
                    ->leftjoin('admin as a', 'asr.adm_id', '=', 'a.adm_id')
                    ->leftjoin('role', 'role.rol_id', '=', 'asr.role_id')
                    ->where('asr.adm_id', $adm_id)
                    ->where('asr.shop_id', $shop_superior_id)
                    ->where('asr.adm_state', 1)
                    ->select('a.adm_id', 'a.adm_name', 'a.adm_account', 'a.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')
                    ->first();
                $Store_Manager = DB::table('admin_shop_role as asr')
                    ->leftjoin('admin as a', 'asr.adm_id', '=', 'a.adm_id')
                    ->leftjoin('role', 'role.rol_id', '=', 'asr.role_id')
                    ->where('asr.adm_shop_leave', 1)
                    ->where('asr.shop_id', $adm_shop_id)
                    ->where('asr.adm_state', 1)
                    ->select('a.adm_id', 'a.adm_name', 'a.adm_account', 'a.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')
                    ->first();
                $find_admin = $Store_Manager;
                $find_admin->adm_id = $find_admin_sup->adm_id;
            }
        }
        if (empty($find_admin)) {
            return response()->json(['code'=>500, 'msg'=>'账号密码错误', 'data'=>'账号密码错误']);
        }
        if ($find_admin->adm_state == 2) {
            return response()->json(['code'=>300, 'msg'=>'当前账号已被停用', 'data'=>'当前账号已被停用']);
        }
        if ($find_admin->rol_state != 1) {
            return response()->json(['code'=>500, 'msg'=>'当前账号所属角色权限已被停用', 'data'=>'当前账号所属角色权限已被停用']);
        }
        // 查找此用户对应得角色权限
        $role_auth = $this->getRolePrivilege($find_admin);
        $role_info = $role_auth['role_auth'];

        // 对象转数组
        // $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;
    }

    // 修改活动性质为一次性时,自动启动状态
    public function activityStart($find_admin, $shop_set_superior_id)
    {
        $time = date('Y-m-d H:i:s');
        // 查询活动列表是否自动启动
        $find_start = DB::table('activity')
            ->where('acti_cid', $find_admin->adm_cid)
            ->where('acti_superior_shop_id', $shop_set_superior_id)
            ->where('acti_start_time', '>=', $time)
            ->where('acti_state', 2)
            ->select('acti_id', 'acti_start_time')
            ->get()
            ->toArray();
        if ($find_start) {
            // 当前时间大于活动开始时间,活动状态从发布变成启动
            $sql = 'UPDATE `faster_activity` SET ';
            $acti_id_sql = '';
            $update_time_sql = '';
            $ids = '';
            foreach ($find_start as $key => $value) {
                // 更新活动表的数据
                $acti_id_sql = $acti_id_sql . ' WHEN ' . $value->acti_id;
                $acti_id_sql = $acti_id_sql . ' THEN "' . 3 . '"';

                $update_time_sql = $update_time_sql . ' WHEN ' . $value->acti_id;
                $update_time_sql = $update_time_sql . ' THEN "' . date('Y-m-d H:i:s') . '"';
                $ids = $ids . $value->acti_id . ',';
            }
            $sql = $sql . ' `acti_state` = CASE `acti_id`' . $acti_id_sql . ' END,';
            $sql = $sql . ' `acti_update_time`=  CASE `acti_id` ' . $update_time_sql . ' END';
            $sql = $sql . ' WHERE `acti_id` IN (' . trim($ids, ',') . ')';
            $acti_res = DB::update($sql);
        }
    }

    // 修改活动性质为一次性时,自动终止状态
    public function activityTerminate($find_admin, $shop_set_superior_id)
    {
        $time = date('Y-m-d H:i:s');
        // 查询活动列表是否自动启动
        $find_terminate = DB::table('activity')
            ->where('acti_cid', $find_admin->adm_cid)
            ->where('acti_superior_shop_id', $shop_set_superior_id)
            ->where('acti_end_time', '<', $time)
            ->where('acti_activity_nature', 1)
            ->where('acti_state', 3)
            ->select('acti_id', 'acti_end_time')
            ->get()
            ->toArray();
        if ($find_terminate) {
            // 当前时间大于活动开始时间,活动状态从发布变成启动
            $sql = 'UPDATE `faster_activity` SET ';
            $acti_id_sql = '';
            $update_time_sql = '';
            $ids = '';
            foreach ($find_terminate as $key => $value) {
                // 更新活动表的数据
                $acti_id_sql = $acti_id_sql . ' WHEN ' . $value->acti_id;
                $acti_id_sql = $acti_id_sql . ' THEN "' . 5 . '"';

                $update_time_sql = $update_time_sql . ' WHEN ' . $value->acti_id;
                $update_time_sql = $update_time_sql . ' THEN "' . date('Y-m-d H:i:s') . '"';
                $ids = $ids . $value->acti_id . ',';
            }
            $sql = $sql . ' `acti_state` = CASE `acti_id`' . $acti_id_sql . ' END,';
            $sql = $sql . ' `acti_update_time`=  CASE `acti_id` ' . $update_time_sql . ' END';
            $sql = $sql . ' WHERE `acti_id` IN (' . trim($ids, ',') . ')';
            $acti_res = DB::update($sql);
        }

        // 周期性只有进行中
        $find_end = DB::table('activity')
            ->where('acti_cid', $find_admin->adm_cid)
            ->where('acti_superior_shop_id', $shop_set_superior_id)
            ->where('acti_start_time', '>=', $time)
            ->where('acti_activity_nature', 2)
            ->where('acti_state', '3')
            ->select('acti_id', 'acti_start_time', 'acti_activity_days', 'acti_cycle_number')
            ->get()
            ->toArray();
        if ($find_end) {
            // 当前时间大于活动开始时间,活动状态从发布变成启动
            $sql = 'UPDATE `faster_activity` SET ';
            $acti_cycle_number_sql = '';
            $update_time_sql = '';
            $ids = '';
            foreach ($find_end as $key => $value) {
                // 当前时间 - 活动开始时间的天数
                $start_time = strtotime($time);
                $end_time = strtotime($value->acti_start_time);
                $days = ceil(($start_time - $end_time) / 86400);
                // 根据天数算出是第几周期
                $cycle = ceil($days / $value->acti_activity_days);
                // 周期序号相等,不需要更新周期序号
                if ($cycle != $value->acti_cycle_number) {
                    // 更新活动表的数据
                    $acti_cycle_number_sql = $acti_cycle_number_sql . ' WHEN ' . $value->acti_id;
                    $acti_cycle_number_sql = $acti_cycle_number_sql . ' THEN "' . $cycle . '"';

                    $update_time_sql = $update_time_sql . ' WHEN ' . $value->acti_id;
                    $update_time_sql = $update_time_sql . ' THEN "' . date('Y-m-d H:i:s') . '"';
                    $ids = $ids . $value->acti_id . ',';
                }
            }
            $sql = $sql . ' `acti_cycle_number` = CASE `acti_id`' . $acti_cycle_number_sql . ' END,';
            $sql = $sql . ' `acti_update_time`=  CASE `acti_id` ' . $update_time_sql . ' END';
            $sql = $sql . ' WHERE `acti_id` IN (' . trim($ids, ',') . ')';
            if ($ids != '') {
                $acti_update_res = DB::update($sql);
            }
        }
    }
}
