<?php
/**
 * 用户中心登陆管理Model
 * Created by PhpStorm.
 * User: 小威
 * Date: 2019/11/04
 * Time: 09:00
 */

namespace JinDouYun\Model\UserCenter;

use Mall\Framework\Core\ErrorCode;
use Mall\Framework\Core\StatusCode;
use Mall\Framework\Core\ResultWrapper;
use Mall\Framework\Core\Jwt;

use JinDouYun\Dao\UserCenter\DUserCenter;
use JinDouYun\Dao\Enterprise\DUserBindEnterprise;

use JinDouYun\Model\Enterprise\MEnterprise;


class MUserCenterLogin
{

    private $objDUserCenter;
    private $objMEnterprise;
    private $objDUserBindEnterprise;

    public function __construct()
    {
        $this->objDUserCenter = new DUserCenter('default');
        $this->objMEnterprise = new MEnterprise();
        $this->objDUserBindEnterprise = new DUserBindEnterprise('default');
    }

    /**
     * 后台用户中心登陆  判断账号密码
     * @param $params
     * @return ResultWrapper
     */
    public function login($params)
    {
        $where = [
            'mobile' => $params['mobile'],
            'deleteStatus' => StatusCode::$standard,
        ];
        $userInfoData = $this->objDUserCenter->get($where);
        if($userInfoData === false){
            return ResultWrapper::fail($this->objDUserCenter->error(), ErrorCode::$dberror);
        }

        if( empty($userInfoData)){
            return ResultWrapper::fail('当前手机号未注册系统', ErrorCode::$accountfail);
        }
        if(password_verify($params['password'], $userInfoData['password'] ) !== true){
            return ResultWrapper::fail('账号密码错误', ErrorCode::$accountfail);
        }

        $returnData = self::createToken($userInfoData);

        $objMEnterprise = new MEnterprise();
        $modelResult = $objMEnterprise->getAllEnterprise($userInfoData['id'], $params['source']);
        if(!$modelResult->isSuccess()){
            return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
        }
        $returnData['enterprise'] = $modelResult->getData();

        return ResultWrapper::success($returnData);
    }

    /**
     * 创建token
     */
    public function createToken($userInfo)
    {
        //jwt过期时间
        $expireTime = time() + 7200;

        $payload = array(
            'uid' => $userInfo['id'],
            'expireTime' => $expireTime,
        );
        $encoded = JWT::encode($payload, SITE_SECRET);

        return [
            'expireTime' => $expireTime,
            'token'      => $encoded,
        ];

    }

    /**
     * 刷新token方法
     * @param $userId
     * @return ResultWrapper
     */
    public function flushToken($userId)
    {

        $userInfo = $this->objDUserCenter->get(['id'=>$userId]);
        if($userInfo === false){
            return ResultWrapper::fail($this->objDUserCenter->error(), ErrorCode::$dberror);
        }
        if(empty($userInfo)){
            return ResultWrapper::fail('用户不存在', ErrorCode::$contentNotExists);
        }

        $returnData = self::createToken($userInfo);
        return ResultWrapper::success($returnData);
    }


}