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

use App\Models\Company;
use Illuminate\Http\Request;
use App\Models\Admin;
use App\Models\AdminToken;
use App\Models\Department;
use App\Models\Permissions;
use App\Models\MassagePower;
use App\Models\PhoneCoke;
use App\Models\Bmmc;
use App\Models\AdminInfor;
use App\Models\Functions;
use App\Services\BmmcService;
use App\Services\CommonService;
use BlueCity\Core\Inc\ErrorInc;
use App\Services\LoginService;
use App\Inc\VerificationCodeInc;
use App\Services\RedisService;
//use Illuminate\Support\Facades\Redis;
use DB;
use App\Http\Controllers\BaseController;
//登录控制器
class LoginController extends BaseController
{
	protected $rules = array(
		'account' => '账号',
		'password' => '密码',
		'loginType' => '登录类型',
		'phone' => '电话',
		'code' => '验证码',
		'browser' => '设备参数',
		'id' => '数据编号',
		'send_type' => '验证码类型',
		'token' => '授权码',
	);
    /**|---------------------------------------------------------------------------------
     * @name  登录
     * @param account   账号
     * @param password  密码
     * @param id  用户id
     * @param loginType  登录方式 1:账号密码登录 2验证码登录  3微信登录
     * @param phone  电话号码
     * @param code  验证码
     * @param browser  登录设备参数
     * @return \Illuminate\Http\JsonResponse
     * @author dou <2021/07/14>
     * |---------------------------------------------------------------------------------
     */
    public function login (Request $request)
    {
	    $parameter = $request->only('account','password','loginType','phone','code','browser','id','send_type','com_name');
	    $checkKey = CommonService::checkKey(['loginType','browser'],$parameter,$this->rules);
	    if($checkKey['code']!=1){
			return $this->error('参数'.$checkKey['data'].'未填写,或值为空', ErrorInc::INVALID_PARAM, []);
		}
        $ip = $request->ip();
	    if( $parameter['loginType'] == 1 ){
		    return self::accountLogin($parameter,$ip);
	    }elseif ( $parameter['loginType'] == 2 ){
	    	return self::phoneLogin($parameter,$ip);
	    }elseif ( $parameter['loginType'] ==3 ){
	    	return self::accreditLogin($parameter,$ip);
	    }else{
		    return $this->error('账号不存在，请联系客服', ErrorInc::FAILED_PARAM, []);
	    }

    }

	/**|---------------------------------------------------------------------------------
     * @name  账号登录
     * @param array $parameter   请求参数
     * @param string $ip  访问ip
     * @return \Illuminate\Http\JsonResponse
     * @author dou <2021/07/14>
     * |---------------------------------------------------------------------------------
     */
     public function accountLogin ( $parameter , $ip ){
	     $checkKey = CommonService::checkKey(['account','password'],$parameter,$this->rules);
	    if($checkKey['code'] ==1){

            $result = Admin::where('admin_acc',$parameter['account'])->first();
            if (!$result){
	            return $this->error('账号不存在，请联系客服', ErrorInc::REQUEST_FORBIDDEN, []);
            }
            //验证是否有此公司
           // $parameter['com_name'] = '天津公司';
            $input['com_name'] = trim($parameter['com_name']);
            $input['admin_groupnew'] = trim($result['admin_groupnew']);
            $input['company_id'] = trim($result['company_id']);
            if($result['admin_groupnew']!=7){
                $retCom = $this->checkCompany($input);
                if($retCom->original['ErrorCode']!=1){
                    return $retCom;
                }
            }


            if($result['admin_password'] == md5($parameter['password'])){
                if($result['enable']==1){
//	                if(!in_array($ip,LoginService::getIp())){
//                		$weixin['ip'] = $ip;
//			            $weixin['dress'] = LoginService::ipDress($ip);
//			            $weixin['account'] = $parameter['account'];
//			            $weixin['admin_id'] = $result['id'];
//			            $weixin['equipment'] = LoginService::judgeEquipment($parameter['browser']);
//			            //$this->post_form('http://weixin.sudianwang.com/index.php/BindingAccount/loginPush', $weixin);
//			            $data['account'] = $result['admin_acc'];
//				        $data['admin_groups'] = $result['admin_groupnew'];
//				        $data['id'] = $result['id'];
//			            return $this->error('非办公区ip，请等待微信授权或者切换至验证码登录', ErrorInc::REQUEST_FORBIDDEN, $data);
//	                }
                    return self::getGroupData($parameter,$result,$ip);
                }else{
	                return $this->error('账号已停用，请联系客服！', ErrorInc::REQUEST_FORBIDDEN, []);
                }
            }else{
	            return $this->error('密码错误', ErrorInc::REQUEST_FORBIDDEN, []);
            }
        }else{
	        //return $this->error('请输入账号或密码', ErrorInc::REQUEST_FORBIDDEN, []);

			return $this->error('参数'.$checkKey['data'].'未填写,或值为空', ErrorInc::INVALID_PARAM, []);
        }
     }

     /**|---------------------------------------------------------------------------------
     * @name  授权登录
     * @param array $parameter   请求参数
     * @param string $ip  访问ip
     * @return \Illuminate\Http\JsonResponse
     * @author dou <2021/07/14>
     * |---------------------------------------------------------------------------------
     */
     public function accreditLogin ( $parameter , $ip ){
	    $checkKey = CommonService::checkKey(['account','password','code'],$parameter,$this->rules);
	    if($checkKey['code'] == 1){
            $result = Admin::where('admin_acc',$parameter['account'])->first();
            if (!$result){
	            return $this->error('账号不存在，请联系客服', ErrorInc::REQUEST_FORBIDDEN, []);
            }
            //验证是否有此公司
            $input['com_name'] = trim($parameter['com_name']);
            $input['admin_groupnew'] = trim($result['admin_groupnew']);
            $input['company_id'] = trim($result['company_id']);
            if($result['admin_groupnew']!=7){
                $retCom = $this->checkCompany($input);
                if($retCom->original['ErrorCode']!=1){
                    return $retCom;
                }
            }

            if($result['admin_password'] == md5($parameter['password'])){
                if($result['enable'] == 1){
	                $search_token = AdminToken::where('at_adminid',$result['id'])->where('at_accredit',$parameter['code'])->orderBy('at_time','DESC')->first();
	                if($search_token){
                    	return self::getGroupData($parameter,$result,$ip);
                	}else{
	                	return $this->error('授权码错误', ErrorInc::REQUEST_FORBIDDEN, []);
                	}
                }else{
	                return $this->error('账号已停用，请联系客服！', ErrorInc::REQUEST_FORBIDDEN, []);
                }
            }else{
	            return $this->error('密码错误', ErrorInc::REQUEST_FORBIDDEN, []);
            }
        }else{
	        //return $this->error('请输入账号或密码', ErrorInc::REQUEST_FORBIDDEN, []);

			return $this->error('参数'.$checkKey['data'].'未填写,或值为空', ErrorInc::INVALID_PARAM, []);
        }
     }
     /**|---------------------------------------------------------------------------------
     * @name  电话登录
     * @param array $parameter   请求参数
     * @param string $ip  访问ip
     * @return \Illuminate\Http\JsonResponse
     * @author dou <2021/07/14>
     * |---------------------------------------------------------------------------------
     */
     public function phoneLogin ( $parameter , $ip ){
	    $checkKey = CommonService::checkKey(['account','id','phone','code','send_type'],$parameter,$this->rules);
	    if($checkKey['code'] == 1){
            $result = Admin::where('admin_acc',$parameter['account'])->where("id",$parameter['id'])->first();
            if (!$result){
	            return $this->error('账号不存在，请联系客服', ErrorInc::REQUEST_FORBIDDEN, []);
            }
            //验证是否有此公司
            $input['com_name'] = trim($parameter['com_name']);
            $input['admin_groupnew'] = trim($result['admin_groupnew']);
            $input['company_id'] = trim($result['company_id']);
            if($result['admin_groupnew']!=7){
                $retCom = $this->checkCompany($input);
                if($retCom->original['ErrorCode']!=1){
                    return $retCom;
                }
            }

            $phc_type = CommonService::aginCodeType($parameter['send_type']);
			if($phc_type == 'error'){
				return $this->error('操作类型错误', ErrorInc::FAILED_PARAM, []);
			}else{
				$res = PhoneCoke::whereRaw("phc_phone='".$parameter['phone']."' and phc_creacttime<'".date('Y-m-d H:i:s')."' and phc_expirationtime>'".date("Y-m-d H:i:s")."' and phc_coke='".$parameter['code']."' and phc_type='".$phc_type."'")->value('phc_id');
				if($res){
		            if($result['admin_password'] == md5($parameter['password'])){
		                if($result['enable'] == 1){
	                    	return self::getGroupData($parameter,$result,$ip);
		                }else{
			                return $this->error('账号已停用，请联系客服！', ErrorInc::REQUEST_FORBIDDEN, []);
		                }
		            }else{
			            return $this->error('密码错误', ErrorInc::REQUEST_FORBIDDEN, []);
		            }
	            }else{
		            return $this->error('验证码不存在', ErrorInc::REQUEST_FORBIDDEN, []);
	            }
            }
        }else{
			return $this->error('参数'.$checkKey['data'].'未填写,或值为空', ErrorInc::INVALID_PARAM, []);
        }
     }
  	/**|----------------------------------------------------------------------
     * @name 获取账号权限
     * @param array $result 账号对应admin数据
     * @param string $ip 操作人ip
     * @param array $parameter   请求参数
     * @param Request $request
     * @return json
     * @author dou <2021-07-14 19:36>
     * |----------------------------------------------------------------------
     */
     public function getGroupData ( $parameter , $result , $ip ){
         $company = Company::where("com_id",$result['company_id'])->first();
         $com_parent_id = $company['com_parent_id'];
//        $com_parent_id = Company::where("com_id",$result['company_id'])->value('com_parent_id');
         $result['com_parent_id'] = $com_parent_id.",".$result['company_id'];
         $result['com_brand'] = $company['com_brand'];
         $all_company = Company::whereRaw("FIND_IN_SET(".$result['company_id'].",com_parent_id) and com_type=2")->select('com_id')->get();
         $all_company = CommonService::dataToArray($all_company);
         if($all_company){
             $all_company = array_column($all_company, 'com_id');
             $all_company[] = $result['company_id'];
         }else{
             $all_company = [$result['company_id']];
         }
         $result['all_company'] = $all_company;

         $all_companys = Company::whereRaw("FIND_IN_SET(".$result['company_id'].",com_parent_id) and com_type=1")->select('com_id')->get();
         $all_companys = CommonService::dataToArray($all_companys);
         if($all_companys){
             $all_companys = array_column($all_companys, 'com_id');
             $all_companys[] = $result['company_id'];
         }else{
             $all_companys = [$result['company_id']];
         }
         $result['all_companys'] = $all_companys;
         $result['com_type'] = $company['com_type'];
         if($company['com_type']==2){
             $result['search_id'] = Admin::where('company_id',$result['company_id'])->where("admin_groupnew",3)->value('id');
         }else{
             $result['search_id']=$result['id'];
         }
     	$function = Functions::where('function_type',3)->select('function_id','function_model','function_action')->get()->toArray();
        $list = [];
        foreach ($function as $k =>$v){
            $list[] = $v['function_model'].':'.$v['function_action'];
        }
        $arr['at_time'] = date('Y-m-d H:i:s');
        $api_token = md5(date('Ymdhis').$result['id'].rand(1000,9999));//token
        $arr['at_token'] = $api_token;
        $arr['at_adminid'] = $result['id'];

        $at_permissions['admindata'] = $result;
        //$at_permissions['function'] = $list;


        $search_token = AdminToken::where('at_adminid',$result['id'])->orderBy('at_time','DESC')->first();
        /*********************获取所有按钮**************************/
        //$admin_groupnew = Admin::where('admin_acc',$request->input('account'))->where('admin_password',md5($request->input('password')))->value('admin_groupnew');

        $function_id = Department::where('id',$result['admin_groupnew'])->value('function_id');

        $function_id = explode(',',$function_id);

        $at_permissions['function_id'] = $function_id;
        $at_permissions = json_encode($at_permissions);
        $arr['at_permissions'] = $at_permissions;

        $res = Permissions::whereIn('function_id',$function_id)->where('function_position','!=',3)->select('function_id','function_parent_id','function_name','function_model','function_action','function_position','sort_order')->orderBy('sort_order','DESC')->get()->toArray();
        $at_permiss = [];
        foreach ($res as $k=>$v){
            $at_permiss[$v['function_parent_id']][] = $v;
        }
        $arr['at_perm'] = json_encode($at_permiss);
        //$arr['at_button'] = json_encode($at_permiss);
        $arr['at_accredit'] = '';
        /********************************************************************/
        if ($search_token){
            $token_Info = AdminToken::where('at_token',$search_token['at_token'])->update($arr);
        }else{
            $token_Info = AdminToken::where('at_token',$search_token['at_token'])->insert($arr);
        }
        if ($parameter['browser']){
            $browser = $parameter['browser'];
        }else{
            $browser = '暂无';
        }
        $content = "登录ip：".$ip."，浏览器信息：".$browser;
        $this->insertingLog("成员登录，",'',$content,"登录",$ip,$result['admin_acc']);//日志
        $data['account'] = $result['admin_acc'];
        $data['api_token'] = $api_token;
        $data['defaultAction'] = "Homeshow";
        $data['admin_groups'] = $result['admin_groupnew'];
        $data['id'] = $result['id'];
        $data['massage_power'] = MassagePower::where('id',$result['id'])->value('function');
        $data['company_id'] = $result['company_id'];
        if ($token_Info){
	        $arr['at_perm'] = json_decode($arr['at_perm']);
        	//$arr['at_button'] = json_decode($arr['at_button']);
        	$arr['at_permissions'] = json_decode($arr['at_permissions']);
        	$id = 'Login'.$result['id'];
        	RedisService::redisSet($id, $arr);
            return $this->success('登录成功', $data);
        }
     }
    /**|----------------------------------------------------------------------
     * @name 获取动态左侧栏目（权限控制）
     * @param Request $request
     * @return json
     * @author he <2019-06-18 15:09>
     * |----------------------------------------------------------------------
     */
    public function jurisdiction (Request $request)
    {
        $at_adminid = DB::table('admin_token')->where('at_token',$request->input('token'))->value('at_adminid');
        $admin_acc = DB::table('admin')->where('id',$at_adminid)->value('admin_acc');
        if (!isset($at_adminid)){
            return $this->error('授权已过期，请重新登录id', 1001, []);
        } else {
            $admin_groupnew = Admin::where('id',$at_adminid)->value('admin_groupnew');
            $function_id = Bmmc::where('id',$admin_groupnew)->value('function_id');
            $function_id = explode(',',$function_id);
            if ($admin_groupnew == "研发"){
                $function = Functions::where('function_type','!=',3)->select('function_id','function_parent_id','function_name','function_model','function_action','function_img_src')->orderBy('sort_order','DESC')->get();
            }else{
                $function = Functions::whereIn('function_id',$function_id)->where('function_type','!=',3)->select('function_id','function_parent_id','function_name','function_model','function_action','function_img_src')->orderBy('sort_order','DESC')->get();
            }

            if (!$function->isEmpty()){
                $function = $function->toArray();
                foreach ($function as $k=>$v){
                    $function[$k]['mate']['title'] = $v['function_name'];
                    $function[$k]['mate']['function_id'] = $v['function_id'];
                }
                $tree = BmmcService::getsTree($function,0);
                $column = DB::table('column')->where('admin_id', $at_adminid)->value('column');
                if (!empty($column)) {
                    $column = json_decode($column, true);
                    $tees = $tree;
                    $listArr = [];
                    foreach ($tees as $k => $v) {
                        $listArr[$v['function_id']] = $v;
                        foreach ($v['function_children'] as $ks => $vs) {
                            $listArr[$v['function_id']][$vs['function_id']] = $vs;
                        }
                    }
                    //return $listArr;exit;
                    foreach ($column as $k => $v) {
                        $column[$k]['children_id'] = explode(',', trim($v['children_id'], ','));
                    }

                    $trers = [];
                    foreach ($column as $kk => $vv) {
                        $trers[$kk]['function_id'] = $listArr[$vv['function_id']]['function_id'];
                        $trers[$kk]['function_model'] = $listArr[$vv['function_id']]['function_model'];
                        $trers[$kk]['function_name'] = $listArr[$vv['function_id']]['function_name'];
                        $trers[$kk]['function_parent_id'] =
                            $listArr[$vv['function_id']]['function_parent_id'];
                        $trers[$kk]['function_img_src'] = $listArr[$vv['function_id']]['function_img_src'];
                        $trers[$kk]['mate'] = $listArr[$vv['function_id']]['mate'];
                        foreach ($vv['children_id'] as $key => $value) {
                            $trers[$kk]['function_children'][]= $listArr[$vv['function_id']][$value];

                        }

                    }
                    if ($trers){
                        return $this->success('登录成功', $tree);
                    }else{
                        return $this->error('授权已过期，请重新登录trers', 1001, []);
                    }

                }

                if ($tree){
                    return $this->success('登录成功', $tree);
                }else{
                    return $this->error('授权已过期，请重新登录', 1001, []);
                }
            }else{
                return $this->error('授权已过期，请重新登录tree', 1001, []);
            }
        }
    }
    /**|---------------------------------------------------------------------------------
     * @name 退出
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @author he <2019-04-30>
     * |---------------------------------------------------------------------------------
     */
    public function logout (Request $request)
    {
    	$parameter = $request->only("token","id");
	    $checkKey  =CommonService::checkKey(['token','id'],$parameter,$this->rules);
	    if($checkKey['code'] == 1){//退出，让token时间过期，将时间修改为一天前
            $at_time = date('Y-m-d H:i:s',strtotime("-1 day",time()));
            $upRes = AdminToken::where('at_token',$parameter['token'])->where("at_adminid",$parameter['id'])->update(['at_time'=>$at_time]);
            if ($upRes){
	        	RedisService::redisDel($parameter['id']);
               	return $this->success('操作成功', []);
            }else{
	            return $this->error('操作失败', ErrorInc::MYSQL_FAILED, []);
            }
        }else{
	        return $this->error('token参数错误', ErrorInc::REQUEST_FORBIDDEN, []);
        }
    }
	/**|----------------------------------------------------------------------
     * @name 获取手机绑定账号
     * @param phone 手机号码
     * @param send_type  验证码类型
     * @param Request $request
     * @return json
     * @author dou <2021-07-15 16:10>
     * |----------------------------------------------------------------------
     */
    public function phoneAccount ( Request $request ){
	    $parameter = $request->only('phone','code','send_type');
	    $checkKey = CommonService::checkKey(['phone','code','send_type'],$parameter,$this->rules);
	    if($checkKey['code']!=1){
			return $this->error('参数'.$checkKey['data'].'未填写,或值为空', ErrorInc::INVALID_PARAM, []);
		}
		$phc_type = CommonService::aginCodeType($parameter['send_type']);
		if($phc_type == 'error'){
			return $this->error('操作类型错误', ErrorInc::FAILED_PARAM, []);
		}else{
			$res = PhoneCoke::whereRaw("phc_phone='".$parameter['phone']."' and phc_creacttime<'".date('Y-m-d H:i:s')."' and phc_expirationtime>'".date("Y-m-d H:i:s")."' and phc_coke='".$parameter['code']."' and phc_type='".$phc_type."'")->value('phc_id');
			if(!$res){
	            return $this->error('验证码不存在', ErrorInc::REQUEST_FORBIDDEN, []);
	        }else{
		     	$admininfor = AdminInfor::where("phone",$parameter['phone'])->select('admin_id')->get();
		     	if($admininfor->isEmpty()){
			     	return $this->error('手机号未绑定', ErrorInc::REQUEST_FORBIDDEN, []);
		     	}else{
			     	$admininfor = $admininfor->toArray();
			     	$admim_id = array_column($admininfor, 'admin_id');
			     	$admin = Admin::whereIn('id',$admim_id)->select('id','admin_acc','company_name')->get();
			     	if($admin->isEmpty()){
				     	return $this->error('手机号未绑定', ErrorInc::REQUEST_FORBIDDEN, []);
			     	}else{
				     	$admin = $admin->toArray();
				     	foreach( $admin as $k => $v ){
				     		$admin[$k]['company_name']=$v['company_name']??'智配贴装管理账号';
				     	}
				     	return $this->success('操作成功', $admin);
			     	}
		     	}
	     	}
     	}
    }

    /**
     * @name 检测公司信息
     * @param $input
     * @return mixed
     * @author du
     * @date 2022/9/15
     * @Time: 14:46
     */
    public function checkCompany($input){
        $com = Company::where('com_name',trim($input['com_name']))->first();
        if(!$com){
            return $this->error('公司不存在', ErrorInc::MYSQL_FAILED);
        }
        if($com['com_id']!=$input['company_id']){
            return $this->error('公司不正确', ErrorInc::MYSQL_FAILED);
        }
        $time = date('Y-m-d H:i:s');
        if($com['com_start_time']<=$time && $com['com_end_time']>=$time){
        }else{
            return $this->error('公司合同到期', ErrorInc::MYSQL_FAILED);
        }

        return $this->success('获取成功',$com['com_id']);
    }

}
