<?php
namespace homecn\action;
use \model\user\users;
use \model\wx;

class userAction extends baseAction
{
    public function index()
    {
	   $this->mustLogin();
	   $users = new users();
	   $scoreList = $users->getScoreByUidList(['u_id' => $_SESSION['cnuser']['u_id']],['page' => 1,'pageSize' => 100]);
	   $_SESSION['cnuser']['u_score'] = $users->getScoreByUid($_SESSION['cnuser']['u_id']);

	   $info = $users->getUserByUid($_SESSION['cnuser']['u_id']);
	   $info['u_wx_info'] = json_decode($info['u_wx_info'], true);
	   \view::set('scoreList', $scoreList['list']);
	   \view::set('user', $info);
       \view::set('title', \mvc::$cfg['siteTitle']);
       \view::put();
    }

	public function unbindWx()
	{
		$this->mustLogin();
	    $users = new users();
		$res = $users->unbindWx($_SESSION['cnuser']['u_id']);
		echo json_encode($res);
	}


	public function bindWx()
	{
		$this->mustLogin();
		$wx = new wx();
		if(!empty($this->param['code']))
		{
			$WXUserArr = $wx->getUserByCode($this->param['app'], $this->param['code']);
			if(!empty($WXUserArr['unionid']))
			{
				$users = new users();
				$users->bindWx($_SESSION['cnuser']['u_id'], base64_encode(json_encode($WXUserArr)));
				Header("Location: ".\mvc::$cfg['SELF_URI'].'user/index');
				exit;
			}
		}
		$backUrl = \mvc::$cfg['SELF_URI'].'user/bindWx';
		if($this->isWxClient)
			$res = $wx->getWxUserUrl(['app'=>'gzh', 'backUrl'=>$backUrl.'?app=gzh', 'scope'=>'snsapi_userinfo']);
		else
			$res = $wx->getWxUserUrl(['app'=>'gzh_app', 'backUrl'=>$backUrl.'?app=gzh_app', 'scope'=>'snsapi_login']);
		Header("Location: ".$res['url']);
	}
	

	public function loginByWx()
	{
		$wx = new wx();
		if(!empty($this->param['code']))
		{
			$WXUserArr = $wx->getUserByCode($this->param['app'], $this->param['code']);
			if(!empty($WXUserArr['unionid']))
			{
				$users = new users();
				$row = $users->loginByAny('weixin', ['unionid'=>$WXUserArr['unionid']]);
				if($this->loginSession($row)){
					 header('Location:'.\mvc::$cfg['SELF_URI'].'user/index');
					 exit();
				}elseif(isset($row['msg'])) {
                 $_SESSION['loginerror'] = $row['msg'];//密码错误
				}elseif(isset($row['u_status'])){
					 $_SESSION['loginerror'] = '帐号正在审核中';
					 header('Location:'.\mvc::$cfg['SELF_URI'].'user/login?loginerror='.$loginerror);
					 exit();
				}else{
					Header("Location: ".\mvc::$cfg['SELF_URI'].'user/register?udata='.base64_encode(json_encode($WXUserArr)));
					exit();
				}
			}
		}
		$backUrl = \mvc::$cfg['SELF_URI'].'user/loginByWx';
		if($this->isWxClient)
			$res = $wx->getWxUserUrl(['app'=>'gzh', 'backUrl'=>$backUrl.'?app=gzh', 'scope'=>'snsapi_userinfo']);
		else
			$res = $wx->getWxUserUrl(['app'=>'gzh_app', 'backUrl'=>$backUrl.'?app=gzh_app', 'scope'=>'snsapi_login']);
		Header("Location: ".$res['url']);
		
	}

    public function login()
    {
	   if($this->isLogin()) {
			header('Location:'.\mvc::$cfg['SELF_URI']);
			exit();
	   }
	   $udataArr = [];
	   if(!empty($this->param['udata']))
	   {
		   $udataArr = json_decode(base64_decode($this->param['udata']), true);
	   }
	   if(isset($_SERVER['HTTP_REFERER'])) {
			$referrer = filter_var($_SERVER['HTTP_REFERER'], FILTER_VALIDATE_URL);
			$_SESSION['login_back_url'] =  $referrer ? $referrer : '';
		}
       \view::set('udataArr', $udataArr);
       \view::set('udata', $this->param['udata']);
       \view::set('loginerror', $_SESSION['loginerror']);
	   unset($_SESSION['loginerror']);
       \view::set('title', \mvc::$cfg['siteTitle']);
       \view::put();
    }

    public function addUserBehavior()
    {
        /*$user = new users();
        $time = time();
        if(isset($this->param['token']) && $this->param['token'] > 0){
            $updateData = [
                'new_code' => $this->param['p_num_new'],
                'part_category' => $this->param['part_name'],
                'is_car' => $this->param['is_car']
            ];
            $user->updateUserBehaviorLog($updateData,$this->param['token']);
        }else{
            $temp = explode('/',$this->param['content']);
            if(count($temp) == 2){
                $temp = $temp['1'];
            }else{
                if($this->param['part_name']){
                    $temp = $this->param['part_name'];
                }else{
                    $temp = '';
                }
            }
            $data = [
                'date' => date('Y-m-d',$time),
                'time' => date('H:i:s',$time),
                'u_id' => $_SESSION['cnuser']['u_id'],
                'mobile' => $_SESSION['cnuser']['u_mb'],
                'interface' => $this->param['interface'],
                'content' => $this->param['content'],
                'remark' => $this->param['remark'],
                'new_code' => isset($this->param['p_num_new']) ? $this->param['p_num_new'] : '',
                'part_category' => $temp,
                'is_car' => isset($this->param['is_car']) ? $this->param['is_car'] : '',
                'session_id' => session_id(),
            ];
            $id = $user->addUserBehaviorLog($data);
            ob_clean();
            echo json_encode([
                'status'=> 1,
                'data' => [
                    'id' => $id
                ]
            ]);
        }*/
		echo json_encode([
			'status'=> 1,
			'data' => [
				'id' => 0
			]
		]);
    }

    public function register()
    {
	   $udataArr = [];
	   if(!empty($this->param['udata']))
	   {
		   $udataArr = json_decode(base64_decode($this->param['udata']), true);
	   }
       \view::set('udataArr', $udataArr);
       \view::set('udata', $this->param['udata']);
       \view::set('title', \mvc::$cfg['siteTitle']);
       \view::put();
    }

    public function forget()
    {
       \view::set('title', \mvc::$cfg['siteTitle']);
       \view::put();
    }

    public function agreement()
    {
       \view::set('title', \mvc::$cfg['siteTitle']);
       \view::put();
    }
    public function signout()
    {
        $_SESSION['cnuser'] = [];
        header('Location:'.\mvc::$cfg['SELF_URI'].'user/login');
        exit();
    }

    public function loginPost()
    {
		
		$loginerror = '';
		$goto = \mvc::$cfg['SELF_URI'].'user/login';
        
        if(!empty($this->param)){
            foreach($this->param as $k=>$v){
                $this->param[$k] = addslashes($v);
            }
            $users = new users();
            $row = $users->loginByAny('pass', ['mb'=>$this->param['mb'], 'pass'=>$this->param['password'], 'u_wx_info'=>$this->param['u_wx_info']]);
            if($this->loginSession($row)){
                if($_SESSION['login_back_url']!='') $goto = $_SESSION['login_back_url'];
				header('Location:'.$goto);
				exit();
            }elseif(isset($row['u_status'])){
                $_SESSION['loginerror'] = '帐号正在审核中';
            }elseif(isset($row['msg'])) {
                 $_SESSION['loginerror'] = $row['msg'];//密码错误
            }else{
                if(strlen($this->param['mb'])!=11 && !is_numeric($this->param['mb'])){
                  $_SESSION['loginerror'] = '请输入一个正确的手机号';
                }else{
                    $_SESSION['loginerror'] = '用户名或者密码错误';
                }
            }
        }
		$_SESSION['login_back_url']='';
        header('Location:'.$goto);
        exit();
    }

	function loginSession($row)
	{
		if(!empty($row['u_id']) && $row['u_status'] == 1)
		{
			$_SESSION['loginerror'] = '';
			$_SESSION['cnuser'] = $row;
			$users = new users();
			$users->updateUserScore(['us_type' => 'SCORE_LOGIN', 'us_u_id' => $row['u_id'], 'us_ue_id' => '', 'us_remark' => '用户登录',],'+',date('Y-m-d',time()));
			return true;
		}
		return false;
	}

    public function registerCheck()
    {
        $mb = $this->param['mb'];
        $isNohas = $this->param['isNohas'];
        $error = '';
        $status = true;
        if($_SESSION['tncode_check']!='ok'){
                $error = '验证码不正确';
                $status = false;
        }else{
            if(strlen($mb)!=11 && !is_numeric($mb)){
                $error = '手机号格式不正确';
                $status = false;
            }elseif($isNohas!=1){
                $users = new users();
                $row = $users->getRowByMb($mb);
                if(!empty($row)){
                    $error = '此手机号已被注册';
                    $status = false;
                }
            }
        }
        $data = ['status' => $status ,'code' => 0,'data' => $error];
        if($status){
            $data = $this->SendSmsCode($mb);
        }
        ob_clean();
        echo json_encode($data, JSON_UNESCAPED_UNICODE);
    }

    public function SendSmsCode($mb)
    {
        $users = new users();
        include(\mvc::$cfg['mvcDir'].'/lib/aliyun-dysms-php-sdk/api_demo/SmsDemo.php');
        $error = '';
        $status = true;
        $code = mt_rand(100000,999999);
        $msgArr = [
            'sms_to_mobile'=> $mb,	
            'sms_text'=>'{"code":"'.$code.'"}',	
            'sms_sign'=> \mvc::$cfg['SMS']['ali']['barcode_remaining']['sms_sign'],
            'sms_tpl'=> \mvc::$cfg['SMS']['ali']['barcode_remaining']['sms_tpl']
        ];
        $response = \SmsDemo::sendSms($msgArr);
        if($response->Message != 'OK')
        {
            $status = false;
            $error= '对不起，短信发送失败，请重试, '.$response->Message;
        }else{
            $users->addSmsCode($mb, $code);
        }
        $data = ['status' => $status ,'code' => 0,'data' => $error];
        return $data;
    }
    
    public function registerPost()
    {
        $users = new users();
        foreach($this->param as $k=>$v){
            $this->param[$k] = addslashes($v);
        }
        $mb = $this->param['mb'];
        $rowCode = $users->getSmsCode($mb);
        $users->delSmsCode($mb);
        $status = 'ok';
        if(
               (strlen($mb)!=11 && !is_numeric($mb)) 
            || (strlen($this->param['checkcode'])!=6 && !is_numeric($mb)) 
            || (strlen($this->param['password'])<8) 
            || (strlen($this->param['password'])>20) 
            || (strlen($this->param['truename'])>20) 
            || (strlen($this->param['sex'])>1) 
            || (strlen($this->param['company'])>100) 
            || (strlen($this->param['emaill'])>200) 
            || (strlen($this->param['wx'])>100) 
            || (strlen($this->param['address'])>200) 
         ){
            $status = 'error';
        }else if($this->param['checkcode']!==$rowCode['sms_code']){
            $status = 'code';
        }else{
            $row = $users->getRowByMb($mb);
            if(!empty($row)){
                $status = 'has';
            }
        }
        if($status=='ok'){
            $time = date('Y-m-d h:i:s', time());
            $data = [
                'u_mb'=>$this->param['mb'],
                'u_password'=> $users->pass($this->param['password']),
                'u_name'=>$this->param['truename'],
                'u_sex'=>$this->param['sex'],
                'u_email'=>$this->param['email'],
                'u_wx'=>$this->param['wx'],
                'u_company'=>$this->param['company'],
                'u_address'=>$this->param['address'],
                'u_status' => 1,
                'u_create_time'=> $time,
                'u_update_time'=>$time,
				'u_wx_info'=>$this->param['wxinfo'],
				'u_from'=>'cn'
            ];
            try{
                $users->addUser($data);
            } catch (Exception $e) {
                $status = 'error';
            }   
        }
        header('Location:'.\mvc::$cfg['SELF_URI'].'user/registerPostInfo?status='.$status);
        exit();
    }

    public function forgetPost(){
        $users = new users();
        foreach($this->param as $k=>$v){
            $this->param[$k] = addslashes($v);
        }
        $mb = $this->param['mb'];
        $rowCode = $users->getSmsCode($mb);
        $users->delSmsCode($mb);
        $status = 'ok_forget';
        // if(
        //        (strlen($mb)!=11 && !is_numeric($mb)) 
        //     || (strlen($this->param['checkcode'])!=6 && !is_numeric($mb)) 
        //     || (strlen($this->param['password'])<8) 
        //     || (strlen($this->param['password'])>20) 
        //  ){
        //     $status = 'error';
        // }else if($this->param['checkcode']!==$rowCode['sms_code']){
        //     $status = 'code';
        // }
        $users->updatePass($mb, $users->pass($this->param['password']));
        if($status=='ok_forget'){
            try{
               
            } catch (Exception $e) {
                $status = 'error';
            }   
        }
        header('Location:'.\mvc::$cfg['SELF_URI'].'user/registerPostInfo?status='.$status);
        exit();
    }

    public function registerPostInfo()
    {
        \view::set('title', \mvc::$cfg['siteTitle']);
        \view::set('status', $_GET['status']);
       \view::put();
    }
    

    public function checkoutPost()
    {
        $this->mustLogin();
        foreach($this->param as $k=>$v){
            $this->param[$k] = addslashes($v);
        }
        $this->param['prolist'] = stripslashes($this->param['prolist']);
        $time = date('Y-m-d h:i:s', time());
        $userinfo = [
          'o_u_id'=> $_SESSION['cnuser']['u_id'],
          'o_u_mb'=> $this->param['mb'],
          'o_u_name'=> $this->param['truename'],
          'o_u_company'=> $this->param['company'],
          'o_u_address'=> $this->param['address'],
          'o_u_sex'=> $this->param['sex'],
          'o_u_email'=> $this->param['email'],
          'o_u_wx'=> $this->param['wx'],
          'remark'=> $this->param['remark']
        ];
        $data = [
          'o_u_id'=> $_SESSION['cnuser']['u_id'],
          'o_u_mb'=> $this->param['mb'],
          'o_u_name'=> $this->param['truename'],
          'o_u_address'=> $this->param['address'],
          'o_u_company'=> $this->param['company'],
          'o_user_info'=> json_encode($userinfo),
          'o_product_info'=> $this->param['prolist'],
          'o_create_time'=> $time,
          'o_update_time'=> $time
        ];
        if($this->param['mb']!=''){
            $users = new users();
            $users->addOrder($data);
            header('Location:'.\mvc::$cfg['SELF_URI'].'user/checkoutPostInfo');
        }
        exit();
    }

    public function checkoutPostInfo()
    {
        \view::set('title', \mvc::$cfg['siteTitle']);
        \view::set('status', $_GET['status']);
       \view::put();
    }

    public function readNewPro()
    {
        $this->mustLogin();
		$users = new users();
        $result = $users->updateUserScore(['us_type' => 'SCORE_READ_NEW_PRODCUT', 'us_u_id' => $_SESSION['cnuser']['u_id'], 'us_ue_id' => '', 'us_remark' => '浏览新产品',],'+',date('Y-m-d',time()));
    }


	public function getHistory()
    {
        $this->mustLogin();
		$users = new users();
        $result = $users->getHistory($_SESSION['cnuser']['u_id'], $this->param['type']);
		$data = ['status' =>true,'data'=>$result,'code'=>0];
		$this->exitToJson($data);
    }

    public function collect()
    {   
        if(!$this->isLogin()){
            $data = ['status' =>false,'data'=>'请先登录','code'=>-1];
            $this->exitToJson($data);
        } 
        $req = \mvc::$req; 
        if(!$req['cate_id']) exitJson(0, '参数错误');
        $users = new users();
        $result = $users->collect($_SESSION['cnuser']['u_id'], $req['cate_id']);
        $data = ['status' =>true,'data'=>$result,'code'=>0];
        $this->exitToJson($data);
    }

}