<?php
/**
 * 用户中心注册管理Controller
 * Created by PhpStorm.
 * User: 小威
 * Date: 2019/11/01
 * Time: 14:00
 */

namespace JinDouYun\Controller\UserCenter;

use http\Exception;
use Mall\Framework\Core\ErrorCode;
use Mall\Framework\Core\StatusCode;

use JinDouYun\Cache\SmsVerification;

use JinDouYun\Controller\BaseController;

use JinDouYun\Model\UserCenter\MUserCenterRegister;
use JinDouYun\Model\Enterprise\MEnterprise;

class UserCenterRegister extends BaseController
{
    private $objMUserCenterRegister;
    private $objMEnterprise;
    private $SmsVerification;

    public function __construct($isCheckAcl = false, $isMustLogin = false, $checkToken=false)
    {
        parent::__construct($isCheckAcl, $isMustLogin, $checkToken);
        $this->objMUserCenterRegister = new MUserCenterRegister();
        $this->objMEnterprise = new MEnterprise();
        $this->SmsVerification = new SmsVerification();
    }

    /**
     * 获取参数
     * @param bool $verifyEnterprise
     * @return array
     */
    public function commonFieldFilter($verifyEnterprise = false)
    {
        //接收参数
        $params = $this->request->getRawJson();
        //映射参数
        $UserCenterData = [
            "mobile" => isset($params['mobile']) ? $params['mobile'] : '',
            "password" => isset($params['password']) ? $params['password'] : '',
            "repeatPassword" => isset($params['repeatPassword']) ? $params['repeatPassword'] : '',
            "smsCode" => isset($params['smsCode']) ? $params['smsCode'] : '',
        ];

        if($verifyEnterprise) {
            $UserCenterData["enterpriseId"] = isset($params['enterpriseId']) ? $params['enterpriseId'] : '';
        }
        //校验参数
        foreach ($UserCenterData as $key => $value) {
            if (empty($value) && $value !== 0) {
                parent::sendOutput($key . '参数错误', ErrorCode::$paramError);
            }
        }
        //校验两次密码
        if($UserCenterData['password'] != $UserCenterData['repeatPassword']){
            parent::sendOutput('两次输入密码不一致', ErrorCode::$paramError);
        }
        unset($UserCenterData['repeatPassword']);
        //固定参数
        $UserCenterData['source'] = isset($params['source']) ? $params['source'] : StatusCode::$source['manage'];
        $UserCenterData['updateTime'] = time();

        //校验手机号格式
        $this->checkMobile($UserCenterData['mobile']);

        return $UserCenterData;
    }

    /**
     * 用户中心添加 / 后台用户注册
     * @throws \Exception
     */
    public function addUserCenter()
    {
        exit;
        $UserCenterData = $this->commonFieldFilter();

        //校验redis短信验证码
//        $this->VerifyMobileCode($UserCenterData['mobile'], $UserCenterData['smsCode']);
        unset($UserCenterData['smsCode']);

        //格式化密码
        $UserCenterData['password'] = password_hash($UserCenterData['password'], PASSWORD_DEFAULT );

        //来源标识
        $UserCenterData['source'] = StatusCode::$source['manage'];
        $UserCenterData['createTime'] = time();
        $UserCenterData['updateTime'] = time();

        $result = $this->objMUserCenterRegister->addUserCenter($UserCenterData);
        if ($result->isSuccess()) {
            parent::sendOutput($result->getData());
        } else {
            parent::sendOutput($result->getData(), $result->getErrorCode());
        }
    }

    /**
     * 修改手机号(账号)
     */
    public function updateUserMobile()
    {
        $params = $this->request->getRawJson();
        if(empty($params)){
            parent::sendOutput('参数为空', ErrorCode::$paramError);
        }
        $data['mobile'] = isset($params['mobile']) ? $params['mobile'] : '';
        $data['userCenterId'] = isset($params['userCenterId']) ? $params['userCenterId'] : '';
        $data['password'] = isset($params['password']) ? $params['password'] : '';
        foreach($data as $key => $value){
            if(empty($value)){
                parent::sendOutput($key.'参数为空', ErrorCode::$paramError);
            }
        }
        $result = $this->objMUserCenterRegister->updateUserMobile($data);
        if ($result->isSuccess()) {
            parent::sendOutput($result->getData());
        } else {
            parent::sendOutput($result->getData(), $result->getErrorCode());
        }
    }

    /**
     * 用户中心删除
     */
    public function deleteUserCenter()
    {
        $params['id'] = $this->request->param('request_id');
        if (empty($params)) {
            parent::sendOutput('参数为空', ErrorCode::$paramError);
        }

        $result = $this->objMUserCenterRegister->deleteUserCenter($params);
        if ($result->isSuccess()) {
            parent::sendOutput($result->getData());
        } else {
            parent::sendOutput($result->getData(), $result->getErrorCode());
        }
    }

    /**
     * 用户中心修改
     */
    public function updateUserCenter()
    {
        $params['id'] = $this->request->param('request_id');
        if (empty($params)) {
            parent::sendOutput('参数为空', ErrorCode::$paramError);
        }
        $UserCenterData = $this->commonFieldFilter();

        $result = $this->objMUserCenterRegister->updateUserCenter($UserCenterData, $params);
        if ($result->isSuccess()) {
            parent::sendOutput($result->getData());
        } else {
            parent::sendOutput($result->getData(), $result->getErrorCode());
        }
    }

    /**
     * 后台用户中心忘记密码
     * @throws \Exception
     */
    public function forgetPassword()
    {
        $UserCenterData = $this->commonFieldFilter();
        //检验手机号是否存在
        $mobileResult = $this->objMUserCenterRegister->mobileIsRegister($UserCenterData['mobile']);
        if(!$mobileResult){
            parent::sendOutput('手机号不存在', ErrorCode::$mobileishaved);
        }
        //校验redis短信验证码
        $this->VerifyMobileCode($UserCenterData['mobile'], $UserCenterData['smsCode']);

        //格式化密码
        $password = password_hash($UserCenterData['password'], PASSWORD_DEFAULT );

        $where['mobile'] = $UserCenterData['mobile'];

        $result = $this->objMUserCenterRegister->updateUserCenterPassword($password, $where);
        if ($result->isSuccess()) {
            parent::sendOutput($result->getData());
        } else {
            parent::sendOutput($result->getData(), $result->getErrorCode());
        }
    }

    /**
     * 用户中心列表
     */
    public function getAllUserCenter()
    {
        $params = $this->request->getRawJson();

        $pageParams = pageToOffset($params['page'] ?: 1, $params['pageSize'] ?: 10);
        $selectParams['limit'] = $pageParams['limit'];
        $selectParams['offset'] = $pageParams['offset'];

        $result = $this->objMUserCenterRegister->getAllUserCenter($selectParams);

        if ($result->isSuccess()) {
            $returnData = $result->getData();
            $pageData = [
                'pageIndex' => $params['page'],
                'pageSize' => $params['pageSize'],
                'pageTotal' => $returnData['total'],
            ];
            parent::sendOutput($returnData['data'], 0, $pageData);
        } else {
            parent::sendOutput($result->getData(), ErrorCode::$dberror);
        }
    }

    /**
     * 用户中心详情
     */
    public function getUserCenterInfo()
    {
        $params['id'] = $this->request->param('request_id');
        if (empty($params['id'])) {
            parent::sendOutput('参数为空', ErrorCode::$paramError);
        }

        $result = $this->objMUserCenterRegister->getUserCenterInfo($params);
        if ($result->isSuccess()) {
            parent::sendOutput($result->getData());
        } else {
            parent::sendOutput($result->getData(), $result->getErrorCode());
        }
    }

    /**
     * 公用方法
     */

    /**
     * 验证短信验证码
     *
     * @param $mobile
     * @param $mobileCode
     * @return void
     * @throws \Exception
     */
    public function VerifyMobileCode($mobile, $mobileCode)
    {
        // $cacheMobileCode = $this->SmsVerification->getMobileCode($mobile);
        // if( $mobileCode != $cacheMobileCode ){
        //     parent::sendOutput('验证码有误', ErrorCode::$mobileCodeFail);
        // }
    }

    /**
     * 验证手机号是否存在(注册)
     */
    public function mobileIsRegister()
    {
        $mobile = $this->request->param('request_id');
        if( !$mobile ){
            parent::sendOutput('手机号为空', ErrorCode::$paramError);
        }
        $this->checkMobile($mobile);
        $result = $this->objMUserCenterRegister->mobileIsRegister($mobile);
        if ($result) {
            parent::sendOutput(true); //已注册
        }
        parent::sendOutput( false);//未注册
    }

}