<?php

namespace app\api\controller;
use think\facade\Lang;
/**
 * ============================================================================
 * 
 * ============================================================================
 * 版权所有 2014-2028 浙江惠利玛产业互联网有限公司，并保留所有权利。
 * 网站地址: https://www.valimart.net/
 * ----------------------------------------------------------------------------
 * 
 * ============================================================================
 * 用户账号控制器
 */
class Memberaccount extends MobileMember
{
    public function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
        Lang::load(base_path() . 'home/lang/' . config('lang.default_lang') . '/memberpoints.lang.php');
    }

    /**
     * @api {POST} api/Memberaccount/bind_mobile_step1 绑定手机第一步
     * @apiVersion 1.0.0
     * @apiGroup MemberAccount
     *
     * @apiHeader {String} X-DS-KEY 用户授权token
     *
     * @apiParam {String} mobile 手机号
     *
     * @apiSuccess {String} code 返回码,10000为成功
     * @apiSuccess {String} message  返回消息
     * @apiSuccess {Object} result  返回数据
     * @apiSuccess {Int} result.sms_time 倒计时时间（秒）
     */
    public function bind_mobile_step1()
    {
        if (!input('post.mobile') || !preg_match('/^\d{11}$/', input('post.mobile'))) {
            ds_json_encode(10001, lang('fill_your_phone_number_correctly'), ['code' => '']);
        }


        $member_model = model('member');
        $check_mobile = $member_model->getMemberInfo(array(
            'member_mobile' => trim(input('post.mobile')),
            'member_mobilebind' => 1
        ));
        if (is_array($check_mobile) and count($check_mobile) > 0) {
            ds_json_encode(10001, lang('please_change_another_phone_number'), ['code' => '']);
        }
        //验证发送频率
        $verify_code_model = model('verify_code');
        $result = $verify_code_model->isVerifyCodeFrequant(4, 1);
        if (!$result['code']) {
            ds_json_encode(10001, $result['msg'], ['code' => '']);

        }

        $verify_code = $verify_code_model->genVerifyCode(4, 1);
        if (!$verify_code) {
            ds_json_encode(10001, lang('system_occur_error'), ['code' => '']);

        }

        try {

            $mailtemplates_model = model('mailtemplates');
            $tpl_info = $mailtemplates_model->getTplInfo(array('mailmt_code' => 'modify_mobile'));
            $param = array();
            $param['code'] = $verify_code;
            $ten_param=array($param['code']);
            $message = ds_replace_text($tpl_info['mailmt_content'], $param);
            $smslog_param=array(
                    'ali_template_code'=>$tpl_info['ali_template_code'],
                    'ali_template_param'=>$param,
                    'ten_template_code'=>$tpl_info['ten_template_code'],
                    'ten_template_param'=>$ten_param,
                    'message'=>$message,
                );
            //发送短信
            $result = model('smslog')->sendSms(input('post.mobile'), $smslog_param,4,$verify_code);

            if ($result['state']) {
                $ip = request()->ip();
                $flag = $verify_code_model->addVerifyCode(array(
                    'verify_code_type' => 4,
                    'verify_code' => $verify_code,
                    'verify_code_user_type' => 1,
                    'verify_code_user_id' => $this->member_info['member_id'],
                    'verify_code_user_name' => $this->member_info['member_name'],
                    'verify_code_add_time' => TIMESTAMP,
                    'verify_code_ip' => $ip,
                ));
                if (!$flag) {
                    ds_json_encode(10001, lang('system_occur_error'));

                }
                $updates = array();
                $updates['member_mobilebind'] = 0;
                $updates['member_mobile'] = input('post.mobile');
                $member_model->editMember(array('member_id' => $this->member_info['member_id']), $updates,$this->member_info['member_id']);
                ds_json_encode(10000, lang('send_success'), array('sms_time' => DEFAULT_CONNECT_SMS_TIME));
            } else {
                ds_json_encode(10001, $result['message']);
            }
        } catch (Exception $e) {
            ds_json_encode(10001, $e->getMessage());
        }
    }

    /**
     * @api {POST} api/Memberaccount/bind_mobile_step2 绑定手机第二步 - 验证短信码
     * @apiVersion 1.0.0
     * @apiGroup MemberAccount
     *
     * @apiHeader {String} X-DS-KEY 用户授权token
     *
     * @apiParam {String} auth_code 验证码
     *
     * @apiSuccess {String} code 返回码,10000为成功
     * @apiSuccess {String} message  返回消息
     */
    public function bind_mobile_step2()
    {
        if (!input('post.auth_code') || !preg_match('/^\d{6}$/', input('post.auth_code'))) {
            ds_json_encode(10001, lang('input_verification_code'), ['code' => '-1']);
        }
        $member_model = model('member');

        $verify_code = input('post.auth_code');
        $validate_data = array(
            'verify_code' => $verify_code,

        );
        $verify_code_validate = ds_validate('verify_code');
        if (!$verify_code_validate->scene('verify_code_search')->check($validate_data)) {

            ds_json_encode(10001, $verify_code_validate->getError(), ['code' => '-1']);
        }
        $verify_code_model = model('verify_code');
        if (!$verify_code_model->getVerifyCodeInfo(array(array('verify_code_type' ,'=', 4), array('verify_code_user_type' ,'=', 1), array('verify_code_user_id' ,'=', $this->member_info['member_id']), array('verify_code' ,'=', $verify_code), array('verify_code_add_time','>', TIMESTAMP - VERIFY_CODE_INVALIDE_MINUTE * 60)))) {

            ds_json_encode(10001, lang('validation_fails'), ['code' => '-1']);
        }


        $updates = array();
        $updates['member_mobilebind'] = 1;
        $update = $member_model->editMember(array('member_id' => $this->member_info['member_id']), $updates,$this->member_info['member_id']);
        if (!$update) {
            ds_json_encode(10001, lang('system_occur_error'));
        }
        ds_json_encode(10000, lang('ds_common_op_succ'), 1);
    }

    /**
     * @api {POST} api/Memberaccount/bind_email_step1 绑定邮箱第一步
     * @apiVersion 1.0.0
     * @apiGroup MemberAccount
     *
     * @apiHeader {String} X-DS-KEY 用户授权token
     *
     * @apiParam {String} email 邮箱
     *
     * @apiSuccess {String} code 返回码,10000为成功
     * @apiSuccess {String} message  返回消息
     * @apiSuccess {Object} result  返回数据
     * @apiSuccess {Int} result.sms_time 倒计时时间（秒）
     */
    public function bind_email_step1()
    {
        if (!input('post.email') || !preg_match('/^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/', input('post.email'))) {
            ds_json_encode(10001, lang('please_fill_mailbox_correctly'), ['code' => '']);
        }


        $member_model = model('member');
        $check_email = $member_model->getMemberInfo(array(
            'member_email' => trim(input('post.email')),
            'member_emailbind' => 1
        ));
        if (is_array($check_email) and count($check_email) > 0) {
            ds_json_encode(10001, lang('mailbox_has_been_used'), ['code' => '']);
        }
        //验证发送频率
        $verify_code_model = model('verify_code');
        $result = $verify_code_model->isVerifyCodeFrequant(4, 1);
        if (!$result['code']) {
            ds_json_encode(10001, $result['msg'], ['code' => '']);

        }

        $verify_code = $verify_code_model->genVerifyCode(4, 1);
        if (!$verify_code) {
            ds_json_encode(10001, lang('system_occur_error'), ['code' => '']);

        }

        try {

            $uid = base64_encode(ds_encrypt($this->member_info['member_id'] . ' ' . input('post.email')));
            $verify_url = HOME_SITE_URL . '/Login/bind_email.html?uid=' . $uid . '&hash=' . md5($verify_code);

            $mailtemplates_model = model('mailtemplates');
            $tpl_info = $mailtemplates_model->getTplInfo(array('mailmt_code' => 'bind_email'));
            $param = array();
            $param['site_name'] = config('ds_config.site_name');
            $param['user_name'] = $this->member_info['member_name'];
            $param['verify_url'] = $verify_url;
            $subject = ds_replace_text($tpl_info['mailmt_title'], $param);
            $message = ds_replace_text($tpl_info['mailmt_content'], $param);

            //发送短信
            $email = new \sendmsg\Email();
            $result['state'] = $email->send_sys_email(input('post.email'), $subject, $message);

            if ($result['state']) {
                $ip = request()->ip();
                $flag = $verify_code_model->addVerifyCode(array(
                    'verify_code_type' => 5,
                    'verify_code' => $verify_code,
                    'verify_code_user_type' => 1,
                    'verify_code_user_id' => $this->member_info['member_id'],
                    'verify_code_user_name' => $this->member_info['member_name'],
                    'verify_code_add_time' => TIMESTAMP,
                    'verify_code_ip' => $ip,
                ));
                if (!$flag) {
                    ds_json_encode(10001, lang('system_occur_error'));

                }
                $updates = array();
                $updates['member_emailbind'] = 0;
                $updates['member_email'] = input('post.email');
                $member_model->editMember(array('member_id' => $this->member_info['member_id']), $updates,$this->member_info['member_id']);
                ds_json_encode(10000, lang('send_success'), array('sms_time' => DEFAULT_CONNECT_SMS_TIME));
            } else {
                ds_json_encode(10001, $result['message']);
            }
        } catch (Exception $e) {
            ds_json_encode(10001, $e->getMessage());
        }
    }


    /**
     * 检测会员手机是否绑定
     * 更改绑定手机 第一步 - 得到已经绑定的手机号
     * 修改密码 第一步 - 得到已经绑定的手机号
     * 修改支付密码 第一步 - 得到已经绑定的手机号
     */
    public function get_mobile_info()
    {
        $data = array();
        $data['state'] = $this->member_info['member_mobilebind'] ? true : false;
        $data['mobile'] = $data['state'] ? encrypt_show($this->member_info['member_mobile'], 4, 4) : $this->member_info['member_mobile'];
        ds_json_encode(10000, '', $data);
    }

    /**
     * 检测是否设置了支付密码
     */
    public function get_paypwd_info()
    {
        $data = array();
        $data['state'] = $this->member_info['member_paypwd'] ? true : false;
        ds_json_encode(10000, '', $data);
    }

    /**
     * @api {POST} api/Memberaccount/send_auth_code 统一发送身份验证码
     * @apiVersion 1.0.0
     * @apiGroup MemberAccount
     *
     * @apiHeader {String} X-DS-KEY 用户授权token
     *
     * @apiParam {String} type 类型
     *
     * @apiSuccess {String} code 返回码,10000为成功
     * @apiSuccess {String} message  返回消息
     * @apiSuccess {Object} result  返回数据
     * @apiSuccess {Int} result.sms_time 倒计时时间（秒）
     */
    public function send_auth_code()
    {
        $type = input('post.type');
        if (!in_array($type, array('email', 'mobile'))) {
            ds_json_encode(10001, lang('param_error'));
        }

        if ($type == 'mobile' && (!$this->member_info['member_mobilebind'] || !$this->member_info['member_mobile'])) {
            ds_json_encode(10001, lang('not_bind_mobile'));
        }
        if ($type == 'email' && (!$this->member_info['member_emailbind'] || !$this->member_info['member_email'])) {
            ds_json_encode(10001, lang('not_bind_email'));
        }

        $member_model = model('member');
        //验证发送频率
        $verify_code_model = model('verify_code');
        $result = $verify_code_model->isVerifyCodeFrequant(6, 1);
        if (!$result['code']) {
            ds_json_encode(10001, $result['msg']);

        }

        $verify_code = $verify_code_model->genVerifyCode(6, 1);
        if (!$verify_code) {
            ds_json_encode(10001, lang('system_occur_error'));

        }

        try {

            $tpl_info = model('mailtemplates')->getTplInfo(array('mailmt_code' => 'authenticate'));
            $param = array();
            $ali_template_param=array();
            $param['code'] = $verify_code;
            $ali_template_param=$param;
            $param['site_name'] = config('ds_config.site_name');
            $ten_template_param=array($param['code']);
            $subject = ds_replace_text($tpl_info['mailmt_title'], $param);
            $message = ds_replace_text($tpl_info['mailmt_content'], $param);

            if ($type == 'email') {
                $email = new \sendmsg\Email();
                $result['state'] = $email->send_sys_email($this->member_info["member_email"], $subject, $message);
            } elseif ($type == 'mobile') {
                $smslog_param=array(
                    'ali_template_code'=>$tpl_info['ali_template_code'],
                    'ali_template_param'=>$ali_template_param,
                    'ten_template_code'=>$tpl_info['ten_template_code'],
                    'ten_template_param'=>$ten_template_param,
                    'message'=>$message,
                );
                $result = model('smslog')->sendSms($this->member_info['member_mobile'], $smslog_param,5,$verify_code);
            }


            if ($result['state']) {
                $ip = request()->ip();
                $flag = $verify_code_model->addVerifyCode(array(
                    'verify_code_type' => 6,
                    'verify_code' => $verify_code,
                    'verify_code_user_type' => 1,
                    'verify_code_user_id' => $this->member_info['member_id'],
                    'verify_code_user_name' => $this->member_info['member_name'],
                    'verify_code_add_time' => TIMESTAMP,
                    'verify_code_ip' => $ip,
                ));
                if (!$flag) {
                    ds_json_encode(10001, lang('system_occur_error'));

                }
                ds_json_encode(10000, lang('send_success'), array('sms_time' => DEFAULT_CONNECT_SMS_TIME, 'state' => '1'));
            } else {
                ds_json_encode(10001, $result['message'], ['code' => '']);
            }
        } catch (Exception $e) {
            ds_json_encode(10001, $e->getMessage(), ['code' => '']);
        }
    }

    /**
     * @api {POST} api/Memberaccount/check_auth_code 统一验证身份验证码
     * @apiVersion 1.0.0
     * @apiGroup MemberAccount
     *
     * @apiHeader {String} X-DS-KEY 用户授权token
     *
     * @apiParam {String} auth_code 验证码
     *
     * @apiSuccess {String} code 返回码,10000为成功
     * @apiSuccess {String} message  返回消息
     */
    public function check_auth_code()
    {
        $verify_code = input('post.auth_code');
        $validate_data = array(
            'verify_code' => $verify_code,

        );
        $verify_code_validate = ds_validate('verify_code');
        if (!$verify_code_validate->scene('verify_code_search')->check($validate_data)) {

            ds_json_encode(10001, $verify_code_validate->getError());
        }
        $verify_code_model = model('verify_code');
        if (!$verify_code_model->getVerifyCodeInfo(array(array('verify_code_type' ,'=', 6), array('verify_code_user_type' ,'=', 1), array('verify_code_user_id' ,'=', $this->member_info['member_id']), array( 'verify_code' ,'=', $verify_code), array('verify_code_add_time','>', TIMESTAMP - VERIFY_CODE_INVALIDE_MINUTE * 60)))) {

            ds_json_encode(10001, lang('validation_fails'));
        }
        ds_json_encode(10000, '', 1);
    }

    private function _modify_pwd_limit_check()
    {
        //身份验证后，需要在30分钟内完成修改密码操作

        $verify_code_model = model('verify_code');
        if (!$verify_code_model->getVerifyCodeInfo(array(array('verify_code_type' ,'=', 6), array('verify_code_user_type' ,'=', 1), array('verify_code_add_time','>', TIMESTAMP - 30 * 60)))) {

            ds_json_encode(10001, lang('validation_fails'), ['code' => '']);
        }
    }

    /**
     * @api {POST} api/Memberaccount/modify_password 更改密码 - 保存新密码到数据库
     * @apiVersion 1.0.0
     * @apiGroup MemberAccount
     *
     * @apiHeader {String} X-DS-KEY 用户授权token
     *
     * @apiParam {String} password 原密码
     * @apiParam {String} password1 新密码
     *
     * @apiSuccess {String} code 返回码,10000为成功
     * @apiSuccess {String} message  返回消息
     */
    public function modify_password()
    {
        if (!input('post.password') || !input('post.password1') || input('post.password') != input('post.password1')) {
            ds_json_encode(10001, lang('param_error'), ['code' => '']);
        }

        //身份验证后，需要在30分钟内完成修改密码操作
        $this->_modify_pwd_limit_check();

        $member_model = model('member');

        $update = $member_model->editMember(array('member_id' => $this->member_info['member_id']), array('member_password' => md5(input('post.password'))),$this->member_info['member_id']);
        if (!$update) {
            ds_json_encode(10001, lang('password_setting_failed'), ['code' => '']);
        }


        ds_json_encode(10000, lang('ds_common_op_succ'), 1);
    }


     /**
     * @api {POST} api/Memberaccount/modify_password 更改支付密码 - 保存新密码到数据库
     * @apiVersion 1.0.0
     * @apiGroup MemberAccount
     *
     * @apiHeader {String} X-DS-KEY 用户授权token
     *
     * @apiParam {String} password 原密码
     * @apiParam {String} password1 新密码
     *
     * @apiSuccess {String} code 返回码,10000为成功
     * @apiSuccess {String} message  返回消息
     */
    public function modify_paypwd()
    {

        if (!input('post.password') || !input('post.password1') || input('post.password') != input('post.password1')) {
            ds_json_encode(10001, lang('param_error'), ['code' => '']);
        }

        //身份验证后，需要在30分钟内完成修改密码操作
        $this->_modify_pwd_limit_check();

        $member_model = model('member');
        $update = $member_model->editMember(array('member_id' => $this->member_info['member_id']), array('member_paypwd' => md5(input('post.password'))),$this->member_info['member_id']);
        if (!$update) {
            ds_json_encode(10001, lang('password_setting_failed'), ['code' => '']);
        }

        ds_json_encode(10000, lang('ds_common_op_succ'), 1);
    }

}