<?php
namespace wstmart\app\controller;
use wstmart\common\model\Auth as M;
use wstmart\common\model\AuthFamily as FM;
/**
 * ============================================================================
 * 认证控制器
 */
class Auth extends Base{
	// 前置方法执行列表
	protected $beforeActionList = [
			'checkAuth'
	];
	
	/**
	 * 获取认证信息
	 */
	public function getAuthInfo(){
		$m = new M();
		$isCompany = (int)input('post.isCompany');//1是合作认证
		if(1 == $isCompany){
			$m->setTable('auth_company');
		}
		$authInfo = $m->getInfo(['userId'=>$this->getUserId()],'*');
		exit(jsonReturn('',1,$authInfo));
	}
	/**
	 * 添加/编辑认证信息
	 */
	public function setAuthInfo(){
		$m = new M();
		$isCompany = (int)input('post.isCompany');//1是合作认证
		$data = input('post.');
		unset($data['headImgTag']);
		unset($data['accountBookImgTag']);
		$userId = $this->getUserId();
		if(1 == $isCompany){
    		if($this->user['authType'] == 1) exit(jsonReturn('没有权限!'));	

			$m->setTable('auth_personal'); 
			if($m->getField(['status'=>0,'userId'=>$userId],'id')){
				exit(jsonReturn('当前账户已申请个人认证,请等待审核'));	
			}
			$m->setTable('auth_company');
			$validate =  \think\Loader::validate('Auth');
			if(!$validate->scene('company')->check($data)){
				exit(jsonReturn($validate->getError()));
			}
		}else{			
    		if($this->user['authType'] == 2) exit(jsonReturn('没有权限!'));	   
    		$m->setTable('auth_company'); 
			if($m->getField(['status'=>0,'userId'=>$userId],'id')){
				exit(jsonReturn('当前账户已申请合作认证,请等待审核'));	
			}
			$m->setTable('auth_personal');
			$validate =  \think\Loader::validate('Auth');
			if(!$validate->scene('personal')->check($data)){
				exit(jsonReturn($validate->getError()));
			}
			$fm = new FM();
			if($fm->getInfo(['familyIdCard'=>$data['householdIdCard']],'id')){
				exit(jsonReturn('该身份证已报备,请更换'));	
			}
		}
		$isUpdate = 0;
		$authId = 0;
		$data['userId'] = $userId;
		$authInfo = $m->getInfo(['userId'=>$userId],'id,status');
		if($authInfo){
			if(!empty($data['authId'])){//更新状态
				$authId = $authInfo['id'];
				if($authId == $data['authId']){//更新
					$payPwd = $data['payPwd'];
					if(md5($payPwd) != $this->user['payPwd']){
						exit(jsonReturn('操作密码错误'));
					}
					$isUpdate = 1;
					if(1 == $authInfo['status']) {
						$data['status'] = 1;
						unset($data['householdIdCard']);//成功不可以更改身份证号
					}else{
						$data['status'] = 0;//拒绝时
					}

				}else{
					exit(jsonReturn('没有权限!'));	
				}
			}else{
				exit(jsonReturn('请不要重复提交'));	
			}
		}else{
			$userPhone = session('Reg_UserPhone');
			if(!$userPhone){
				exit(jsonReturn('操作超时,请重试!'));	
			}
			$verify = session('RegCode_UserPhone');
            $startTime = (int)session('RegCode_UserPhone_Time');
            if((time()-$startTime)>120){
               	exit(jsonReturn('验证码已超过有效期,请重新发送!'));	
            }
        	$mobileCode = $data['mobileCode'];
            if($mobileCode=="" || $verify != $mobileCode){
            	exit(jsonReturn('短信验证码错误!'));	
            }
            //$loginName = WSTRandomLoginName($log
			$data['status'] = 0;
		}
		
		unset($data['authId']);
		unset($data['mobileCode']);
		unset($data['isCompany']);	
		unset($data['payPwd']);	
		if($isUpdate){
			$isSuccess = $m->updateInfo(['id'=>$authId],$data);
		}else{
			$isSuccess = $m->insertInfo($data);
		}		
		if(false !== $isSuccess){
			session('Reg_UserPhone',null);	
			$userPhone = getAdminPhone();
    		$tpl = WSTMsgTemplates('PHONE_USER_UPDATE_NOTICE');
	    	if( $tpl['tplContent']!='' && $tpl['status']=='1'){
	    		$params = ['tpl'=>$tpl,'params'=>['name'=>$this->user['loginName']]];
	    		$m =  Model('common/LogSms');
	    		$rv = $m->sendSMS(0,$userPhone,$params,'PHONE_USER_UPDATE_NOTICE',0);
	    	}
	    	exit(jsonReturn('提交成功,请等待系统审核',1));
		}else{
			exit(jsonReturn('操作失败,请重试'));	
		}
	}
	/**
     * 获取验证码
     */
    public function getPhoneCode(){
    	$userPhone = input("post.userPhone");
    	if($this->user['userPhone'] && $this->user['userPhone'] != $userPhone){
    		exit(jsonReturn("手机号错误!"));
    	}
    	$rs = array();
    	if(!WSTIsPhone($userPhone)){
    		exit(jsonReturn("手机号格式不正确!"));
    	}
    	$m = Model('common/Users');
    	$rs = $m->checkUserPhone($userPhone,$this->getUserId());
        if($rs["status"]!=1){
          	exit(jsonReturn($rs['msg']));
        }
    	$phoneVerify = rand(1000,9999);
    	$tpl = WSTMsgTemplates('PHONE_USER_AUTH_NOTICE');
    	$rv['status'] = -1;
    	$rv['msg'] = '发送失败';
    	if( $tpl['tplContent']!='' && $tpl['status']=='1'){
    		$params = ['tpl'=>$tpl,'params'=>['code'=>$phoneVerify]];
    		$m =  Model('common/LogSms');
    		$rv = $m->sendSMS(0,$userPhone,$params,'PHONE_USER_AUTH_NOTICE',$phoneVerify);
    	}
    	if( $tpl['tplContent']!='' && $tpl['status']=='1'){
    		session('Reg_UserPhone',$userPhone);
    		session('RegCode_UserPhone',$phoneVerify);
    		session('RegCode_UserPhone_Time',time());
    	}
    	exit(json_encode($rv));
    }
    /**
	 * 获取亲人报备列表
	 */
	public function getAuthFamilyReportSelect(){
		$m = new FM();
		$authInfo = $m->getList(['userId'=>$this->getUserId()],'*');
		exit(jsonReturn('',1,$authInfo));
	}
   	/**
	 * 获取亲人报备信息
	 */
	public function getAuthFamilyReportInfo(){
		$m = new FM();
		$id = (int)input('post.id');
		$authInfo = $m->getInfo(['userId'=>$this->getUserId(),'id'=>$id],'*');
		exit(jsonReturn('',1,$authInfo));
	}

	
    /**
	 * 添加/编辑亲人报备信息
	 */
    public function setAuthFamilyReport(){
		$m = new FM();
		$data = input('post.');
		$validate =  \think\Loader::validate('Auth');
		if(!$validate->scene('report')->check($data)){
			exit(jsonReturn($validate->getError()));
		}
		$userId = $this->getUserId();
		$data['userId'] = $userId;
		if(!empty($data['id'])){//更新状态
			$id = $data['id'];
			unset($data['id']);
			$authInfo = $m->getInfo(['userId'=>$userId,'id'=>$id],'id');
			if(!$authInfo){
				exit(jsonReturn('未找到此信息'));
			}
			$isSuccess = $m->updateInfo(['id'=>$id],$data);
		}else{			
			$isSuccess = $m->insertInfo($data);
		}
		if($isSuccess){
			exit(jsonReturn('提交成功',1));	
		}else{
			exit(jsonReturn('操作失败,请重试'));	
		}
    }
    /**
	 * 获取亲人认证列表
	 */
	public function getAuthFamilyPersonalSelect(){
		$m = new FM();
		$m->setTable('auth_family_personal');
		$authInfo = $m->getSelect(['userId'=>$this->getUserId()],'*');
		exit(jsonReturn('',1,$authInfo));
	}
   	/**
	 * 获取亲人认证信息
	 */
	public function getAuthFamilyPersonalInfo(){
		$m = new FM();		
		$m->setTable('auth_family_personal');
		$id = (int)input('post.id');
		$authInfo = $m->getInfo(['userId'=>$this->getUserId(),'id'=>$id],'*');
		exit(jsonReturn('',1,$authInfo));
	}
	/**
	 * 获取亲人认证信息
	 */
	public function getAuthInfoByMobile(){
		$m = new M();	
		//$isPartner = (int)input('post.isPartner');
		// if(1 == $isPartner){//合作认证
		// 	$userPhone = session('partner_UserPhone');
		// 	$verify = session('partnerCode_UserPhone');
  		//  $startTime = (int)session('partner_UserPhone_Time');
		// }else{
			$userPhone = session('auth_UserPhone');
			$verify = session('authCode_UserPhone');
        	$startTime = (int)session('auth_UserPhone_Time');
		//}
		
		if(!$userPhone){
			exit(jsonReturn('操作超时,请重试!'));	
		}		
        if((time()-$startTime)>1200){
           	exit(jsonReturn('验证码已超过有效期,请重新发送!'));	
        }
    	$mobileCode = input('post.mobileCode');
        if($mobileCode=="" || $verify != $mobileCode){
        	exit(jsonReturn('短信验证码错误!'));	
        }
		session('auth_ok',1);
		$authInfo = $m->getAuthInfoByMobile($userPhone);
		exit(json_encode($authInfo));
	}
	/**
	 * 删除报备或认证信息
	 * @return [type] [description]
	 */
	public function delAuthFamily(){
		$m = new FM();		
		$payPwd = input("post.payPwd");
		if(md5($payPwd) != $this->user['payPwd']){
			exit(jsonReturn('操作密码错误'));	
		}
		$id = input("post.id");
		$isReport = (int)input('post.isReport');//0是亲人认证,1是亲人报备
		if(0 == $isReport){
			$m->setTable('auth_family_personal');
		}
		$rs = $m->updateInfo(['userId'=>$this->getUserId(),'id'=>$id],['dataFlag'=>-1]);
		if(false !== $rs){
			exit(jsonReturn('成功',1));
		}
		exit(jsonReturn('失败,请重试',1));
	}
	/**
     * 获取亲人验证码
     */
    public function getFamilyPhoneCode(){
    	if($this->user['authType'] == 2) exit(jsonReturn('没有权限!'));	
    	$userPhone = input("post.userPhone");
    	$rs = array();
    	if(!WSTIsPhone($userPhone)){
    		exit(jsonReturn("手机号格式不正确!"));
    	}
    	if($this->user['userPhone'] && $this->user['userPhone'] == $userPhone){
    		exit(jsonReturn("请输入实名认证的亲人手机号!"));
    	}
    	$m = Model('common/Users');
    	$rs = $m->checkUserPhone($userPhone,0,'loginName');
        if($rs["status"]==1){
          	exit(jsonReturn('手机号不存在'));
        }        
    	$rv['status'] = -1;
    	$rv['msg'] = '发送失败';
    	$phoneVerify = rand(1000,9999);
    	$tpl = WSTMsgTemplates('PHONE_USER_AUTH_FAMILY_VERFIY');
    	if( $tpl['tplContent']!='' && $tpl['status']=='1'){    		
    		$params = ['tpl'=>$tpl,'params'=>['name'=>$rs['loginName'],'code'=>$phoneVerify]];
    		$m =  Model('common/LogSms');
    		$rv = $m->sendSMS(0,$userPhone,$params,'PHONE_USER_AUTH_FAMILY_VERFIY',$phoneVerify);
    	}
    	if( $tpl['tplContent']!='' && $tpl['status']=='1'){
    		session('auth_UserPhone',$userPhone);
    		session('authCode_UserPhone',$phoneVerify);
    		session('auth_UserPhone_Time',time());
    	}
    	exit(json_encode($rv));
    }
    /**
	 * 添加/编辑亲人认证信息
	 */
	public function setAuthFamilyPersonal(){
    	if($this->user['authType'] == 2) exit(jsonReturn('没有权限!'));	
		$data = input('post.');

		$validate =  \think\Loader::validate('Auth');
		if(!$validate->scene('family')->check($data)){
			exit(jsonReturn($validate->getError()));
		}

		$id = isset($data['id']) ? $data['id'] : 0;
		if(!$id){
			$userPhone = session('auth_UserPhone');
			if(!$userPhone){
				exit(jsonReturn('操作超时,请重试!'));	
			}
			$auth_ok = session('auth_ok');
			if(empty($auth_ok)) exit(jsonReturn('操作超时,请重新再试!'));	
	    	

			$where['userPhone']=$userPhone;
			$userInfo = getUserInfo($where,'userId');
			if($userInfo){
				$data['familyId']=$userInfo['userId'];
				$am = new M();
				$familyInfo = $am->getInfo(['userId'=>$userInfo['userId'],'status'=>1],'householdName,householdIdCard');
				if(!$familyInfo){
					exit(jsonReturn('亲人认证账号必须为个人实名通过会员!'));
				}
				$data['familyName'] = $familyInfo['householdName'];
				$data['familyIdCard'] = $familyInfo['householdIdCard'];
			}else{
				exit(jsonReturn('未找到用户'));
			}
		}
		unset($data['id']);
		$userId = $this->getUserId();
		$data['userId'] = $userId;
		$m = new FM();
		$m->setTable('auth_family_personal');
		if(!$id && $m->getInfo(['familyId'=>$data['familyId'],'userId'=>$userId],'id')){
			exit(jsonReturn('此亲人已认证,请更换'));
		}
		if($id){//编辑
			$isSuccess = $m->updateInfo(['userId'=>$userId,'id'=>$id],$data);
		}else{//新增
			$isSuccess = $m->insertInfo($data);
		}

		if(false !== $isSuccess){
			session('auth_UserPhone',null);			
    		session('auth_ok',null);
			exit(jsonReturn('提交成功',1));
		}else{
			exit(jsonReturn('操作失败,请重试'));	
		}
	}
	/**
	 * 获取银行列表
	 */
	public function getBankNameList(){
		$bankList = Model('banks')->listQuery();
		exit(jsonReturn('',1,$bankList));
	}
	/**
	 * 获取会员银行列表
	 */
	public function getCompanyBankList(){
		$bankList = Model('CompanyBank')->getSelect(['userId'=>$this->getUserId()],'*');
		exit(jsonReturn('',1,$bankList));
	}
	/**
	 * 获取会员银行卡信息
	 */
	public function getCompanyBankInfo(){
		$id = (int)input('post.id/d');
		$bankInfo = Model('CompanyBank')->getInfo(['userId'=>$this->getUserId(),'id'=>$id],'id,bankName,accountName,bankNo');
		exit(jsonReturn('',1,$bankInfo));
	}
	/**
	 * 删行会员银行卡
	 */
	public function delCompanyBank(){		
    	if($this->user['authType'] != 2) exit(jsonReturn('没有权限!'));
		$id = (int)input('post.id/d');
		$payPwd = input("post.payPwd");
		if(md5($payPwd) != $this->user['payPwd']){
			exit(jsonReturn('操作密码错误'));
		}
		$rs = Model('CompanyBank')->updateInfo(['userId'=>$this->getUserId(),'id'=>$id],['dataFlag'=>-1]);
		if(false !== $rs){
			exit(jsonReturn('删除成功',1));
		}
		exit(jsonReturn('删除失败,请重试'));
	}
	/**
	 * 添加/编辑银行卡信息
	 */
    public function setBank(){
    	if($this->user['authType'] != 2) exit(jsonReturn('合作认证账号才可以添加银行卡'));
		$m = Model('CompanyBank');
		$data = input('post.');
		$validate =  \think\Loader::validate('Auth');
		if(!$validate->scene('bank')->check($data)){
			exit(jsonReturn($validate->getError()));
		}
		$id = isset($data['id']) ? $data['id'] : 0;
		$data['userId'] = $this->getUserId();
		if($id){//编辑
			$isSuccess = $m->updateInfo(['userId'=>$data['userId'],'id'=>$id],$data);
		}else{//新增
			$isSuccess = $m->insertInfo($data);
		}
		if(false !== $isSuccess){
			exit(jsonReturn('提交成功',1));	
		}else{
			exit(jsonReturn('操作失败,请重试'));	
		}
    }
    /**
     * 获取合作人验证码
     */
    public function getPartnerPhoneCode(){
    	if(2 != $this->user['authType'])exit(jsonReturn('个人认证不可添加合作人'));
    	$userPhone = input("post.userPhone");
    	$rs = array();
    	if(!WSTIsPhone($userPhone)){
    		exit(jsonReturn("手机号格式不正确!"));
    	}
    	if($this->user['userPhone'] && $this->user['userPhone'] == $userPhone){
    		exit(jsonReturn("请输入实名认证的手机号!"));
    	}
    	$m = Model('common/Users');
    	$rs = $m->checkUserPhone($userPhone,0,'loginName');
        if($rs["status"]==1){
          	exit(jsonReturn('手机号不存在'));
        }        
    	$rv['status'] = -1;
    	$rv['msg'] = '发送失败';
    	$phoneVerify = rand(1000,9999);
    	$tpl = WSTMsgTemplates('PHONE_USER_AUTH_PARTNER_VERFIY');
    	if( $tpl['tplContent']!='' && $tpl['status']=='1'){
    		$params = ['tpl'=>$tpl,'params'=>['name'=>$rs['loginName'],'code'=>$phoneVerify]];
    		$m =  Model('common/LogSms');
    		$rv = $m->sendSMS(0,$userPhone,$params,'PHONE_USER_AUTH_PARTNER_VERFIY',$phoneVerify);
    	}
    	if( $tpl['tplContent']!='' && $tpl['status']=='1'){
    		session('auth_UserPhone',$userPhone);
    		session('authCode_UserPhone',$phoneVerify);
    		session('auth_UserPhone_Time',time());
    	}
    	exit(json_encode($rv));
    }
    /**
	 * 添加/编辑合伙人认证信息
	 */
	public function setAuthPartner(){
		if(2 != $this->user['authType'])exit(jsonReturn('个人认证不可添加合作人'));	
		$data = input('post.');

		$validate =  \think\Loader::validate('Auth');
		if(!$validate->scene('partner')->check($data)){
			exit(jsonReturn($validate->getError()));
		}

		$userId = $this->getUserId();
		if(isset($data['id'])){
			$m->setTable('auth_company_partner');
			$info = $m->getInfo(['id'=>$data['id'],'dataFlag'=>1],'userId,partnerId');
			if(!$info || $info['userId'] != $userId){				
				exit(jsonReturn('没有权限!'));
			}
			$where['userId']=$info['partnerId'];
			$userInfo = getUserInfo($where,'userId,authType');
		}else{
			$userPhone = session('auth_UserPhone');
			if(!$userPhone){
				exit(jsonReturn('操作超时,请重试!'));	
			}
			$auth_ok = session('auth_ok');
			if(empty($auth_ok)) exit(jsonReturn('操作超时,请重新再试!'));	

			$where['userPhone']=$userPhone;
			$userInfo = getUserInfo($where,'userId,authType');
		}
		
		if($userInfo){
			$data['partnerId']=$userInfo['userId'];
			$am = new M();
			if(1 == $userInfo['authType']){
				$field = 'householdName uName,householdIdCard idCard';
				$uName = 'familyName';
				$idCard = 'familyIdCard';
			}elseif(2 == $userInfo['authType']){
				$am->setTable('auth_company');
				$field = 'trueName uName,idCard';
				$uName = 'uName';
				$idCard = 'idCard';
			}else{
				exit(jsonReturn('合作认证账号必须为实名通过会员'));
			}
			$authInfo = $am->getInfo(['userId'=>$userInfo['userId'],'status'=>1],$field);
			if(!$authInfo){
				exit(jsonReturn('合作认证账号必须为实名通过会员!'));
			}
			$data[$uName] = $authInfo['uName'];
			$data[$idCard] = $authInfo['idCard'];
		}else{
			exit(jsonReturn('未找到用户'));
		}
		$id = isset($data['id']) ? $data['id'] : 0;
		unset($data['id']);
		$data['userId'] = $userId;
		$m = new FM();
		$m->setTable('auth_company_partner');
		if(!$id && $m->getInfo(['partnerId'=>$data['partnerId'],'userId'=>$userId],'id')){
			exit(jsonReturn('此合作人已认证,请更换'));
		}
		if($id){//编辑
			$stakeSum = $m->getSum(['userId'=>$userId,'id'=>['<>',$id]],'stake');
			if(($stakeSum + $data['stake']) > 100){
				exit(jsonReturn('股份分配超出100%比例,当前最大修改比例'.(100-$stakeSum),1));
			}
			$isSuccess = $m->updateInfo(['userId'=>$userId,'id'=>$id],$data);
		}else{//新增
			$stakeSum = $m->getSum(['userId'=>$userId],'stake');
			if(($stakeSum + $data['stake']) > 100){
				exit(jsonReturn('股份分配超出100%比例,当前最大修改比例'.(100-$stakeSum),1));
			}
			$isSuccess = $m->insertInfo($data);
		}

		if(false !== $isSuccess){
			session('auth_UserPhone',null);
			session('auth_ok',null);
			exit(jsonReturn('提交成功',1));
		}else{
			exit(jsonReturn('操作失败,请重试'));	
		}
	}

}