<?php
/**
 * 管理员登录管理
 * @Copyright (C) 2016 汉潮 All rights reserved.
 * @License http://www.hanchao9999.com
 * @Author xiaoq <570035208@qq.com>
 */

namespace Uapp\Model;
use Think\Model;
class LoginModel extends Model{
    protected $tableName = 'member';
    public function _initialize(){
        parent::_initialize ();
    }
    /*会员登陆
     * @param $parme 登陆所需参数数组
     * @return array 返回状态、信息
     */
    public function appcheck_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;
        }
        
        $map=$where=array();
        $map['mobile']= $mobile;
        $map["status"] = array('gt', 0);
        $memberinfo = M('Member')->where($map)->field(true)->find();
        if(!$memberinfo && $parme['unionid']){
            $where['openid'] = $parme['unionid'];
            $oao_member = M('OauthMember')->where($where)->find();
            $map=array();
            $map['id']=$oao_member['lock_to_id'];
            $memberinfo = M('Member')->where($map)->field(true)->find();
        }

        if($memberinfo){
            // z注释掉
            $is_true = check_verify_code($mobile,$verify,0);
            if($is_true == false){
                $root['info']='短信验证码错误，请重新获取!';
                return $root;
            }
            if($memberinfo['salt']==0){ // 小程序登录不存在salt 存一下
                $data_salt['salt']=randStr();
                M('Member')->where($map)->save($data_salt);
            }
            if(!$memberinfo['password']){ //  没有密码 默认一个
                $salt=$data_salt['salt']?$data_salt['salt']:$memberinfo['salt'];
                $data_pwd['password']=creatpwd('HANCHAO'.$salt);
                M('Member')->where($map)->save($data_pwd);
            }
            // 2-25 注册推荐码
            if(!$memberinfo['recom_code']){
                $mem_save['recom_code'] = str_pad($memberinfo['id'],6,0,STR_PAD_LEFT);
                M('Member')->where($map)->save($mem_save);
            }
            // 2-25 注册推荐码

            //1-28 APP 绑定微信登录
            if($parme['is_show'] && $parme['is_show']==1 && (empty($parme['unionid']) || $parme['unionid']=='false')){
                $arr=array();
                $arr['lock_to_id'] = $memberinfo['id'];
                $is_bang = M('OauthMember')->where($arr)->count();
                if($is_bang==0 || !$is_bang){
                    if(empty($memberinfo['wxid'])){
                        $root['status'] = -2;
                        $root['info'] = '您还未绑定微信，请先点击下方按钮绑定微信';
                        return $root;
                    }
                }
            }
            // 绑定手机号
            if(!$memberinfo['mobile']){
                $phone_data['mobile']=$parme['mobile'];
                M('Member')->where($map)->save($phone_data);
            }

            if($parme['unionid'] && !empty($parme['unionid']) && $parme['unionid']!='false'){
                $outh_arr=array();
                $outh_arr['openid'] = $parme['unionid'];
                //oauth_member
                $is_outh = M('OauthMember')->where($outh_arr)->count();
                if(!$is_outh || $is_outh==0){
                    $ipid=get_client_ip(1);
                    $add = array();
                    $add['_from'] = 'wx';
                    $add['_name'] = $parme['nickname'];
                    $add['head_img'] = $parme['header_img'];
                    $add['create_time'] = $add['last_login_time'] = NOW_TIME;
                    $add['lock_to_id'] = $memberinfo['id'];
                    $add['status'] = $add['login_times'] = 1;
                    $add['access_token'] = $parme['access_token'];
                    $add['last_login_ip'] = $ipid;
                    // $add['openid'] = $openid;
                    $add['openid'] = $parme['unionid'];  //outh_member中的open_id == $unionid
                    M("OauthMember")->add($add);
                }else{
                    $data = array(
                        'last_login_time'    => NOW_TIME,
                        'last_login_ip'      => $ipid,
                        'login_times'        => array('exp', 'login_times+1'),
                        '_name'              => $param['nickName'],
                        'head_img'           => $param['avatarUrl'],
                    );
                    M("OauthMember")->where("`openid`='".$param['unionid']."'")->save($data);
                }
                //2.修改member表里的数据
                $save=array();
                if($parme['header_img'] && $parme['nickname']){
                    $save['header_img'] = $parme['header_img'];
                    $save['nickname'] = $parme['nickname'];
                    $is_true  = M('Member')->where($map)->save($save);
                }
                //  保存wx_unionid
                if(!$memberinfo['wx_unionid']){
                    $wx_data['wx_unionid']=$parme['unionid'];
                    M('Member')->where($map)->save($wx_data);
                }
            }
            $memberinfo = M('Member')->where('id='.$memberinfo['id'])->find();// 重新查一遍获取最新信息
        }
        else{ // 注册
            $result = $this->do_register($parme);
            if($result['status']==1){
                $memberinfo = $result['data'];
            }else{
                $root['info']=$result['info'];
                return $root;
            }
        }
        if(!$root['status']){
            $root['status']=1;
            $root['info']='登录成功';
            $root['data']=$memberinfo;
            $root['token']=creatpwd('HANCHAO'.$data['salt']);
            $root['url']=get_forward();
            // give_login_point($memberinfo['id']);//登录赠积分
            if(cookie('forward')){cookie('forward',null);}
            cookie('dingwei_address',null);
        }
        if($root['status']==1){
            $root['id']=$memberinfo['id'];
            D('Common/Login')->loginupdate($memberinfo);
            action_log('user_login', 'Member', $memberinfo['id'],$memberinfo['id']);
        }
        return $root;
    }
    /**
     * 注册验证
     * @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['mobile'] || !$postdata['verify']) {
                $root['info']='必填项请不要为空!';
                $root['url']=U('Home/Login/register');
                return $root;
            }
            //  首次注册也必须绑定微信
            if($postdata['is_show'] && $postdata['is_show']==1 && (empty($postdata['unionid']) || $postdata['unionid']=='false')){
                $root['info'] = '您还未绑定微信，请先点击下方按钮绑定微信';
                return $root;
            }
            $is_true = check_verify_code($postdata['mobile'],$postdata['verify'],0);
            if($is_true == false){
                $root['info']='短信验证码错误，请重新获取!';
                $root['url']=U('Home/Login/register');
                return $root;
            }
            $result=$this->register($postdata);
            if($result['status']!=0){
                $member_info = M('Member')->where('id='.$result['id'])->field(true)->find();
                $root['data']=$member_info;
                $root['status']=1;
                $root['info']='尊敬的会员您好！恭喜您注册成功!';
                $root['url']=U('Member/Index/index');
            }else{
                $root['info']=$result['msg'];
                $root['url']=U('Home/Login/register');
            }
        }
        return $root;
    }
    public function register($data){
        $return=array('status'=>0,'msg'=>'');
        if(!empty($data['mobile'])){
        $chaxun = M('Member')->where("mobile='".$data['mobile']."'")->count();
        if(!empty($chaxun)){
            $return['status'] = 0;
            $return['msg']='该手机号已经注册过';
            return $return;
        }}
        $oauth_arr=array();
        $oauth_arr['openid'] = $data['unionid'];
        $is_oauth = M('OauthMember')->where($oauth_arr)->count();
        if($is_oauth>0){
            $return['status'] = 0;
            $return['msg']='该微信号已经注册绑定过，请直接登录';
            return $return;exit();
        }
        // --3-29 zjn ---
        if(getconfig('REGISTER_OPEN')==0){//不开放
            if(empty($data['recom_code'])){
                $return['msg']='请填写推荐码';
                return $return;
            }
        }
        if(!empty($data['recom_code'])){
            $map = array();
            $map['recom_code']=$data['recom_code'];
            $map['status']=1;
            $mem_info = M('Member')->where($map)->getField('id');
            if(!empty($mem_info)){
                $data['parent_id']=$mem_info;
            }else{
                $return['msg']='推荐码无效，请重新输入!';
                return $return;
            }
        }
        unset($data['recom_code']);
        // ---end---
        $data['salt'] = randStr();
        $data['password'] = creatpwd('HANCHAO'.$data['salt']);// 用于APP校验
        $data['reg_time'] = $data['last_login'] = NOW_TIME;
        $data['reg_ip'] = $data['last_ip'] = get_client_ip(1);
        $data['rank_id'] = $data['status'] = 1;
        if($data['nickname']){
            $data['username']=$data['nickname'];
        }else{
            $data['nickname']=$data['username']=$data['mobile'];
        }
        if($data['unionid']) $data['wx_unionid']=$data['unionid'];
        C('TOKEN_ON',false);
        $this->create($data);
        $id = $this->add();
        // -----end----

        // 2-25 注册推荐码
        $map = array();
        $map['id']=$id;
        $mem_save['recom_code'] = str_pad($id,6,0,STR_PAD_LEFT);
        M('Member')->where($map)->save($mem_save);
        // 2-25 注册推荐码

        //913新加注册绑定微信
        $api_name = $data['nickname'];//获取到的昵称
        $api_avatar = $data['header_img'];//获取到的头像
        $access_token = $data['access_token'];
        $unionid = $data['unionid']; //unionid
        if(!$is_oauth || $is_oauth==0){
            $ipid=get_client_ip(1);
            $add = array();
            $add['_from'] = 'wx';
            $add['_name'] = $api_name;
            // xyy 2018.12.14 begin
            if(empty($api_avatar) && !empty($data['head_img'])){
              $add['head_img'] = $api_avatar;
            }else{
              $add['head_img'] = $api_avatar;
            }
            // $add['head_img'] = $api_avatar;
            // xyy 2018.12.14 end
            $add['create_time'] = $add['last_login_time'] = NOW_TIME;
            $add['lock_to_id'] = $id;
            $add['status'] = $add['login_times'] = 1;
            $add['access_token'] = $access_token;
            $add['last_login_ip'] = $ipid;
            // $add['openid'] = $openid;
            $add['openid'] = $unionid;  //outh_member中的open_id == $unionid

            M("OauthMember")->add($add);
        }
        //end
        // $this->oaut_login($id);
        return $this->find($id);
    }

    /**
     * APP 微信登陆
     * @param $id 新会员id
     * @param $mobile 新会员手机号
     */
    function qqlogin($api_type='wx',$postdata,$type){
        $return['status'] = 3;
        $unionid = $postdata['unionid'];
        $openid = $postdata['openid'];//openid
        $access_token = $postdata['access_token'];//access_token
        
        $api_avatar = $postdata['headimgurl'];//获取到的头像
        $api_name = $postdata['nickname'];//获取到的昵称
        $signstr = $postdata['sign'];//安全验证sign
        if(!$unionid||!$access_token){
            $return['msg']='授权失败,未获取到信息';
            return $return;
        }
        $where = array();
        if($api_type=='qq'){
            $where['qqid'] = $unionid;
            $user_data = M("Member")->where($where)->find();
        }else if($api_type=='wx'){
            //1030新加
            $oauth=array();
            $oauth['openid'] = $unionid;
            $is_trues = M('OauthMember')->where($oauth)->count();
            if($is_trues>0){
                $where['id'] = intval(M('OauthMember')->where($oauth)->getField('lock_to_id'));
                $user_data = M("Member")->where($where)->find();
                // 微信登陆 无初始密码 默认生成
                if(!$user_data['password']){
                    if($user_data['salt']==0){ // 小程序登录不存在salt 存一下
                        $data_salt['salt']=randStr();
                        M('Member')->where($where)->save($data_salt);
                    }
                    $salt=$user_data['salt']?$user_data['salt']:$data_salt['salt'];
                    $data_pwd['password']=creatpwd('HANCHAO'.$salt);
                    M('Member')->where($where)->save($data_pwd);
                    $user_data = M("Member")->where($where)->find();
                }
            }
            //end
        }
        if($user_data && $user_data['status'] == 0){
            $return['msg']='您的账号存在异常，请联系管理员处理';
            return $return;
        }
        $save = $map = $data = array();
        // $return['datda35'] = $user_data;
        if($user_data && $user_data['mobile']){
            //已绑定会员
            $return['datda'] = $api_type;
            if($api_type=='qq'){
                $save['last_login'] = NOW_TIME;
                $save['nickname'] = $api_name;
                $save['header_img'] = $api_avatar;
                $map['id'] = $user_data['id'];
                $res = M("Member")->where($map)->save($save);
                if(!empty($user_data['nickname'])){
                    $user_data['username'] = $user_data['nickname'];
                }elseif(!empty($user_data['username'])){
                    $user_data['username'] = $user_data['username'];
                }
            }else if($api_type=='wx'){
                $save['last_login'] = NOW_TIME;
                $save['header_img'] = $api_avatar;
                $save['nickname'] = $api_name;
                $map['id'] = $user_data['id'];
                $res = M("Member")->where($map)->save($save);
                if(!empty($user_data['nickname'])){
                    $user_data['username'] = $user_data['nickname'];
                }elseif(!empty($user_data['username'])){
                    $user_data['username'] = $user_data['username'];
                }
            }  
            $oauth_save = $oauth_where = array();
            $oauth_save['_name'] = $api_name;
            $oauth_save['last_login_time'] = NOW_TIME;
            $oauth_where['lock_to_id'] = $user_data['id'];
            M("OauthMember")->where($oauth_where)->save($oauth_save);
            M("OauthMember")->where($oauth_where)->setInc("login_times");
            $user_data['token'] = $user_data['password'];
            $return = $user_data;       
            $return['status']=1;
            $return['info']='登录成功';
        }else{
           $return['status'] = 3;
           $return['info'] = '请输入手机号';
        }
        
        return $return;
    }
  //end
}