<?php
/**
 * 用户身份认证相关操作
 */

//use Shopnc\Tpl;

defined('InShopNC') or exit('Access Invalid!');

require_once(BASE_DATA_PATH . '/model/member.model.php');
require_once(BASE_CORE_PATH . '/framework/libraries/sms.php');
require_once(BASE_CORE_PATH . '/framework/function/core.php');
require_once(BASE_ROOT_PATH . '/helper/sms_helper.php');
require_once(BASE_ROOT_PATH . '/helper/field_helper.php');
require_once(BASE_ROOT_PATH . '/helper/session_helper.php');
require_once(BASE_ROOT_PATH . '/helper/relation_helper.php');
require_once(BASE_ROOT_PATH . '/helper/account_helper.php');
require_once(BASE_ROOT_PATH . '/helper/session.php');
require_once(BASE_ROOT_PATH . '/helper/login_helper.php');

//登录，获取验证码，注册

class loginControl extends mobileHomeControl
{
    const mobile_login = 1;
    const wxopen_login = 2;

    //客户登录身份类型
    protected $client_login_type_array = array(0, 1, 2);
    private static $fields = 'member_id,member_mobile,member_wxunionid,member_wxopenid,member_name,member_truename,member_signname,' .
    'member_nickname,member_avatar,member_sex,member_birthday,member_passwd,member_paypwd,member_email,member_mobile_bind,member_state';

    public function __construct()
    {
        parent::__construct();
    }

    public function statusOp()
    {
        if (session_helper::logined()) {
            session::instance()->set_cookie($_SESSION['MPHPSESSID']);
            account_helper::onStatus($_SESSION['member_id']);
            return self::outsuccess(['member_id' => $_SESSION['member_id'],'HPHPSESSID' => $_SESSION['MPHPSESSID'],'userinfo' => $this->userinfo()]);
        }
        else
        {
            $fcode = new user_session\fcode();
            $fcode->onStatus();
            return self::outsuccess(NULL);
        }
    }

    public function wxauthorOp()
    {
        $user_info = $_GET['user_info'];
        if(empty($user_info)) {
            return self::outerr(errcode::ErrParamter, "上传的用户信息为空.");
        }

        $user_info = json_decode($user_info,true);
        if(empty($user_info)) {
            return self::outerr(errcode::ErrParamter, "上传的用户信息为空.");
        }

        if(session_helper::logined())
        {
            $loginner = new login\open_userinfo_log($user_info);
            if($loginner->ismember())
            {
                if(session_helper::memberid() == $loginner->memberid())
                {
                    return self::outsuccess(array('ismember'   => true,'isauthor' => true,
                                                  'member_id'  => $_SESSION['member_id'],
                                                  'HPHPSESSID' => $_SESSION['MPHPSESSID'],'userinfo' => $this->userinfo()));
                }
                else
                {
                    $loginner->unbind();
                }
            }

            $id_loginer = new login\memberid_log(session_helper::memberid());
            $id_loginer->bind($user_info,false);
            $id_loginer->login();
            return self::outsuccess(['ismember' => true,'isauthor' => true,
                                     'member_id' => $_SESSION['member_id'],'HPHPSESSID' => $_SESSION['MPHPSESSID'],
                                     'userinfo' => $this->userinfo()]);
        }
        else
        {
            $loginner = new login\open_userinfo_log($user_info);
            if($loginner->ismember()) {
                $loginner->bind($user_info,false);
                $loginner->login();
                return self::outsuccess(['ismember' => true,'isauthor' => true,
                                         'member_id' => $_SESSION['member_id'],
                                         'HPHPSESSID' => $_SESSION['MPHPSESSID'],
                                         'userinfo' => $this->userinfo()]);
            }
            else
            {
                $user_info['openid'] = '';
                $_SESSION['wx_author']['user_info'] = $user_info;
                $_SESSION['wx_author']['handled'] = false;
                return self::outsuccess(['ismember' => false,'isauthor' => true]);
            }
        }
    }

    public function bind_mobileOp()
    {
        $mobile = trim($_GET['mobile']);
        $code = trim($_GET['code']);

        if($mobile == '13700000000' && $code == '1111')
        {
            if(login_helper::onBinded($mobile,$code,0,false)) {
                return self::outsuccess(['ismember' => true,'isauthor' => true,
                    'member_id' => $_SESSION['member_id'],
                    'HPHPSESSID' => $_SESSION['MPHPSESSID'],'userinfo' => $this->userinfo()]);
            }
        }
        if($mobile == '13800000000' && $code == '1111')
        {
            if(login_helper::onBinded($mobile,$code,0,false)) {
                return self::outsuccess(['ismember' => true,'isauthor' => true,
                    'member_id' => $_SESSION['member_id'],
                    'HPHPSESSID' => $_SESSION['MPHPSESSID'],'userinfo' => $this->userinfo()]);
            }
        }
        if($mobile == '13900000000' && $code == '1111')
        {
            if(login_helper::onBinded($mobile,$code,0,false)) {
                return self::outsuccess(['ismember' => true,'isauthor' => true,
                    'member_id' => $_SESSION['member_id'],
                    'HPHPSESSID' => $_SESSION['MPHPSESSID'],'userinfo' => $this->userinfo()]);
            }
        }

        // 输入内容判断
        $validator = new Validator();
        $validator->setValidate(Validator::verify_mobile($mobile));
        $validator->setValidate(Validator::verify_smscode($code));
        $err = $validator->validate();
        if ($err != '') {
            return self::outerr(errcode::ErrInputParam,$err);
        }

        // 校验验证码
        $ret = sms_helper::check_code(Sms::register_code,$code,$mobile);
        if(is_array($ret)) {
            return self::outerr($ret['code'], $ret['msg']);
        }

        if(login_helper::onBinded($mobile,$code,session_helper::relay_id(),false)) {
            $isauthor = empty($_SESSION['member_wxunionid']) ? false : true;
            return self::outsuccess(['ismember' => true,'isauthor' => $isauthor,'member_id' => $_SESSION['member_id'],'HPHPSESSID' => $_SESSION['MPHPSESSID'],'userinfo' => $this->userinfo()]);
        } else {
            return self::outerr(errcode::ErrDB,"对不起，系统出现错误:(");
        }
    }

    private function userinfo()
    {
        $result = [];
        $result['member_avatar'] = session_helper::avatar();
        $result['member_mobile'] = session_helper::cur_mobile();
        $result['member_nickname'] = session_helper::nickname();
        $result['member_sex'] = session_helper::sex();

        return $result;
    }

    public function getcodexOp()
    {
        $mobile = trim($_POST['mobile']);
        $type = trim($_POST['type']);

        $validator = new Validator();
        $validator->setValidate(Validator::verify_mobile($mobile));
        $err = $validator->validate();
        if ($err != '') {
            return self::outerr(errcode::ErrParamter, $err);
        }

        $sms = new sms_helper();
        $ret = $sms->send($mobile,$type);

        if($ret['code'] == 200)
        {
            $items = Model('member')->getMemberInfo(array('member_mobile' => $mobile));
            if(empty($items)) {
                $isMember = false;
            } else {
                $isMember = true;
            }
            return self::outsuccess(['is_member' => $isMember]);
        }
        else {
            return self::outerr($ret['code'],$ret['msg']);
        }
    }
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    public function loginOp()
    {
        if ($_SESSION['is_login'] == '1') { //检查是否已经登录
            return self::outsuccess(array('member_id' => $_SESSION['member_id'],'HPHPSESSID' => $_SESSION['MPHPSESSID']));
        }

        $type = intval(trim($_POST['type']));
        if (!isset($type) || !in_array($type, $this->client_login_type_array)) {
            return self::outerr(errcode::ErrParamter, 'type error.');
        } else {
            $_SESSION['login_type'] = $type;
        }

        $validate = new Validator();
        if ($type == self::mobile_login) {
            $openid = trim($_POST['mobile']);
            $password = trim($_POST['passwd']);
            $validate->setValidate(Validator::verify_mobile($openid));
            $validate->setValidate(Validator::verify_password($password));
        } else {
            $openid = trim($_POST['openid']);
            $validate->setValidate(Validator::verify_openid($openid));
        }

        $error = $validate->validate();
        if ($error != '') {
            return self::outerr(errcode::ErrParamter, $error);
        }

        $model_member = Model('member');
        $member_info = $this->getMemberInfoEx($model_member,$openid, $type, $password);

        if (is_array($member_info) and !empty($member_info))
        {
            if (!$member_info['member_state']) {
                return self::outerr(errcode::ErrAccountStop);
            }
        }
        else
        {
            if($type == self::wxopen_login) { //如果是开放平台帐号，此处先需要注册
                return self::outerr(errcode::ErrWxNotExist);
            } else {
                return self::outerr(errcode::ErrUserOrPass, "该手机号码未注册或者密码错误");
            }
        }

        $model_member->createSession($member_info);
        Model('cart')->mergecart($member_info, $_SESSION['store_id']);
        Model('goods_browse')->mergebrowse($_SESSION['member_id'], $_SESSION['store_id']);

        account_helper::onLogin($_SESSION['member_id']);
        session::instance()->set_cookie($_SESSION['MPHPSESSID']);
        return self::outsuccess(array('member_id' => $_SESSION['member_id'],'HPHPSESSID' => $_SESSION['MPHPSESSID']));
    }

    private function register_open($model_member,$type,$openid)
    {
        if($type == self::wxopen_login)
        {
            $id = $model_member->insert(array('member_wxopenid' => $openid));
            if($id > 0) {
                return $this->getMemberInfoEx($model_member,$openid,$type);
            } else {
                return NULL;
            }
        }
        else {
            return NULL;
        }
    }

    private function getMemberInfoEx($model_member,$openid, $type, $passwd = '')
    {
        $conditions = array();
        if ($type == self::mobile_login) {
            $conditions['member_mobile'] = $openid;
            $conditions['member_passwd'] = md5($passwd);
        } elseif ($type == self::wxopen_login) {
            $conditions['member_wxopenid'] = $openid;
        } else {
            return NULL;
        }

        $ret = $model_member->getMemberInfo($conditions,self::$fields);
        $member_info = session_helper::filter_member_info($ret,$openid);
        
        return $member_info;
    }

    public function getcodeOp()
    {
        $mobile = trim($_POST['mobile']);
        $type = trim($_POST['type']);

        $validator = new Validator();
        $validator->setValidate(Validator::verify_mobile($mobile));
        $err = $validator->validate();
        if ($err != '') {
            return self::outerr(errcode::ErrParamter, $err);
        }

        $sms = new sms_helper();
        $ret = $sms->send($mobile,$type);

        if($ret['code'] == 200) {
            return self::outsuccess(NULL);
        } else {
            return self::outerr($ret['code'],$ret['msg']);
        }
    }

    public function registerOp()
    {
        if($_SESSION['is_login'] == 1) {
            return self::outerr(errcode::ErrHasLogined, '登录后，不能注册新用户.');
        }

        $mobile = trim($_POST['mobile']);
        $password = trim($_POST['passwd']);
        $code = trim($_POST['code']);

        $validator = new Validator();
        $validator->setValidate(Validator::verify_mobile($mobile));
        $validator->setValidate(Validator::verify_password($password));
        $validator->setValidate(Validator::verify_smscode($code));
        $err = $validator->validate();
        if ($err != '') {
            return self::outerr(errcode::ErrParamter, $err);
        }
        $ret = sms_helper::check_code(Sms::register_code,$code,$mobile);
        if(is_array($ret)) {
            return self::outerr($ret['code'], $ret['msg']);
        }

        $model = Model('member');
        $ret =$model->getMemberInfo(array('member_mobile' => $mobile));
        if (!empty($ret)) {
            return self::outerr(errcode::ErrUserExisted, "用户已经存在.");
        }
        else
        {
            $member_info = array('member_mobile' => $mobile,
                'member_type' => self::mobile_login,
                'member_passwd' => $password,
                'member_sex' => 0,
                'member_name' => $mobile,
                'member_nickname' => substr_replace($mobile, '****', 3, 4),
                'member_mobile_bind' => 1);

            $insert_id = $model->addMember($member_info);
            if ($insert_id == false) {
                return self::outerr(errcode::ErrRegister);
            }
            else
            {
                $member_info =$model->getMemberInfoByID($insert_id);

                $model->createSession($member_info);
                Model('cart')->mergecart($member_info, $_SESSION['store_id']);
                Model('goods_browse')->mergebrowse($_SESSION['member_id'], $_SESSION['store_id']);
                account_helper::onRegister($_SESSION['member_id'],session_helper::relay_id());
                session::instance()->set_cookie($_SESSION['MPHPSESSID']);
                return self::outsuccess(array('member_id' => $_SESSION['member_id'],'HPHPSESSID' => $_SESSION['MPHPSESSID']));
            }
        }
    }

    public function resetpassOp()
    {
        $mobile = trim($_POST['mobile']);
        $password = trim($_POST['passwd']);
        $code = trim($_POST['code']);

        $validator = new Validator();
        $validator->setValidate(Validator::verify_mobile($mobile));
        $validator->setValidate(Validator::verify_password($password));
        $validator->setValidate(Validator::verify_smscode($code));
        $err = $validator->validate();
        if ($err != '') {
            return self::outerr(errcode::ErrParamter, $err);
        }

        $ret = sms_helper::check_code(Sms::resetpass_code,$code,$mobile);
        if(is_array($ret)) {
            return self::outerr($ret['code'], $ret['msg']);
        }
	
	    $model = Model('member');
        $ret = $model->editMember(array('member_mobile' => $mobile),array('member_passwd' => md5($password)));
        if($ret == false || $model->affected_rows() <= 0)
        {
            $ret = $model->getMemberInfo(array('member_mobile' => $mobile));
            if (empty($ret)) {
                return self::outerr(errcode::ErrMemberNotExist, "该手机号未注册");
            }
        }

        return self::outsuccess(NULL);
    }

    /**
     * 微信注册登录
     * wx_openid 微信id
     * user_info: 用户信息
     * mobile: 手机号
     * code: 验证码
     */
    public function bindOp()
    {
        $wx_openid = trim($_GET['wx_openid']);
        $mobile = trim($_GET['mobile']);
        $code = trim($_GET['code']);

        // 输入内容判断
        $validator = new Validator();
        $validator->setValidate(Validator::verify_mobile($mobile));
        $validator->setValidate(Validator::verify_openid($wx_openid));
        $validator->setValidate(Validator::verify_smscode($code));
        $err = $validator->validate();
        if ($err != '') {
            return self::outerr(errcode::ErrInputParam,$err);
        }

        // 校验验证码
        $ret = sms_helper::check_code(Sms::register_code,$code,$mobile);
        if(is_array($ret)) {
            return self::outerr($ret['code'], $ret['msg']);
        }

        // 判断是否处理
        $model = Model('member');
        $ret = $model->getMemberInfo(array('member_mobile' => $mobile));
        if (empty($ret))
        {
            $passwd = $_POST['passwd'];
            $validator = new Validator();
            $validator->setValidate(Validator::verify_password($passwd));
            $err = $validator->validate();
            if ($err != '') {
                return self::outerr(errcode::ErrInputParam,$err);
            }
            $member_info = array('member_mobile' => $mobile,
                'member_type' => self::mobile_login,
                'member_passwd' => $passwd,
                'member_sex' => 0,
                'member_name' => $mobile,
                'member_nickname' => substr_replace($mobile, '****', 3, 4),
                'member_mobile_bind' => 1);
            $member_id = $model->addMember($member_info);

            if(!isset($member_id) || $member_id == false) {
                return self::outerr(errcode::ErrMemberNotExist);
            } else {
                account_helper::onRegister($member_id,session_helper::relay_id());
            }
        }
        else {
            $member_id = $ret['member_id'];
        }

        $update_arr = array();
        $info = session_helper::parase_wxinfo($_GET['user_info']);
        if($info == false) {
            $update_arr['member_wxopenid'] = $wx_openid;
        } else {
            $update_arr['member_wxopenid'] = $wx_openid;
            $update_arr = array_merge($update_arr,$info);
        }

        $ret = $model->editMember(array('member_id' => $member_id), $update_arr);
        if (!$ret) {
            return self::outerr(errcode::ErrDB);
        } else {
            $info = $model->getMemberInfoByID($member_id);
            $model->createSession($info);
            Model('cart')->mergecart($info, $_SESSION['store_id']);
            Model('goods_browse')->mergebrowse($_SESSION['member_id'], $_SESSION['store_id']);
            session::instance()->set_cookie($_SESSION['MPHPSESSID']);
            return self::outsuccess(array('member_id' => $_SESSION['member_id'],'HPHPSESSID' => $_SESSION['MPHPSESSID']));
        }
    }
}