<?php
/** 文章模型
 * @Copyright (C) 2016 汉潮 All rights reserved.
 * @License http://www.hanchao9999.com
 * @Author xiaoq <570035208@qq.com>
 */

namespace Common\Model;

use Think\Model;

class LoginModel extends Model{
    protected $tableName = 'member';
	public function _initialize(){
		parent::_initialize ();
    }
    /* 用户模型自动完成 */
    protected $_auto = array(
        array('reg_ip', 'get_client_ip', self::MODEL_INSERT, 'function', 1),
        array('reg_time', NOW_TIME, self::MODEL_INSERT),
        array('last_ip', 0, self::MODEL_INSERT),
        array('last_login', 0, self::MODEL_INSERT),
        array('status', 1, self::MODEL_INSERT),
        array('rank_id', 1, self::MODEL_INSERT),
    );
	/**第三方登陆
	 *@return array 登陆列表
	 */
	public function index($backarray=0){
		$list = M('Oauth')->where('status=1')->field(true)->select();
		$list_html = '';
		if(empty($list))return $list_html;
		foreach($list as $k=>$v){
			switch($v['code']){
				case 'qq':$icon='&#xe616;';break;
				case 'sina':$icon='&#xe653;';break;
				case 'weixin':$icon='&#xe647;';break;
			}
            $list[$k]['icon']=$icon;
            $list[$k]['url']=U('Member/oauth/login',array('type'=>$v['code']));
			$list_html.= ' <li><a href="'.$list[$k]['url'].'" class="hc-iconfont" title="'.$v['code'].'">'.$icon.'</a></li>';
		}
		return $backarray?$list:$list_html;
	}
    /**登陆
     * @param $parme 登陆所需参数数组
     * @return array 返回状态、信息
     */
    public function check_login($parme){
        $root=array('status'=>0);
        if(empty($parme)){
            $root['info']='参数错误';
            return $root;
        }
        $username=$parme['username'];
        $password=$parme['password'];
        $verify=$parme['verify'];
        if(empty($username)||empty($password)){
            $root['info']='请输入用户名或密码';
            return $root;
        }
        if(!isset($parme['unverify'])){
            if(empty($verify)){
                $root['info']='请输入验证码';return $root;
            }
            if (!check_verify($verify,'Member')){
                $root['info']=L('verify_error');return $root;
            }
        }
		if(C('MEMBER_UC')){$uc = new \Ucenter\Client\Client();$re = $uc->uc_user_login($username,$password);}//uc登录
        $map['username|mobile']= array($username,$username,'_multi'=>true);
        $map["status"] = array('gt', 0);
        $memberinfo = M('Member')->where($map)->field(true)->find();
        if($memberinfo){
			if(C('MEMBER_UC') && $re[0]=='-2'){$root['status']=-2;$root['info']='密码错误';}
            if(C('MEMBER_UC') && $re[0]=='-3'){$root['status']=-3;$root['info']='安全提问错误';}
			if(!$root['status']){
				$postpassword = creatpwd($password,'HANCHAO'.$memberinfo['salt']);
				if($postpassword==$memberinfo['password']){
					if($parme['autologin']&& $memberinfo){//自动登录设置
						$ip=get_client_ip();
						$autostr=$memberinfo['id'].'|'.$ip.'|'.$username;
						cookie('autologin',authcode($autostr),3600);
					}else{
						cookie('autologin',null);
					}
					unset($memberinfo['password']);
					if(C('MEMBER_UC') && $re[0]=='-1' && $memberinfo['email']){//用户不存在则注册上
						$re = $uc->uc_user_register($username,$password,$memberinfo['email']);
					}            
					if(C('MEMBER_UC') && $re[0]>0){echo $uc->uc_user_synlogin($re[0]);}//同步登录
					$ma_map['uid'] = $memberinfo['id'];
        			$ma_map['status'] = 1;
        			$ma_info = M('MemberAddress')->where($ma_map)->field('xpoint,ypoint,address,city')->find();
                    if($ma_info){
                        $siteinfo['temp_lng'] = $ma_info['xpoint'];
            			$siteinfo['temp_lat'] = $ma_info['ypoint'];
            			$siteinfo['temp_name'] = $ma_info['address'];
            			$siteinfo['tj_type'] = 1;
            			$siteinfo['city'] = idtoname($ma_info['city'],'Area','name');
                        session('siteinfo',$siteinfo);
                    }
						$root['status']=1;
						$root['info']='登录成功';
                        $root['data']=$memberinfo;
						$root['url']=get_forward();
						// give_login_point($memberinfo['id']);//登录赠积分
						if(cookie('forward')){cookie('forward',null);}
						cookie('dingwei_address',null);
				}else{
					$root['status']=-2;
					$root['info']='密码错误';
				}
            }
        }else{
			if(C('MEMBER_UC') && $re[0]>0){
                $ucinfo =$uc->uc_get_user($username);
                if($ucinfo[1]){
                    $adddata['username']=$ucinfo[1];
                    $adddata['password']=$password;
                    $adddata['email']=$ucinfo[2];
                    $memberinfo=$this->register($adddata,'1');
                    $root['status']=1;
                    $root['info']='登录成功';
					$root['url']=get_forward();
					if(cookie('forward')){cookie('forward',null);}
					// give_login_point($memberinfo['id']);//登录赠积分
					if(cookie('forward')){cookie('forward',null);}
                }
            }
            if(!$ucinfo[1]){
				$root['status']=-1;
				$root['info']='用户不存在,或者被删除!';
            }
        }
        if($root['status']==1){
            $root['id']=$memberinfo['id'];
            $this->loginupdate($memberinfo);
            action_log('user_login', 'Member', $memberinfo['id'],$memberinfo['id']);
        }
        return $root;
    }
    /*会员登陆
     * @param $parme 登陆所需参数数组
     * @return array 返回状态、信息
     */
    public function mobilecheck_login($parme){
        $root=array('status'=>0);
        if(empty($parme)){
            $root['info']='参数错误';
            return $root;
        }
        $mobile=$parme['mobile'];
        $verify=$parme['verify'];
        if(empty($mobile)||empty($verify)){
            $root['info']='请输入用户名或短信验证码';
            return $root;
        }
        if(!isset($parme['unverify'])){
            if(empty($verify)){
                $root['info']='请输入验证码';return $root;
            }
            if (!check_verify($verify,'Member')){
                $root['info']=L('verify_error');return $root;
            }
        }
        $is_true = check_verify_code($mobile,$verify,0);
        if($is_true == false){
            $root['info']='短信验证码错误，请重新获取!';
			return $root;
        } 
      
		if(C('MEMBER_UC')){$uc = new \Ucenter\Client\Client();$re = $uc->uc_user_login($username,$password);}//uc登录
         
        $map['mobile']= $mobile;
        $map["status"] = array('gt', 0);
        $memberinfo = M('Member')->where($map)->field(true)->find();
        if($memberinfo){
			if(C('MEMBER_UC') && $re[0]=='-2'){$root['status']=-2;$root['info']='密码错误';}
            if(C('MEMBER_UC') && $re[0]=='-3'){$root['status']=-3;$root['info']='安全提问错误';}
			if(!$root['status']){
					if($parme['autologin']&& $memberinfo){//自动登录设置
						$ip=get_client_ip();
						$autostr=$memberinfo['id'].'|'.$ip.'|'.$username;
						cookie('autologin',authcode($autostr),3600);
					}else{
						cookie('autologin',null);
					}
					if(C('MEMBER_UC') && $re[0]=='-1' && $memberinfo['email']){//用户不存在则注册上
						$re = $uc->uc_user_register($username,$password,$memberinfo['email']);
					}            
					if(C('MEMBER_UC') && $re[0]>0){echo $uc->uc_user_synlogin($re[0]);}//同步登录
                    save_session($memberinfo['id']);
						$root['status']=1;
						$root['info']='登录成功';
                        $root['data']=$memberinfo;
						$root['url']=get_forward();
						// give_login_point($memberinfo['id']);//登录赠积分
						if(cookie('forward')){cookie('forward',null);}
						cookie('dingwei_address',null);
            }
        }else{
			if(C('MEMBER_UC') && $re[0]>0){
                $ucinfo =$uc->uc_get_user($username);
                if($ucinfo[1]){
                    $adddata['username']=$ucinfo[1];
                    $adddata['password']=$password;
                    $adddata['email']=$ucinfo[2];
                    $memberinfo=$this->register($adddata,'1');
                    $root['status']=1;
                    $root['info']='登录成功';
					$root['url']=get_forward();
					if(cookie('forward')){cookie('forward',null);}
					// give_login_point($memberinfo['id']);//登录赠积分
					if(cookie('forward')){cookie('forward',null);}
                }
            }
            if(!$ucinfo[1]){
				$root['status']=-1;
				$root['info']='用户不存在,或者被删除!';
            }
        }
        if($root['status']==1){
            $root['id']=$memberinfo['id'];
            $this->loginupdate($memberinfo);
            action_log('user_login', 'Member', $memberinfo['id'],$memberinfo['id']);
        }
        return $root;
    }
    public function register($data,$oauth=''){//注册
        $return=array('status'=>0,'msg'=>'');
        if(!isset($data['username']) || ($data['username'] == '')){
            $return['msg']='用户名不能为空';
            return $return;
        }
        if($data['password'] != $data['repassword']&&empty($oauth)){
            $return['msg']='两次输入的密码不相同';
            return $return;
        }
        $map['username']=$data['username'];
        $result = $this->where($map)->count();
        if (!empty($result)){
            $return['msg']='会员'.$data['username'].'已经存在';
            return $return;
        }
        if(!empty($data['mobile'])){
            $chaxun = M('Member')->where("mobile='".$data['mobile']."'")->count();
            if(!empty($chaxun)){
                $return['msg']='该手机号已经注册过';
                return $return;
            }}
        unset($data['repassword']);
        $data['salt'] = randStr();
        $data['password'] = $oauth && empty($data['password'])?'0':creatpwd($data['password'], 'HANCHAO'.$data['salt']);
        $data['reg_time'] = $data['last_login'] = NOW_TIME;
        $data['reg_ip'] = $data['last_ip'] = get_client_ip(1);
        $add['rank_id'] = 1;
        $is_fill_recommend=C('IS_FILL_RECOMMEND');
        if($is_fill_recommend==1 && empty($data['parent_id'])){
            $ExtensionId=cookie('ExtensionId');
            if(!empty($ExtensionId)){
                $data['parent_id'] = $ExtensionId;
                $data['parent_add_time']=NOW_TIME;
            }
        }
        C('TOKEN_ON',false);
        $this->create($data);
        $id = $this->add();
		$this->oaut_login($id);
        //unset($data);
        /*if($data['parent_id']>0 && $id>0){
            $extendata['pid']=$data['parent_id'];
            $extendata['sid']=$id;
            $extendata['addtime']=NOW_TIME;
            M('MemberExtension')->add($extendata);//添加推广记录
            //rolechange($ExtensionId,1);//处理积分
        }*/
        return $this->find($id);
    }
    public function loginupdate($memberinfo){//更新数据
        if(empty($memberinfo['id']))return false;
        $uid=$userdata['id'] = $memberinfo['id'];
        $userdata['login_count'] = array('exp', 'login_count+1');
        $userdata['last_login'] = NOW_TIME;
        $userdata['last_ip'] = get_client_ip(1);
        M('Member')->save($userdata);
        $member_info=M('Member')->where('id='.$memberinfo['id'])->field(true)->find();
		$this->oaut_login($uid);
        $memberinfo['member_info_auth_sign'] = data_auth_sign($memberinfo);
        session('member_info', $memberinfo);
        //判断cookie，未登录加入购物车
        if(cookie('u_cookieid')){
            $map['cookie_id']=cookie('u_cookieid');
            $map['user_id']=0;
            $cart_info=M("Cart")->where($map)->field(true)->select();
            if($cart_info){
                //验证购物车
              foreach ($cart_info as $k => $no_cart) {
                  $cart_map['goods_id']=$no_cart['goods_id'];
                  $cart_map['goods_attr']=$no_cart['goods_attr'];
                  $cart_map['user_id']=$uid;
                  $user_cartlist=M("Cart")->where($cart_map)->field(true)->find();
                  if ($user_cartlist) {
                      $where['goods_id']=$no_cart['goods_id'];
                      $where['goods_attr']=$no_cart['goods_attr'];
                      $where['cookie_id'] = cookie('u_cookieid');
                      M("Cart")->where($where)->delete();
                  } else {
                      $data['user_id'] = $uid;
                      $map['cookie_id'] = cookie('u_cookieid');
                      $map['goods_id'] = $no_cart['goods_id'];
                      $map['goods_attr'] = $no_cart['goods_attr'];
                      M("Cart")->where($map)->save($data);
                      $check = D("Common/Cart")->check_cart_number($no_cart['goods_id'], $no_cart['goods_num']);
                      $price_info = D("Common/Cart")->get_goods_price($no_cart['goods_id'], $no_cart['goods_attr']);
                      $map_data['cookie_id'] = '';
                      $map_data['shop_price'] = $price_info['price'];
                      $map_data['price_type'] = $price_info['price_type'];
                      $where['user_id'] = $uid;
                      $where['goods_id'] = $no_cart['goods_id'];
                      $where['goods_attr']=$no_cart['goods_attr'];
                      M("Cart")->where($where)->save($map_data);
                  }

                  }

                cookie('u_cookieid',null);
            }
        }
    }

    /**
     * 注册验证
     * @param array $postdata
     * @return array
     */
    public function do_register($postdata=array()){
        $root=array();
        $root['status']=0;
        if(!C('MEMBER_ALLOW_REGISTER')){
            $root['info']='网站暂时禁止了注册功能!';
            $root['url']=U('Home/Index/index');
			return $root;
        }
        if(!empty($postdata)){
            if (!$postdata['username'] ||!$postdata['password'] ||!$postdata['mobile'] || !$postdata['mobilecode']) {
                $root['info']='必填项请不要为空!';
                $root['url']=U('Home/Login/register');
				return $root;
            }
            /*$c_data = M('CardData')->getField('option',true);
            if(($c_data[1] == 1 && !$postdata['real_name']) || ($c_data[2] == 1 && !$postdata['sex']) || ($c_data[3] == 1 && !$postdata['birthday'])){
                $root['info']='必填项请不要为空!';
                $root['url']=U('Home/Login/register');
				return $root;
            }*/
			if($postdata['user_name']){
				$map=array();
				$map['user_name']=$postdata['user_name'];
				$is_user=M('Member')->where($map)->field(true)->find();
				if(!empty($is_user)){
					$root['info']='用户名已经被注册';
					return $root;
				}
			}
			if($postdata['ref_mobile']){
				$map=array();
				$map['mobile']=$postdata['ref_mobile'];
				$ref_info=M('Member')->where($map)->field(true)->find();
				if(!empty($ref_info)){
					$postdata['parent_id']=$ref_info['id'];
				}else{
					$root['info']='推荐人不存在';
					return $root;
				}
			}
            $is_true = check_verify_code($postdata['mobile'],$postdata['mobilecode'],0);
            if($is_true == false){
                $root['info']='短信验证码错误，请重新获取!';
                $root['url']=U('Home/Login/register');
				return $root;
            } 
			
            $result=$this->register($postdata);
            if($result['status']!=0){
                action_log('user_login', 'Member', $result['id'], $result['id']);
                cookie('forward',null);
                $member_info = M('Member')->where('id='.$result['id'])->field(true)->find();
                $member_info['member_info_auth_sign'] = data_auth_sign($member_info);
				$this->loginupdate($member_info);
				//给推荐人发短信
				if($member_info['parent_id']){
					$send_data['to'] = idtoname($member_info['parent_id'],'Member','mobile');
					$send_data['code'] = $member_info['username'];
					sendbytheme($send_data, 'TO_REGISTER_CODE');
				}
                $root['status']=1;
                $root['info']='尊敬的会员您好！恭喜您注册成功!';
                $root['data']=$member_info;
                $root['url']=U('Member/Index/index');
				// give_register_point($member_info['id']);//注册赠积分
				// give_login_point($memberinfo['id']);//登录赠积分
            }else{
                $root['info']=$result['msg'];
                $root['url']=U('Home/Login/register');
            }
        }
        return $root;
    }
	/**
     * 完善验证
     * @param array $postdata
     * @return array
     */
    public function do_perfect($postdata=array()){
        $root=array();
        $root['status']=0;
        if(!empty($postdata)){
            if (!$postdata['username'] ||!$postdata['password'] ||!$postdata['mobile'] || !$postdata['mobilecode']) {
                $root['info']='必填项请不要为空!';
				return $root;
            }
            /*$c_data = M('CardData')->getField('option',true);
            if(($c_data[1] == 1 && !$postdata['real_name']) || ($c_data[2] == 1 && !$postdata['sex']) || ($c_data[3] == 1 && !$postdata['birthday'])){
                $root['info']='必填项请不要为空!';
				return $root;
            }*/
			if($postdata['user_name']){
				$map=array();
				$map['user_name']=$postdata['user_name'];
				$is_user=M('Member')->where($map)->count();
				if(!empty($is_user)){
					$root['info']='用户名已经被注册';
					return $root;
				}
			}
			if($postdata['password'] != $postdata['repassword']){
				$root['info']='两次输入的密码不相同';
				return $root;
			}
			if($postdata['ref_mobile']){
				$map=array();
				$map['mobile']=$postdata['ref_mobile'];
				$ref_info=M('Member')->where($map)->field('id')->find();
				if(!empty($ref_info)){
					$postdata['parent_id']=$ref_info['id'];
				}else{
					$root['info']='推荐人不存在';
					return $root;
				}
			}
            $is_true = check_verify_code($postdata['mobile'],$postdata['mobilecode'],0);
            if($is_true == false){
                $root['info']='短信验证码错误，请重新获取!';
                $root['url']=U('Home/Login/perfect');
				return $root;
            } $password=$postdata['password'];
			$postdata['salt'] = randStr();
			$postdata['password'] = creatpwd($postdata['password'], 'HANCHAO'.$save['salt']);
			$is_fill_recommend=C('IS_FILL_RECOMMEND');
			if($is_fill_recommend==1 && empty($postdata['parent_id'])){
				$ExtensionId=cookie('ExtensionId');
				if(!empty($ExtensionId)){
					$postdata['parent_id'] = $ExtensionId;
					$postdata['parent_add_time']=NOW_TIME;
				}
			}
			$postdata['is_tmp'] = 0;
			unset($postdata['repassword']);

            // 发放微信会员卡
			
            $res = M('Config')->field('value')->where("name='WX_CARD'")->find();
            if($res){
                $val = unserialize($res['value']);
                $wxids[] = $postdata['wxid'];
                $wxids[] = $postdata['wxid'];
                $card_id = $val['card_id'];
                $Weixin = new \Common\Vendor\WeixinCoupon();
                $wxcard = $Weixin->wxcard($wxids,$card_id);
                if($wxcard['errcode'] == 0 || $wxcard['errcode'] == 45065){
                    $id = M('Member')->save($postdata);
                }else{
                    $root['status'] = 0;
                    $root['info'] = '微信会员卡发放失败';
                    return $root;
                }
            }else{
                $id = M('Member')->save($postdata);
            }
			if($id == 1){
				action_log('user_login', 'Member', $postdata['id'], $postdata['id']);
				$member_info = M('Member')->where('id='.$postdata['id'])->field(true)->find();
				if($member_info['parent_id']){
					$send_data['to'] = idtoname($member_info['parent_id'],'Member','mobile');
					$send_data['code'] = $member_info['username'];
					sendbytheme($send_data, 'TO_REGISTER_CODE');
				}
				$root['status']=1;
                $root['info']='尊敬的会员您好！恭喜您完善成功!';
                $root['data']=$member_info;
                $root['url']=U('Member/Index/index');
				// give_register_point($member_info['id']);//注册赠积分
                // if(!empty($ref_info))TooKeenAward('',1,'register',$ref_info['id']);//新增会员注册给推荐人奖励
			}else{
                $root['info']=$result['msg'];
                $root['url']=U('mobile/Login/perfect');
            }
        }
        return $root;
    }
    public function logout(){
        $member_info=session('member_info');
        $url=getjumpurl('JUMP_5');
		cookie('forward',U(MODULE_NAME.'/Index/index'));
        if (isset($member_info)) {
            session('member_info',null);
            cookie('autologin',null);
            cookie('lshop_id',null); // 19-1-19 zjn 退出清空
            $return['status']=1;
            $return['info']='退出成功';
            $return['url']=$url;
        } else {
            $return['status']=0;
            $return['info']='已经退出登录！';
            $return['url']=$url;
        }
        return $return;
    }
	/**
     * 重置，找回密码
     * @param array $postdata
     * @return array
     */
	 public function resetpwd($param){
		$return=array('status'=>0,'code'=>$param['code']);
		$code = $param['code'];
    	if($code == 'getpwd'){
    		$is_true = check_verify_code($param['mobile'],$param['mobilecode'],0);
            if($is_true == false){
                $return['info']='短信验证码错误!';
                $return['url']=U('Home/Login/getpassword');
				return $return;
            }else{
				$memberinfo=M('Member')->where('mobile='.$param['mobile'])->field(true)->find();
				if(empty($memberinfo)||$memberinfo['status']==0){
					$return['info']='用户不存在或已禁用';return $return;
				}
				$return['status']=1;
    			$return['mid'] =$memberinfo['id'];
    		}
    	}elseif($param['code'] == 'resetpwd'){
			$memberinfo=idtoname($param['mid'],'Member','*');
    		if(!$param['password'] || !$param['repassword'] || $param['password']!=$param['repassword']){
				$return['info']='您输入的密码为空或不一致,请重新输入!';
    		}else if(empty($memberinfo)){
    			$return['info']='参数错误!';
    		}else{//修改密码
    			$errorlog=array('0'=>'没有做任何修改','1'=>'更新成功','-1'=>'旧密码不正确','-7'=>'没有做任何修改','-8'=>'该用户受保护无权限更改');
    			$result=$this->reset_pwd($memberinfo['id'],$param['password']);
    			if($result==1){
					$return['status']=1;
					$return['info']='找回密码成功！';
					$return['url']=U('Home/Login/index');
    			}else{
    				$return['info']=$errorlog[$result];
    			}
    		}
    	}elseif($param['code'] == 'get_pay_pwd'){
			$is_true = check_verify_code($param['mobile'],$param['mobilecode'],0);
            if($is_true == false){
                $return['info'] = '短信验证码错误!';
                $return['url'] = U('Mobile/Login/get_pay_password');
				return $return;
            }else{
				$where = array();
				$where['id'] = $param['mid'];
				$where['mobile'] = $param['mobile'];
				$memberinfo = M('Member')->where($where)->field(true)->find();
				if(empty($memberinfo) || $memberinfo['status']==0){
					$return['info']='用户不存在或已禁用';return $return;
				}else{
					if(empty($param['paypassword']) || empty($param['repaypassword']) || $param['paypassword'] != $param['repaypassword']){
						$return['info']='您输入的密码为空或不一致,请重新输入!';
					}else{//修改支付密码
						$result = $this->reset_pay_pwd($memberinfo['id'],$param['paypassword']);
						$errorlog = array('0'=>'没有做任何修改','1'=>'找回支付密码成功');
						if($result == 1){
							$return['status'] = 1;
							$return['url'] = U('Mobile/UserInfo/member_account');
						}else{
							$return['info'] = $errorlog[$result];
						}
					}
				}
			}
		}
		return $return;
	}
	/**
     * 重置支付密码
     * @param array $postdata
     * @return array
     */
	public function reset_pay_pwd($uid,$paypassword){
        if(!$uid || !$paypassword)return false;
        $where['id'] = $uid;
		$u_salt = M('member')->where($where)->getField('salt');
		$data = array();
		if(empty($u_salt)){
			$u_salt = randStr();
			$data['salt'] = $u_salt; 
		}
        $data['paypassword'] = creatpwd($paypassword, 'HANCHAO'.$u_salt);        
        $result = M('member')->where($where)->save($data);
        if($result) $ret=1; else $ret=0;       
        return $ret;
    }
	/**
     * 重置密码,同步Ucenter
     * @param array $postdata
     * @return array
     */
	public function reset_pwd($uid,$password,$oldpassword='',$is_id='1'){
        if(!$uid || !$password)return false;
        if($is_id==1){
            $where['id']=$uid;
        }else{
            $where['username']=$uid;
        }
        $uinfo=M('Member')->where($where)->field('id,username,email,salt')->find();
        $data['password']=creatpwd($password, 'HANCHAO'.$uinfo['salt']);        
        $result=$this->where($where)->save($data);
        if($result)$log=1;else $log=0;
        if(C('MEMBER_UC')){
            $uc = new \Ucenter\Client\Client();
            if($oldpassword){
                $log=$uc->uc_user_edit($uinfo['username'],$oldpassword,$password);
            }else{
                $log=$uc->uc_user_edit($uinfo['username'],'',$password,'','1');
            }
        }        
        return $log;
    }
	/**
	*更新第三方登陆信息
	*/
	public function oaut_login($uid){
		$oautinfo=session('oauthmemberlogin');
		if(!$oautinfo['_name']||!$uid){
			return false;
		}elseif($uid){
			$oautinfo['lock_to_id']=$uid;
			M('OauthMember')->add($oautinfo);
			//更新会员信息
			$data=array();
			$data['nickname']=$oautinfo['_name'];
			$data['header_img']=$oautinfo['head_img'];
			M('Member')->where('id='.$uid)->save($data);
			session('oauthmemberlogin',null);
		}
	}
    /**
     * 领卡
     * @param array $postdata
     * @return array
     */
    public function get_card($postdata=array(),$nocheck=0){
        $root=array();
        $root['status']=0;
        if(!empty($postdata)){
            if (!$postdata['mobile'] || !$postdata['mobilecode']) {
                $root['info']='必填项请不要为空!';
                return $root;
            }
            $map=array();
            $map['mobile']=$postdata['mobile'];
            $map['wxid']=array('neq','');
            $map['id']=array('neq',$postdata['id']);
            $is_mobile = M('Member')->where($map)->count();
            if($is_mobile){
                $root['info']='该手机号已注册';
                return $root;
            }
			$res=D("Common/Login")->check_member_info($postdata);
            if($res['status']==3){
                $root['info']=$res['msg'];
                return $root;
            }
            $postdata['parent_id']=$res['parent_id'];
            if(empty($nocheck)){//跳过检查
                 if($postdata['user_name']){
                    $map=array();
                    $map['user_name']=$postdata['user_name'];
                    $is_user=M('Member')->where($map)->count();
                    if(!empty($is_user)){
                        $root['info']='用户名已经被注册';
                        return $root;
                    }
                }
                $is_true = check_verify_code($postdata['mobile'],$postdata['mobilecode'],0);
                if($is_true == false){
                    $root['info']='短信验证码错误，请重新获取!';
                    $root['url']=U('Home/Login/perfect');
                    return $root;
                }
            }
            $is_fill_recommend=C('IS_FILL_RECOMMEND');
            if($is_fill_recommend==1 && empty($postdata['parent_id'])){
                $ExtensionId=cookie('ExtensionId');
                if(!empty($ExtensionId)){
                    $postdata['parent_id'] = $ExtensionId;
                    $postdata['parent_add_time']=NOW_TIME;
                }
            }
            //gyc 2019.1.22
           /*  if(!empty($postdata['recom_code'])){
                $map = array();
                $map['recom_code']=$postdata['recom_code'];
                $map['status']=1;
                $mem_info = M('Member')->where($map)->getField('id');
                if(!empty($mem_info)){
                    if($postdata['id'] != $mem_info)$postdata['parent_id']=$mem_info;
                }else{
                    $root['info']='推荐码无效，请重新输入!';
                    return $root;
                }
            }
            unset($postdata['recom_code']); */
            //gyc
            $postdata['is_tmp'] = 0;
            unset($postdata['repassword']);
            
            // 发放微信会员卡            
            $res = M('Config')->field('value')->where("name='WX_CARD'")->find();
            if(!empty($res['value'])){$val=unserialize($res['value']);
                if(empty($val['card_id'])){
                    $root['info'] = '请先到后台设置微信会员卡';
                    return $root;
                }                
                $data_merge = $this->data_merge($postdata['id'],$postdata['mobile']);
                if($data_merge){
                    $postdata['id'] = $data_merge;
                    $root['data_merge'] = 1;
                }
                $id = M('Member')->save($postdata); 
                /* $wxids = $postdata['wxid'];
                $card_id = $val['card_id'];
                $Weixin = new \Common\Vendor\WeixinCoupon();
                $wxcard = $Weixin->wxcard($wxids,$card_id);
                // $root['wxcard'] = $wxcard;
                if($wxcard['errcode'] == 0){
                }elseif($wxcard['errcode'] == 45015){
                    $root['info'] = '您已经超过24小时没有和公众号发生交互了';
                    $root['url']=U('Mobile/Member/index');
                    return $root;
                }elseif($wxcard['errcode'] == 45065){
                    $root['info'] = '微信会员卡不可重复发放';
                    $root['url']=U('Mobile/Member/index');
                    return $root;
                }else{
                    if($wxcard['errcode']==40001)S('WX_S_TOKEN', null);
                    $root['info'] = '微信会员卡发放失败'.$wxcard['errcode'];
                    $root['url']=U('Mobile/Member/index');
                    return $root;
                } */
                // print_r($wxcard);exit();
            }else{
                $id = M('Member')->save($postdata);
                $root['info'] = '请先开通并到后台设置微信会员卡';
                return $root;
            }
            if($id == 1){
                $root['status']=1;
                $root['info']='尊敬的会员您好！恭喜您领取成功!';
				
				give_register_point($postdata['id']);//注册赠积分
				
                $root['url']=U('Member/Index/index');
            }else{
                $root['url']=U('mobile/Login/perfect');
            }
        }
        return $root;
    }
    /**
     * 会员合并,将新会员全并到旧会员
     * @param $id 新会员id
     * @param $mobile 新会员手机号
     */
    public function data_merge($id,$mobile){
        if(!$id || !$mobile){return false;}
        $map = array();
        $map['mobile'] = $mobile;
        $map['status'] = 1;
        $map['id'] = array('neq',$id);
        $old_info = M('Member')->where($map)->field('username,usepoints,id')->find();
        if(empty($old_info)){return false;}
        $map = array();$map['id']=$id;
        $new_info = M('Member')->where($map)->field('username,header_img,usepoints,wxid,id,wxsmall_openid,wxsmall_session_key,wx_unionid,code')->find();
        $save = array();
        $save['id'] = $old_info['id'];
        $save['usepoints'] = $old_info['usepoints']+$new_info['usepoints'];
        if($new_info['wxid'])$save['wxid'] = $new_info['wxid'];
        if($new_info['header_img'])$save['header_img'] = $new_info['header_img'];
        if($new_info['username'] && empty($old_info['username']))$save['username'] = $new_info['username'];
        if($new_info['wxsmall_openid'])$save['wxsmall_openid'] = $new_info['wxsmall_openid'];
        if($new_info['wxsmall_session_key'])$save['wxsmall_session_key'] = $new_info['wxsmall_session_key'];
        if($new_info['wx_unionid'])$save['wx_unionid'] = $new_info['wx_unionid'];
        if($new_info['code'])$save['code'] = $new_info['code'];                
        M('Member')->save($save);//修改旧数据
        $save = array();
        $save['status'] = 0;
        $save['usepoints'] = 0;
        $save['id'] = $new_info['id'];
        $save['wxid'] =$save['mobile'] = $save['wxsmall_openid'] =$save['wxsmall_session_key'] = $save['wx_unionid'] =$save['code'] ='';
        M('Member')->save($save);//修改新数据 新会员作废
        $map = array();$map['uid'] =  $new_info['id'];
        $save = array();$save['uid'] = $old_info['id'];
        M('AccountLog')->where($map)->save($save);//修改日志表
        $map = array();$map['lock_to_id'] =  $new_info['id'];
        $save = array();$save['lock_to_id'] = $old_info['id'];
        M('OauthMember')->where($map)->save($save);//修改第三方登录会员
        $map = array();$map['id']=$old_info['id'];
        $memberdata = M('Member')->where($map)->field(true)->find();
        session('memberdata',$memberdata);
        $memberdata['member_info_auth_sign'] = data_auth_sign($memberdata);
        session('member_info',$memberdata);
        return $memberdata['id'];
    }
    /**注册验证推荐人
     * @return array
     */
    public function check_member_info($param){
        $return=array('status'=>1);
        if(empty($param)){
            $return = array('status' => 3, 'msg' => '参数错误');
            return $return;
        }
        $is_register=C("REGISTER_OPEN");
        if(empty($is_register)){
            if(empty($param['ref_mobile'])) {
                $return = array('status' => 3, 'msg' => '请填写推荐人手机号');
                return $return;
            }
            $map=array();
            //$map['mobile']=$param['ref_mobile'];
            $map['rank_id']=array('gt',1);
            $map['_string'] = "mobile = ".$param['ref_mobile']." OR recom_code=".$param['ref_mobile'];
            $ref_info=M('Member')->where($map)->field(true)->find();
            // print_r($ref_info);die;
            if(!empty($ref_info)){
                $postdata['parent_id']=$ref_info['id'];
                $return['parent_id']=$ref_info['id'];
            }else{
                $return = array('status' => 3, 'msg' => '推荐人不存在');
                return $return;
            }
        }
        return $return;
    }
}
?>