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

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Api\Verify\VerifyMobileLoginController;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Crypt;

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

        // 查询账号信息
        $find_admin = DB::table('admin as a')
            ->leftjoin('admin_shop_role as asr', 'asr.adm_id', '=', 'a.adm_id')
            ->leftjoin('role', 'role.rol_id', '=', 'a.adm_role_app')
            ->where('adm_phone', $request['username'])
            ->where('adm_password', md5($request['password'].'faster123456'))
            ->select('a.adm_id', 'asr.adm_shop_leave as adm_leave', '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_category', 'adm_type', 'adm_work_state')
            ->first();
        if (empty($find_admin)) {
            return response()->json(['code'=> 500,'msg'=>'账号密码错误','data'=>'{}']);
        }
        //账号类型 1门店账号  2虚拟加盟店账号 3既是门店又是加盟店
        if(in_array($find_admin->adm_type, [2,3])){
            $find_admin->rol_category = 2;
            $find_admin->rol_state = 1;
            if(!empty($find_admin->rol_privilege)){
                $find_admin->rol_privilege = $find_admin->rol_privilege .',1';
            }else{
                $find_admin->rol_privilege = $find_admin->rol_privilege .'1';
            }
        }

        if ($find_admin->rol_category != 2) {
            return response()->json(['code'=> 500,'msg'=>'此账号所属角色没有登录App权限','data'=>'{}']);
        }
        if (empty($find_admin)) {
            return response()->json(['code'=> 500,'msg'=>'账号密码错误','data'=>'{}']);
        }
        if ($find_admin->adm_state == 2) {
            return response()->json(['code'=> 500,'msg'=>'当前账号已被停用','data'=>'{}']);
        }
        if ($find_admin->rol_state != 1) {
            return response()->json(['code'=> 500,'msg'=>'当前账号所属角色权限已被停用','data'=>'{}']);
        }
        if (!in_array($find_admin->adm_leave, [3, 4, 5]) && $find_admin->adm_type == 1) {
            return response()->json(['code'=> 500,'msg'=>'当前账号不是技师或业务员职位，不允许登录','data'=>'{}']);
        }
        if ($find_admin->adm_id !== 1) {
            // 查询账号所属门店是否停用
            $find_shop = DB::table('shop')
                ->where('shop_id', $find_admin->adm_shop_id)
                ->select('shop_state', 'shop_versions')
                ->first();
            if ($find_shop->shop_state != 1) {
                return response()->json(['code'=> 500,'msg'=>'当前账号所属门店已停业','data'=>'{}']);
            }
        }
        //修改拜访任务周期
        $this->visitTask($find_admin);

        // 生成token
        $unique_string = md5(uniqid(md5(microtime(true)).rand(100000, 999999), true));//生成唯一字符串
        $api_token = sha1($unique_string);//加密
        $find_login = DB::table('login_webapp')
                    ->where('adm_id', '=', $find_admin->adm_id)
                    ->select('adm_id', 'lowe_last_login')
                    ->first();
        if (empty($find_login)) {
            // 获取用户对应角色权限
            $role_auth = $this->getRolePrivilege($find_admin);

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

            //如果用户第一次登陆,将用户的登录状态保存到临时表
            $lote_data['adm_id'] = $find_admin->adm_id;//账号id
            $lote_data['lowe_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_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_webapp')->insert($lote_data);
            if (empty($lote_res)) {
                return response()->json(["code"=>500,'msg'=>'api_token写入失败','data'=>'{}']);
            }

            // 查询当前技师的移动仓库id
            // ware_type 类型：1固定仓2技师库3移动仓
            $ware_id = DB::table('warehouse')
                ->where('ware_cid', $find_admin->adm_cid)
                ->where('ware_shop_id', $find_admin->adm_shop_id)
                ->where('ware_leader_id', $find_admin->adm_id)
                ->where('ware_type', 3)
                ->value('ware_id');
            //查询门店设置数据
            $find_shop_set = DB::table('shop_set')
                ->where('shse_shop_id', $find_admin->adm_shop_id)
                ->select('shse_ampere_hour_price')
                ->first();
            // 返回数据
            $return_data = [
                            'api_token'=>Crypt::encrypt($api_token),//生成前台token
                            'default_url'=>$default_url,//默认跳转页面
                            'adm_id'=>$find_admin->adm_id,
                            'shop_id'=>$find_admin->adm_shop_id,
                            'adm_leave'=>$find_admin->adm_leave,
                            'adm_name'=>$find_admin->adm_name,
                            'adm_phone'=>$find_admin->adm_phone,
                            'adm_work_state'=>$find_admin->adm_work_state,
                            'ware_id'=>$ware_id,
                            'shop_versions'=>$find_shop->shop_versions,
                            'role_auth'=>$role_auth['role_auth'],
                            'shse_ampere_hour_price'=>$find_shop_set->shse_ampere_hour_price/100,
                            'role_below'=>''
                        ];
            return response()->json(["code"=>200,'msg'=>'登录成功','data'=>$return_data]);
        }

        $now_time = time();

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

            // 确认此账号默认跳转页面
            $default_url = $this->getDefaultPath($role_auth['role_auth']);
            //修改登陆状态
            $lote_data['lowe_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_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_webapp')
                        ->where('adm_id', $find_admin->adm_id)
                        ->update($lote_data);
            if (empty($lote_res)) {
                return response()->json(["code"=>500,'msg'=>'api_token写入失败','data'=>'{}']);
            }
            // 查询当前技师的移动仓库id
            $ware_id = DB::table('warehouse')
                ->where('ware_cid', $find_admin->adm_cid)
                ->where('ware_shop_id', $find_admin->adm_shop_id)
                ->where('ware_leader_id', $find_admin->adm_id)
                ->where('ware_type', 3)
                ->value('ware_id');
            //查询门店设置数据
            $find_shop_set = DB::table('shop_set')
                ->where('shse_shop_id', $find_admin->adm_shop_id)
                ->select('shse_ampere_hour_price')
                ->first();
            // 返回数据
            $return_data = [
                            'api_token'=>Crypt::encrypt($api_token),//生成前台token
                            'default_url'=>$default_url,//默认跳转页面
                            'adm_id'=>$find_admin->adm_id,
                            'shop_id'=>$find_admin->adm_shop_id,
                            'adm_leave'=>$find_admin->adm_leave,
                            'adm_name'=>$find_admin->adm_name,
                            'adm_phone'=>$find_admin->adm_phone,
                            'adm_work_state'=>$find_admin->adm_work_state,
                            'ware_id'=>$ware_id,
                            'shop_versions'=>$find_shop->shop_versions,
                            'role_auth'=>$role_auth['role_auth'],
                            'shse_ampere_hour_price'=>$find_shop_set->shse_ampere_hour_price/100,
                            'role_below'=>''
                        ];
            return response()->json(["code"=>200,'msg'=>'登录成功','data'=>$return_data]);
        } else {
            return response()->json(["code"=>400,'msg'=>'该用户已经登录','data'=>'{}']);
        }
    }

    //退出
    public function quit(Request $request)
    {
        try {
            $api_token = Crypt::decrypt($request['api_token']);
        } catch (\Exception $e) {
            return response()->json(["code"=>500,'msg'=>'api_token失效','data'=>'{}']);
        }
        // 更改最后登录时间
        $lote_data['lowe_last_login'] = 0;//最后登陆时间
        $res = DB::table('login_webapp')
            ->where('api_token', $api_token)
            ->update($lote_data);
        if ($res) {
            return response()->json(["code"=>200,'msg'=>'退出成功','data'=>'{}']);
        } else {
            return response()->json(["code"=>500,'msg'=>'退出失败','data'=>'{}']);
        }
    }

    /**
     * [getRolePrivilege 获取角色权限]
     * @param  [type] $find_admin [用户信息]
     * @return [type]                [description]
     */
    protected function getRolePrivilege($find_admin)
    {
        $pri_id = explode(',', $find_admin->rol_privilege);
        // 查询权限id对应的权限数据
        $privileges = DB::table('privileges_app')
                    ->whereIn('pri_id', $pri_id)
                    ->get();
        $privileges = json_decode(json_encode($privileges), true);
        // $privileges2 = json_encode($privileges);
        // dump($privileges);die;
        // dump($privileges);die;

        // // 如果当前账号不是root管理去除客户管理相关权限和账号管理相关权限
        // if($role_info['adm_cid'] !== 1 || $role_info['adm_leave'] !== 1)
        // {
        //     foreach($privileges as $key=>$value)
        //     {
        //         if($role_info['adm_leave'] !== 1)
        //         {
        //             // 删除账号相关
        //             if($value['pri_id'] == 37 || $value['pri_fid'] == 37)
        //             {
        //                 unset($privileges[$key]);
        //             }
        //         }
        //         // 删除客户列表相关
        //         if($value['pri_id'] == 157 || $value['pri_fid'] == 157)
        //         {
        //             unset($privileges[$key]);
        //         }
        //     }
        // }

        $privileges = array_values($privileges);
        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;
    }

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

    // 左侧一级二级导航
    public function leftList(Request $request)
    {
        try {
            $api_token = Crypt::decrypt($request['api_token']);
        } catch (\Exception $e) {
            return response()->json(["code"=>500,'msg'=>'非法api_token','data'=>'{}']);
        }
        $role_info = DB::table('login_temporary')
                            ->where('api_token', '=', $api_token)
                            ->select('role_auth')
                            ->first();
        if (empty($role_info)) {
            return response()->json(["code"=>500,'msg'=>'api_token已过期','data'=>'{}']);
        }

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

        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'=>'导航获取失败','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 visitTask($user_info)
    {
        $data = DB::table('visit')
            ->where('vis_visvity_nature', 2)
            ->where('vis_executor_adm_id', $user_info->adm_id)
            ->where('vis_end_time', '<', date('Y-m-d H:i:s'))
            ->where('vis_delete', 1)
            ->get(['vis_id','vis_days','vis_end_time','vis_cycle_number']);
        $data = json_decode(json_encode($data), true);
        if (!empty($data)) {
            // 结束时间小于当前时间,周期重新开始
            $sql = 'UPDATE `faster_visit` SET ';
            $update_time_sql = '';
            $cycle_number = '';
            $actual_quantity = '';
            $vis_ids = [];
            foreach ($data as $key => $value) {
                // 结束时间
                $end_time = $value['vis_end_time'];
                $end_time = date('Y-m-d H:i:s', strtotime($end_time.' +'.$value['vis_days'].' day'));
                $update_time_sql = $update_time_sql . ' WHEN ' .$value['vis_id'];
                $update_time_sql = $update_time_sql . ' THEN "'.$end_time.'"';
                $number = $value['vis_cycle_number'] + 1;
                //拜访序号
                $cycle_number = $cycle_number . ' WHEN ' .$value['vis_id'];
                $cycle_number = $cycle_number . ' THEN "' .$number.'"';

                //实际拜访次数
                $actual_quantity = $actual_quantity . ' WHEN ' .$value['vis_id'];
                $actual_quantity = $actual_quantity . ' THEN 0';

                $vis_ids[] = $value['vis_id'];
            }
            $sql = $sql. ' `vis_cycle_number` = CASE `vis_id`'.$cycle_number.' END,';
            $sql = $sql. ' `vis_actual_quantity` = CASE `vis_id`'.$actual_quantity.' END,';
            $sql = $sql .' `vis_end_time`=  CASE `vis_id` '.$update_time_sql.' END';
            $sql = $sql .' WHERE `vis_id` IN ('.trim(implode(',', $vis_ids), ',').')';
            DB::update($sql);
            //修改实际数量
            $vicl['vicl_actual_quantity'] = 0;
            $vicl['vicl_update_time'] = date('Y-m-d H:i:s');
            DB::table('visit_clients')
                ->whereIn('vicl_vis_id', $vis_ids)
                ->update($vicl);
        }
    }
}
