<?php
/**
 * 前台会员注册登录控制器
 * Created by PhpStorm.
 * User: wxj
 * Date: 2019/11/19
 * Time: 15:57
 */
namespace JinDouYun\Controller\UserCenter;

use Exception;
use JinDouYun\Model\Holders\Holders;
use JinDouYun\Model\Holders\MHoldersBonus;
use JinDouYun\Model\Holders\MHoldersRecord;
use Mall\Framework\Core\ErrorCode;
use Mall\Framework\Core\ResultWrapper;
use Mall\Framework\Core\StatusCode;

use JinDouYun\Controller\BaseController;
use JinDouYun\Model\UserCenter\MApiUserCenter;
use JinDouYun\Model\UserCenter\MUserCenterRegister;
use JinDouYun\Model\Customer\MCustomer;
use JinDouYun\Cache\SmsVerification;

class ApiUserCenter extends BaseController
{
    private $objMApiUserCenter;
    private $objMUserCenterRegister;
    private $SmsVerification;

    public function __construct($isCheckAcl = false, $isMustLogin = false, $checkToken=true)
    {
        parent::__construct($isCheckAcl, $isMustLogin, $checkToken);
        $this->objMApiUserCenter = new MApiUserCenter($this->onlineEnterpriseId, $this->onlineUserId);
        $this->objMUserCenterRegister = new MUserCenterRegister();
        $this->SmsVerification = new SmsVerification();
    }

    /**
     * 获取参数
     *
     * @return array
     */
    public function commonFieldFilter()
    {
        $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'] : '',
            "source" => isset($params['source']) ? $params['source'] : '',
        ];
        foreach ($UserCenterData as $key => $value) {
            if (empty($value) && $value !== 0) {
                parent::sendOutput($key . '参数错误', ErrorCode::$paramError);
            }
        }
        //校验两次密码
        if($UserCenterData['password'] != $UserCenterData['repeatPassword']){
            parent::sendOutput('两次输入密码不一致', ErrorCode::$paramError);
        }
        $UserCenterData['avatar'] = isset($params['avatar']) ? $params['avatar'] : '';
        $UserCenterData['name'] = isset($params['name']) ? $params['name'] : $UserCenterData['mobile'];
        $UserCenterData['salesManId'] = isset($params['salesManId']) ? $params['salesManId'] : '';

        unset($UserCenterData['repeatPassword']);
        $UserCenterData['updateTime'] = time();
        $UserCenterData['createTime'] = time();

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

        return $UserCenterData;
    }

    /**
     * 前台用户注册
     * @throws Exception
     */
    public function register()
    {
        $UserCenterData = $this->commonFieldFilter();

        //校验手机号在当前企业是否作为客户注册过
        $isMobileReg = $this->objMUserCenterRegister->mobileIsRegister($UserCenterData['mobile'], $this->onlineEnterpriseId);
        if($isMobileReg){
            parent::sendOutput('该手机号已经被注册', ErrorCode::$mobileishaved);
        }
        //校验redis短信验证码
//        $this->VerifyMobileCode($UserCenterData['mobile'], $UserCenterData['smsCode']);
//        unset($UserCenterData['smsCode']);

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

        //用户类型
        $UserCenterData['isCustomer'] = StatusCode::$customerType['customer'];

        $result = $this->objMApiUserCenter->register($UserCenterData);
        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 smsLogin()
    {
        //接收参数
        $params = $this->request->getRawJson();
        $data = [
            'mobile' => isset($params['mobile']) ? $params['mobile'] :  '',
            'smsCode' => isset($params['smsCode']) ? $params['smsCode'] : '',
            'source' => isset($params['source']) ? $params['source'] : '',
        ];
        foreach($data as $key => $value){
            if(empty($value) && $value !== 0){
                parent::sendOutput($key.'参数错误', ErrorCode::$paramError);
            }
        }
        $data['salesManId'] = isset($params['salesManId']) ? $params['salesManId'] : '';
        //校验redis短信验证码
//        $this->VerifyMobileCode($data['mobile'], $data['smsCode']);

        $result = $this->objMApiUserCenter->smsLogin($data);
        if ($result->isSuccess()) {
            parent::sendOutput($result->getData());
        } else {
            parent::sendOutput($result->getData(), $result->getErrorCode());
        }

    }

    /**
     *  前台用户中心登陆
     */
    public function login()
    {
        //接收参数
        $params = $this->request->getRawJson();
        $userData = [
            'mobile' => isset($params['mobile']) ? $params['mobile'] :  '',
            'password' => isset($params['password']) ? $params['password'] : '',
            'source' => isset($params['source']) ? $params['source'] : '',//来源
        ];
        foreach($userData as $key => $value){
            if(empty($value) && $value !== 0){
                parent::sendOutput($key.'参数错误', ErrorCode::$paramError);
            }
        }
        //校验手机号格式
        parent::checkMobile($userData['mobile']);
        $result = $this->objMApiUserCenter->login($userData);
        if ($result->isSuccess()) {
            parent::sendOutput($result->getData());
        } else {
            parent::sendOutput($result->getData(), $result->getErrorCode());
        }

    }

    /**
     * 用户中心修改密码
     * @throws \Exception
     */
    public function changePassword()
    {
        $params = $this->request->getRawJson();
        $userData = [
            "mobile" => isset($params['mobile']) ? $params['mobile'] : '',
            "password" => isset($params['password']) ? $params['password'] : '',
            "repeatPassword" => isset($params['repeatPassword']) ? $params['repeatPassword'] : '',
            "smsCode" => isset($params['smsCode']) ? $params['smsCode'] : '',
        ];
        foreach($userData as $key => $value){
            if(empty($value) && $value !== 0){
                parent::sendOutput($key.'参数错误', ErrorCode::$paramError);
            }
        }

        $mobileResult = $this->objMUserCenterRegister->mobileIsRegister($userData['mobile'], $this->onlineEnterpriseId);
        if(!$mobileResult){
            parent::sendOutput('手机号不存在', ErrorCode::$mobileishaved);
        }

        //校验两次密码
        if($userData['password'] != $userData['repeatPassword']){
            parent::sendOutput('两次输入密码不一致', ErrorCode::$paramError);
        }

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

        //格式化密码
        $updateUserCenterData = [
            'password' => password_hash($userData['password'], PASSWORD_DEFAULT ),
            'updateTime' => time(),
        ];

        $where = [
            'mobile' => $userData['mobile'],
            'deleteStatus' => StatusCode::$standard
        ];

        $result = $this->objMApiUserCenter->changePassword($updateUserCenterData, $where);
        if ($result->isSuccess()) {
            parent::sendOutput($result->getData());
        } else {
            parent::sendOutput($result->getData(), $result->getErrorCode());
        }
    }

    /**
     * 判断openId或者unionId是否授权绑定手机号  (微信小程序, 抖音小程序, app微信授权)
     */
    public function checkBindMiniProgram () {
        $params = $this->request->getRawJson();

        $postData = [
            'openId'  => isset($params['openId']) ? $params['openId'] : '',
            'source'  => isset($params['source']) ? $params['source'] : '',
        ];

        foreach($postData as $key => $value){
            if (empty($value) && $value !== 0) {
                parent::sendOutput($key . '参数错误', ErrorCode::$paramError);
            }
        }
        $postData['unionId'] = isset($params['unionId']) ? $params['unionId'] : '';
        if($postData['source'] == StatusCode::$source['ios'] || $postData['source'] == StatusCode::$source['android']){
            if(!isset($params['unionId']) || empty($params['unionId'])){
                parent::sendOutput('unionId参数错误', ErrorCode::$paramError);
            }
        }

        $result = $this->objMApiUserCenter->checkBind($postData);

        if ($result->isSuccess()) {
            parent::sendOutput($result->getData());
        } else {
            parent::sendOutput($result->getData(), $result->getErrorCode());
        }
    }

    /**
     * 授权绑定手机号(微信小程序,app,抖音小程序)
     * @throws Exception
     */
    public function appletsBindMobile()
    {
        $params = $this->request->getRawJson();
        if(empty($params)){
            parent::sendOutput('参数为空', ErrorCode::$paramError);
        }
        $appletsRegisterData = [
            'mobile' => isset($params['mobile']) ? $params['mobile'] : '',
            'openId' => isset($params['openId']) ? $params['openId'] : '',
            'avatar' => isset($params['avatar']) ? $params['avatar'] : '',
            'name' => isset($params['name']) ? $params['name'] : '',
            'type' => isset($params['source']) ? $params['source'] : '',//参数切换一下  是正确的
        ];
        //【影子】设置默认昵称为用户手机号码
        if(!empty($appletsRegisterData['mobile']) && (empty($appletsRegisterData['name']) || $appletsRegisterData['name']=='微信用户')){
            $appletsRegisterData['name'] = $appletsRegisterData['mobile'];
        }
        foreach($appletsRegisterData as $key => $value){
            if (empty($value) && $value !== 0) {
                parent::sendOutput($key . '参数错误', ErrorCode::$paramError);
            }
        }
        $appletsRegisterData['source'] = isset($params['type']) ? $params['type'] : StatusCode::$source['miniProgram'];//参数切换一下  是正确的
        $appletsRegisterData['unionId'] = isset($params['unionId']) ? $params['unionId'] : '';
        $appletsRegisterData['smsCode'] = isset($params['smsCode']) ? $params['smsCode'] : '';
        $appletsRegisterData['salesManId'] = isset($params['salesManId']) ? $params['salesManId'] : '';

        if($appletsRegisterData['source'] == StatusCode::$source['ios'] || $appletsRegisterData['source'] == StatusCode::$source['android']){
            //小程序支付需要openid app不需要 所以空 后面会判断unset app微信绑定手机号不需要openid
            $appletsRegisterData['openId'] = '';
        }
        //除了微信快捷登录其他都需要验证短信
        if($appletsRegisterData['type'] != 'wx' || $appletsRegisterData['type'] != 'byteDance'){
            //校验redis短信验证码
            $this->VerifyMobileCode($appletsRegisterData['mobile'], $appletsRegisterData['smsCode']);

        }
        unset($appletsRegisterData['type']);
        unset($appletsRegisterData['smsCode']);

        //校验手机号在当前企业是否作为客户注册过
        $bindResult = $this->objMApiUserCenter->bindMobileAndOpenId(
            $appletsRegisterData['source'],
            $appletsRegisterData['mobile'],
            $appletsRegisterData['openId'],
            $appletsRegisterData['unionId'],
            $this->onlineEnterpriseId,
            $appletsRegisterData['avatar'],
            $appletsRegisterData['name']
        );
        if($bindResult->isSuccess()) {
            parent::sendOutput($bindResult->getData(), $bindResult->getErrorCode());
        }

        $appletsRegisterData['isCustomer'] = StatusCode::$customerType['customer'];
        $appletsRegisterData['createTime'] = time();
        $appletsRegisterData['updateTime'] = time();

        //调用model
        $result = $this->objMApiUserCenter->register($appletsRegisterData);
        if ($result->isSuccess()) {
            $returnData = $this->objMApiUserCenter->createToken(['id'=>$result->getData()]);
            parent::sendOutput($returnData);
        } else {
            parent::sendOutput($result->getData(), $result->getErrorCode());
        }
    }

    /**
     * 修改手机号
     */
    public function updateUserCenterMobile()
    {
        $params = $this->request->getRawJson();
        if(empty($params)){
            parent::sendOutput('参数为空', ErrorCode::$paramError);
        }
        $data = [
            'userCenterId' => isset($params['userCenterId']) ? $params['userCenterId'] : '',
            'password' => isset($params['password']) ? $params['password'] : '',
            'mobile' => isset($params['mobile']) ? $params['mobile'] : '',
            'smsCode' => isset($params['smsCode']) ? $params['smsCode'] : '',
        ];
        //验证短信验证码
        $this->VerifyMobileCode($data['mobile'], $data['smsCode']);

        //验证手机号
        //校验手机号在当前企业是否作为客户注册过
        $isMobileReg = $this->objMUserCenterRegister->mobileIsRegister($data['mobile'], $this->onlineEnterpriseId);
        if($isMobileReg){
            parent::sendOutput('该手机号已经被注册', ErrorCode::$mobileishaved);
        }

        $update = [
            'mobile' => $data['mobile'],
            'updateTime' => time(),
        ];
        $result = $this->objMUserCenterRegister->updateUserCenter($update, ['id' => $data['userCenterId']]);
        if(!$result->isSuccess()){
            return ResultWrapper::fail($result->getData(), $result->getErrorCode());
        }
        return ResultWrapper::success($result->getData());
    }

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

    /**
     * 股东股份
     * @return void
     */
    public function holders()
    {
        $uid = $this->onlineUserId;
        $Mholders = new Holders();
        $data = $Mholders->getinfo(['en_id' => $this->onlineEnterpriseId, 'us_id' => $uid])->getData();
        parent::sendOutput($data);
    }


    /**
     * 股东分红记录
     * @return void
     */
    public function holders_bonus()
    {
        $params = $this->request->getRawJson();
        $pageParams = pageToOffset($params['page'] ?: 1, $params['pageSize'] ?: 10);
        $selectParams['limit'] = $pageParams['limit'];
        $selectParams['offset'] = $pageParams['offset'];

        $Mbonus = new MHoldersBonus($this->onlineEnterpriseId);
        $uid = $this->onlineUserId;
        $Mholders = new Holders();
        $data = $Mholders->getinfo(['en_id' => $this->onlineEnterpriseId, 'us_id' => $uid])->getData();
//        if (empty($data))   parent::sendOutput('你不是股东', 1005);

        $selectParams['hol_id'] = $data['id'] ?? "";
        $result = $Mbonus->list($selectParams);

        $returnData = $result->getData();
        $pageData = [
            'pageIndex' => $params['page'],
            'pageSize' => $params['pageSize'],
            'pageTotal' => $returnData['total'],
        ];
        parent::sendOutput($returnData['data'], 0, $pageData);

    }

    /**
     * 股东股份增加记录
     * @return void
     */
    public function holders_record()
    {
        $params = $this->request->getRawJson();
        $pageParams = pageToOffset($params['page'] ?: 1, $params['pageSize'] ?: 10);
        $selectParams['limit'] = $pageParams['limit'];
        $selectParams['offset'] = $pageParams['offset'];

        $Mbonus = new MHoldersRecord($this->onlineEnterpriseId);
        $uid = $this->onlineUserId;
        $Mholders = new Holders();
        $data = $Mholders->getinfo(['en_id' => $this->onlineEnterpriseId, 'us_id' => $uid])->getData();
//        if (empty($data))   parent::sendOutput('你不是股东', 1005);


        if ($params['pm']){
            $selectParams['pm'] = $params['pm'];
        }

        if ($params['type']){
            $selectParams['type'] = $params['type'];
        }

        $selectParams['hol_id'] = $data['id'] ?? "";
        $result = $Mbonus->list($selectParams);

        $returnData = $result->getData();
        $pageData = [
            'pageIndex' => $params['page'],
            'pageSize' => $params['pageSize'],
            'pageTotal' => $returnData['total'],
        ];
        parent::sendOutput($returnData['data'], 0, $pageData);


    }

}