<?php
namespace Mobile\Model;
use Think\Model;
use User\Api\SuserApi;

class UserModel extends Model{
	
	protected $_validate = array(
		// 验证用户名
		array('account', '6,30', -1, self::EXISTS_VALIDATE, 'length'), //用户名长度不合法
		array('account', '', -3, self::EXISTS_VALIDATE, 'unique'), //用户名被占用
		// 验证密码
		array('password', '6,30', -4, self::EXISTS_VALIDATE, 'length'), //密码长度不合法
	    // 验证邮箱
		array('email', 'email', -5, self::EXISTS_VALIDATE), //邮箱格式不正确
		//验证手机号码
		array('mobile', '/^13[\d]{9}$|^14[0-9][\d]{8}|^15[0-9][\d]{8}$|^18[0-9][\d]{8}$/', -9, self::MUST_VALIDATE,'regex',2), //手机格式不正确 TODO:
	);

	/* 用户模型自动完成 */
	protected $_auto = array(
		array('password', 'think_ucenter_md5', self::MODEL_BOTH, 'function', UC_AUTH_KEY),
	);
	
	
	/**
     * 构造函数
     * @param string $name 模型名称
     * @param string $tablePrefix 表前缀
     * @param mixed $connection 数据库连接信息
     */
    public function __construct($name = '', $tablePrefix = '', $connection = '') {
        /* 设置默认的表前缀 */
        $this->tablePrefix ='tab_';
        /* 执行构造方法 */
        parent::__construct($name, $tablePrefix, $connection);
    }
	
	/**
	*	验证用户名
	*/
	public function checkUsername($username){
		$map = array();
		$map['account'] = $username;
		$user = $this->where($map)->find();
		return $user;
	}	
	
	
	/**
	*  用户注册
	*/
	public function register($username, $password, $email, $realname, $idcard){
		$data = array(
			'account' => $username,
			'password' => $password,
			'flatcoin' => 0,
			'viplevel' => 0,
			'addup'	=> 0,
			'lock' => 1,
			'createdate' => date("Y-m-d H:i:s",time()),
			'email' => $email,
			'realname' => $realname,
			'idcard' => $idcard,
			'registerip' => $this->getIPaddress(),
		);
		// 添加用户
		if($this->create($data)){
			$uid = $this->add();
			return $uid ? $uid : 0; //0-未知错误,大于0-注册成功
		} else {
			return $this->getError();
		}
	}
	/**
	 * 获取用户信息
	 * @param $account
	 * @param array $filed
	 * @return mixed
	 * author: xmy 280564871@qq.com
	 */
	public function getUserByAccount($account,$filed=['*']){
		$map['account'] = $account;
		$data = $this->field($filed)->where($map)->find();
		return $data;
	}

	/**
	 * 修改密码
	 * @param $phone
	 * @param $old_pwd  旧密码
	 * @param $new_pwd  新密码
	 * @return bool
	 * author: xmy 280564871@qq.com
	 */
	public function changePwd($account, $old_pwd, $new_pwd)
	{
		//修改UC密码
		$result = $this->changeUcPwd($account,$old_pwd,$new_pwd,0);
		if(!$result){
			return false;
		}
		$user = $this->getUserByAccount($account);
		if (!empty($user) && think_psw_md5($old_pwd, UC_AUTH_KEY) === $user['password'])
		{
			$user['password'] = think_psw_md5($new_pwd, UC_AUTH_KEY);
			$result = $this->save($user);
		}else{
			$result = -1;
		}
		return $result;
	}

	/**
	 * 修改UC密码
	 * @param $account
	 * @param string $old_pwd   旧密码
	 * @param $new_pwd          新密码
	 * @param $type             0 修改密码 1 忘记密码
	 * @return bool
	 * author: xmy 280564871@qq.com
	 */
	private function changeUcPwd($account,$old_pwd="",$new_pwd,$type){

		//修改UC密码
		if(C('UC_SET') == 1){
			$uc = new Ucservice();
			$data_uc = $uc->get_uc($account);
			if (is_array($data_uc)) {
				$result = $uc->uc_edit($account, $old_pwd, $new_pwd,'',$type);
				if($result < 0){
					return false;
				}
				return true;
			}else{
				return true;
			}
		}else{
			return true;
		}
	}

	
	
	
	function getIPaddress(){ 
		$ip=false; 
		if(!empty($_SERVER['HTTP_CLIENT_IP'])){ 
			$ip=$_SERVER['HTTP_CLIENT_IP']; 
		}
		if(!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){ 
			$ips=explode (', ', $_SERVER['HTTP_X_FORWARDED_FOR']); 
			if($ip){ array_unshift($ips, $ip); $ip=FALSE; }
			for ($i=0; $i < count($ips); $i++){
				if(!eregi ('^(10│172.16│192.168).', $ips[$i])){
					$ip=$ips[$i];
					break;
				}
			}
		}
		return ($ip ? $ip : $_SERVER['REMOTE_ADDR']); 
	}
	

	/**
	*  用户登录
	*/
	public function login($uid){
        $user = $this->field(true)->find($uid);
        //if(!$user || 1 != $user['status']) {
		if (!$user && 1 != $user['lock']) {
            $this->error = '用户不存在或已被禁用!'; //应用级别禁用
            return false;
        }
        $this->autoLogin($user);
		return true;
    }
	
	/**
	* 验证邮箱
	*/
	public function checkEmail($email) {
		$user = $this->where('email="'.$email.'"')->find();
		return $user;
	}
	
	/**
	* 修改密码
	*/
	public function update($uid,$password) {
		$data = array(
            'playerid'        => $uid,
            'password'		  => think_ucenter_md5($password, UC_AUTH_KEY),			
        );
		return $this->save($data);   
	}
	
	/**
	 * 获取用户信息
	 * @param $user_id
	 * @param array $field
	 * @return mixed
	 * author: xmy 280564871@qq.com
	 */
	public function getUserInfo($account,$field=['id','account','nickname','promote_id','phone','balance','head_img','sex','point','idcard','real_name','age_status']){
		//根据手机号或者账号查找信息(WAP找回密码需要根据手机号查找)
		$map['account'] = $account;
		$map['phone']   = $account;
		$map['_logic']  = 'OR';
		$data = $this->field($field)->where($map)->find();
		if (empty($data)){
			return $data;
		}

		if(is_numeric($data['head_img'])){
			$head_img = get_img_url($data['head_img']);
			$data['head_img'] = $head_img == false?"":$head_img;
		}
		
        if ($data['age_status']==0 && !empty($data['idcard']) && !empty($data['real_name'])){
            $data['age_status'] = 4;
        }
		return $data;
	}
	
	/**
	* 退出
	*/
    public function logout(){
        $member = new SuserApi;
				
				$member->logout();
    }
		
		public function getLoginInfo() {
			
			$member = new SuserApi;
			
			return $member->login_info();
		}
	
	/**
	* 检测用户是否已登录
	*/
	public function isLogin() {
		$users = $this->getLoginInfo();
		if(is_array($users) && !empty($users['username'])) {
			return $users;
		}else {
			return false;
		}
	}
	
	public function updateInfo($uid,$info='',$type) {
		$data['playerid'] = $uid;
		if('email'==$type) {
			if (preg_match("/^([0-9A-Za-z\\-_\\.]+)@([0-9a-z]+\\.[a-z]{2,3}(\\.[a-z]{2})?)$/i",$info)) {
				$data['email']=$info;
				$type = 1;
			} else
				$type = -5;
		}
		if ('phone'==$type) {
			if (preg_match("/^13[0-9]{1}[0-9]{8}$|15[0189]{1}[0-9]{8}$|189[0-9]{8}$/",$info)) {
				$data['phone']=$info;	
				$type = 1;
			}	else 
				$type = -9;
		}
		if ($type>0) {
			$this->save($data);
			return true;
		} else {
			return $type;
		}		
	}
	
	
	/**
	*	密码
	*/
	public function checkPwd($username,$password) {
		$account['account']=$username;
		$user = $this->where($account)->find();
		if(is_array($user)){
			if(think_ucenter_md5($password, UC_AUTH_KEY) === $user['password']){
				return $user['playerid']; //登录成功,返回用户ID
			} else {
				return -2; //密码错误
			}
		} else {
			return -1; //用户不存在或被禁用
		}
	}

	 /**
     * 自动登录用户
     */
    private function autoLogin($user){
		// 更新登录信息
		$data = array(
            'playerid'        => $user['playerid'],
            'addup'           => array('exp', '`addup`+1'),
            'lastlogintime' => date("Y-m-d H:i:s",time()),
            'lastloginip'   => $this->getIPaddress(),
        );
        $this->save($data);
		
		// 设置session
        $auth = array(
            'uid'             => $user['playerid'],
            'username'        => $user['account'],
			'flatcoin'		  => empty($user['flatcoin'])?0:$user['flatcoin'],
			'status'		  => $user['lock'],
			'logintime'		  => $user['lastlogintime'],
        );
        session('user_auth', $auth);
        session('user_auth_sign', data_auth_sign($auth));
		cookie('user_auth',$auth,3600);
    }
		
		/**
		 * 添加支付宝
		 * @author 鹿文学
		 */
		public function saveAlipay() {
			
			$alipay = $_POST['alipay'];
			$alipay_real_name = $_POST['alipay_real_name'];
			
			if(empty($alipay)) {return ['status'=>0,'info'=>'支付宝不能为空'];}
			if(empty($alipay_real_name)) {return ['status'=>0,'info'=>'真实姓名不能为空'];}
			if(!preg_match('/^[\x{4e00}-\x{9fa5}]{2,}$/u',$alipay_real_name)) {return ['status'=>0,'info'=>'真实姓名必须是大于2位的汉字'];}
			
			$user = $this->getLoginInfo();
			
			$data = array('alipay'=>$alipay,'alipay_real_name'=>$alipay_real_name);
			
			$res = $this->where(['id'=>$user['user_id']])->save($data);
			
			if ($res) {
				return ['status'=>1,'info'=>'支付宝添加成功'];
			} else {
				return ['status'=>1,'info'=>'支付宝添加成功'];
			}
			
		}
		
		/**
		 * 获取支付宝信息
		 */
		public function getAlipay() {
			
			$user = $this->getLoginInfo();
			
			return $this->field('id,alipay,alipay_real_name')->where(['id'=>$user['user_id']])->find();
			
		}
	
	
		public function useing_record($p=1) {
			
			$page = intval($p);
      $page = $page ? $page : 1; //默认显示第一页数据
			
			$row = 10;
			
			$spend = M('Spend','tab_');
			$deposit = M('Deposit','tab_');
			$bind = M('BindRecharge','tab_');
			
			$user = $this->getLoginInfo();
			if(is_array($user)) {
				$map['pay_status'] = 1;			
				$map['user_id'] = $user['user_id'];		
				$bindids = $bind->field('GROUP_CONCAT(id) as ids')->where($map)->group('user_id')->select();
				$map['pay_way'] = array('gt',0);
				$depositids = $deposit->field('GROUP_CONCAT(id) as ids')->where($map)->group('user_id')->select();
				$spendids = $spend->field('GROUP_CONCAT(id) as ids')->where($map)->group('user_id')->select();
			
				$ids='';
				if(!empty($bindids[0]['ids'])){ $bids = $bindids[0]['ids']; $ids .= ','.$bids;$bmap['b.id'] = array('in',$bids);}
				if(!empty($depositids[0]['ids'])){$dids = $depositids[0]['ids']; $ids .= ','.$dids;$dmap['d.id'] = array('in',$dids);}
				if(!empty($spendids[0]['ids'])){$sids = $spendids[0]['ids']; $ids .= ','.$sids;$smap['s.id'] = array('in',$sids);}
				if(!empty($ids)) {
					$count = count(explode(',',substr($ids,1)));
				
					if(!empty($smap)) {
						empty($bmap) || $bind_data = $bind->alias('b')->field('b.id,b.amount as pay_amount,FROM_UNIXTIME(b.create_time,"%Y-%m-%d %H:%i:%s") as pay_time,b.game_id,b.game_name,b.zhekou')->where($bmap)->select(false);
						empty($dmap) || $deposit_data = $deposit->alias('d')->field('d.id,d.pay_amount,FROM_UNIXTIME(d.create_time,"%Y-%m-%d %H:%i:%s") as pay_time,if(d.user_id,0,0) as game_id,if(d.user_account,"","") as game_name,IF (d.user_id, -1, -1) as zhekou')->where($dmap)->select(false);
						$sql = $spend->alias('s')->field('s.id,s.pay_amount,FROM_UNIXTIME(s.pay_time,"%Y-%m-%d %H:%i:%s") as pay_time,s.game_id,s.game_name,IF (s.user_id, -1, -1) as zhekou')
							->union($bind_data)	
							->union($deposit_data)			
							->where($smap)->select(false);
						$lists = $spend->table('('.$sql.') as a')->page($page,$row)->select();
					} elseif(!empty($dmap)) {
						empty($bmap) || $bind_data = $bind->alias('b')->field('b.id,b.amount as pay_amount,FROM_UNIXTIME(b.create_time,"%Y-%m-%d %H:%i:%s") as pay_time,b.game_id,b.game_name,b.zhekou')->where($bmap)->select(false);
						$sql = $deposit->alias('d')->field('d.id,d.pay_amount,FROM_UNIXTIME(d.create_time,"%Y-%m-%d %H:%i:%s") as pay_time,if(d.user_id,0,0) as game_id,if(d.user_account,"","") as game_name,IF (d.user_id, -1, -1) as zhekou')
							->union($bind_data)		
							->where($dmap)->select(false);
						$lists = $spend->table('('.$sql.') as a')->page($page,$row)->select();
					}	elseif(!empty($bmap)) {
						$sql = $bind->alias('b')->field('b.id,b.amount as pay_amount,FROM_UNIXTIME(b.create_time,"%Y-%m-%d %H:%i:%s") as pay_time,b.game_id,b.game_name,b.zhekou')->where($bmap)->select();
						$lists = $spend->table('('.$sql.') as a')->page($page,$row)->select();
					}
					
				}
			}
			if(is_array($lists)) {
				$data['lists'] = $lists;$data['status']=1;
				if($count > $row){
				$data['total'] = ceil($count/$row);
				} else {
					$data['total']=1;
				}
			} else {
				$data['lists']='';$data['total'] = 1;$data['status'] = 0;
			}
			$data['current'] = $page;
			
			return $data;
			
		}
		
		/**
		 * 规则显示与否
		 * @param  integer  $type   类型 0:表示买家  1:表示卖家
		 * @return  array 
		 * @author   鹿文学
		 */
		public function set_rule_status($type=0) {
			
			if(is_numeric($type) && ($type == 1 || $type == 0)) {
				$user = $this->getLoginInfo();
				if(is_array($user)) {
					$rule = $_POST['rule'];
					if($type == 1){$data['seller_rule']=$rule;}else{$data['buyer_rule']=$rule;}
					$res = $this->where(['id'=>$user['user_id']])->save($data);
					if($res) {
						return ['status'=>1,'info'=>'已记住'];
					} else {
						return ['status'=>0,'info'=>'更改失败'];
					}
				} else {
					return ['status'=>0,'info'=>'未登录'];
				}
			} else {
				return ['status'=>0,'info'=>'参数错误'];
				
			}
		}
		
		/**
		 * 获取规则显示与否
		 * @param  integer  $type   类型 0:表示买家  1:表示卖家
		 * @return  array 
		 * @author   鹿文学
		 */
		public function get_rule_status($type=0) {
			if(is_numeric($type) && ($type == 1 || $type == 0)) {
				$user = $this->getLoginInfo();
				if(is_array($user)) {
					if($type == 1){$fields = 'seller_rule';}else{$fields = 'buyer_rule';}
					$data = $this->field($fields)->where(['id'=>$user['user_id']])->find();
					return $data[$fields]?$data[$fields]:0;					
				} else {
					return 0;
				}
			} else {
				return 0;
			}
		}
		
		
		/**
		 * 获取小号信息
		 * @param  integer  $id  小号编号
		 * @return  array 
		 * @author   鹿文学
		 */
		public function get_small_info($id=0) {
			
			$data = $this->field('DATEDIFF(CURDATE(),FROM_UNIXTIME(register_time,"%Y-%m-%d")) as day,cumulative as accumulation')
			
			->where(['id'=>$id])->find();
			
			return $data;
			
		}
		
		/**
		 * 获取金币数额
		 * @return  integer 
		 * @author   鹿文学
		 */
		public function get_gold_coin() {
			
			$user = $this->getLoginInfo();
			
			$gold_coin = $this->field('gold_coin')->where(['id'=>$user['user_id']])->find();
			
			return $gold_coin['gold_coin'];
		}
		
		
		/**
		 * 获取金币相关信息
		 * @return  array 
		 * @author   鹿文学
		 */
		public function get_info_about_gold() {
			
			$user = $this->getLoginInfo();
			
			$gold_coin = $this->field('id,account,gold_coin,alipay,alipay_real_name')->where(['id'=>$user['user_id']])->find();
			
			return $gold_coin;
		}
		
		public function get_phone() {
			$user = $this->getLoginInfo();
			$data = $this->field('account,phone')->where(['id'=>$user['user_id']])->find();
			if(preg_match('/^1[3456789][0-9]{9}$/u',$data['account'])) {
				return $data['account'];
			} elseif (!empty($data['phone'])) {
				return $data['phone'];
			} else {
				return '';
			}
		}
		
		
		/**
		 * 获取小号列表通过游戏
		 * @param  integer  $game_id   游戏编号
		 * @return  array 
		 * @author   鹿文学
		 */
		public function get_small_list_by_game($game_id=0) {
			if(is_numeric($game_id) && $game_id > 0) {

				$lists = $this->get_small_list_on_shop($game_id);
				$spend = $this->get_small_list_on_self($game_id);
				
				if(!is_array($lists)) {$lists = array();}
				if(!is_array($spend)) {$spend = array();}
				
				return array_merge($lists,$spend);
				
			} else {
				return '';
			}
		}
		
		/**
		 * 获取自己购买的小号列表
		 * @param  integer  $game_id   游戏编号
		 * @return  array 
		 * @author   鹿文学
		 */
		public function get_small_list_on_shop($game_id=0) {
			if(is_numeric($game_id) && $game_id > 0) {
				$user = D('User')->getLoginInfo();
				
				$lists = $this->alias('u')->field('u.id as small_id,u.account as small_account,u.cumulative')
						->join('tab_merchandise as m on (m.small_id=u.id and m.status=1) ')
						->where(['m.game_id'=>$game_id,'u.lock_status'=>1,'u.puid'=>$user['user_id'],'source_puid'=>array('gt',0),'source_time'=>array('gt',0)])->select();
				
				return $lists;
			} else {
				return '';
			}
		}
		
		
		/**
		 * 获取自己创建的且充过值的小号列表
		 * @param  integer  $game_id   游戏编号
		 * @return  array 
		 * @author   鹿文学
		 */
		public function get_small_list_on_self($game_id=0) {
			if(is_numeric($game_id) && $game_id > 0) {
				$user = D('User')->getLoginInfo();
				
				$lists = $this->alias('u')->field('u.id as small_id,u.account as small_account,u.cumulative')
						->join('tab_spend as s on(u.id=s.small_id and s.pay_status=1) ')
						->where(['s.game_id'=>$game_id,'u.lock_status'=>1,'u.puid'=>$user['user_id'],'u.source_puid'=>0,'u.source_time'=>0])->group('s.small_id')->select();
				
				return $lists;
			} else {
				return '';
			}
		}
		
		
		/**
		 * 获取自己创建的且充过值的小号列表
		 * @param  string  $fields   字段列表
		 * @return  array 
		 * @author   鹿文学
		 */
		public function getInfo($fields=true) {
			
			$session = $this->getLoginInfo();
			
			$data = $this->field($field)->where(['id'=>$session['user_id']])->find();
			
			if (empty($data)){
				return $data;
			}
			
			if(is_numeric($data['head_img'])){
				$head_img = get_img_url($data['head_img']);
				$data['head_img'] = $head_img == false?"":$head_img;
			}
		
			if ($data['age_status']==0 && !empty($data['idcard']) && !empty($data['real_name'])){
					$data['age_status'] = 4;
			}
			
			return $data;
			
		}

}