<?php
/**
 * Created by PhpStorm.
 * User: leo
 * Date: 2018/2/24
 * Time: 下午1:02
 */
namespace backendApi\modules\v1\models;

use common\helpers\Date;
use common\helpers\Tool;
use Yii;
use yii\web\IdentityInterface;

class User extends Admin implements IdentityInterface
{
    /**
     * @param mixed $token
     * @param null $type
     * @return null|IdentityInterface|static
     */
    public static function findIdentityByAccessToken($token, $type = null)
    {
        // 从redis中把 token 找到
        return Yii::$app->tokenRedis->hget($token, 'ID');
//        if($userId){
//            return static::findOne(['ID' => $userId]);
//        }
//        return null ;
    }

    public function fields()
    {
        $fields = parent::fields();

        // 删除一些包含敏感信息的字段
        unset($fields['PASSWORD_HASH'], $fields['PASSWORD_RESET_TOKEN'], $fields['AUTH_KEY']);

        return $fields;
    }

    /**
     * {@inheritdoc}
     */
    public function behaviors()
    {
        return [
            'yii\behaviors\TimestampBehavior',
        ];
    }

    /**
     * {@inheritdoc}
     */
    public static function findIdentity($id)
    {
        return static::findOne(['ID' => $id]);
    }

    /**
     * Finds user by adminName
     *
     * @param string $adminName
     * @return static|null
     */
    public static function findByUsername($adminName)
    {
        return static::findOne(['ADMIN_NAME' => $adminName,'IS_DEL'=>0]);
    }

    /**
     * 通过用户名获取信息并带着token表内容
     * @param $adminName
     * @return array
     */
    public static function findByUsernameWithToken($adminName){
        $result = static::find()->select(static::tableName().'.*,T.ACCESS_TOKEN,T.REFRESH_TOKEN,T.CREATED_AT,T.UPDATED_AT')->join('LEFT JOIN', AdminToken::tableName().' AS T', static::tableName().'.ID=T.ADMIN_ID')->where(static::tableName().'.ADMIN_NAME=:ADMIN_NAME', ['ADMIN_NAME'=>$adminName])->asArray()->one();
        return $result;
    }

    /**
     * 静态方法校验两个密码
     * @param $password
     * @param $validatePassword
     * @return bool
     */
    public static function validatePasswordStatic($password, $validatePassword)
    {
        return Yii::$app->security->validatePassword($password, $validatePassword);
    }

    /**
     * 生成PCAccessToken
     * @param $appType (pc|app)
     * @return string
     * @throws \yii\base\Exception
     */
    public static function generateAccessToken($appType){
        $appTypeUper = strtoupper($appType);
        // 从redis的AccessTokenIncr中自增一个值
        $incrValue = Yii::$app->tokenRedis->incr($appTypeUper.'AccessTokenIncr');
        // apa(admin_pc_access)
        return md5('a'.$appType[0].'a_' . Yii::$app->security->generateRandomString(8) . Date::nowTime() . $incrValue);
    }

    /**
     * 生成PCRefreshToken
     * @param $appType (pc|app)
     * @return string
     * @throws \yii\base\Exception
     */
    public static function generateRefreshToken($appType){
        $appTypeUper = strtoupper($appType);
        // 从redis的AccessTokenIncr中自增一个值
        $incrValue = Yii::$app->tokenRedis->incr($appTypeUper.'RefreshTokenIncr');
        // apr(admin_pc_access)
        return md5('a'.$appType[0].'r_' . Yii::$app->security->generateRandomString(8) . Date::nowTime() . $incrValue);
    }

    /**
     * 通过重设密码 token 找到用户
     * @param $token
     * @return null|static
     */
    public static function findByPasswordResetToken($token)
    {
        if (!static::isPasswordResetTokenValid($token)) {
            return null;
        }

        return static::findOne([
            'PASSWORD_RESET_TOKEN' => $token,
        ]);
    }

    /**
     * Finds out if password reset token is valid
     *
     * @param string $token password reset token
     * @return bool
     */
    public static function isPasswordResetTokenValid($token)
    {
        if (empty($token)) {
            return false;
        }

        $timestamp = (int) substr($token, strrpos($token, '_') + 1);
        $expire = Yii::$app->params['user.passwordResetTokenExpire'];
        return $timestamp + $expire >= time();
    }

    /**
     * {@inheritdoc}
     */
    public function getId()
    {
        return $this->getPrimaryKey();
    }

    /**
     * {@inheritdoc}
     */
    public function getAuthKey()
    {
        return $this->AUTH_KEY;
    }

    /**
     * {@inheritdoc}
     */
    public function validateAuthKey($authKey)
    {
        return $this->getAuthKey() === $authKey;
    }

    /**
     * Validates password
     *
     * @param string $password password to validate
     * @return bool if password provided is valid for current user
     */
    public function validatePassword($password)
    {
        return Yii::$app->security->validatePassword($password, $this->PASSWORD_HASH);
    }

    /**
     * Generates password hash from password and sets it to the model
     * @param $password
     * @throws \yii\base\Exception
     */
    public function setPassword($password)
    {
        $this->PASSWORD_HASH = Yii::$app->security->generatePasswordHash($password);
    }

    /**
     * Generates "remember me" authentication key
     * @throws \yii\base\Exception
     */
    public function generateAuthKey()
    {
        $this->AUTH_KEY = Yii::$app->security->generateRandomString();
    }

    /**
     * Generates new password reset token
     * @throws \yii\base\Exception
     */
    public function generatePasswordResetToken()
    {
        $this->PASSWORD_RESET_TOKEN = Yii::$app->security->generateRandomString() . '_' . Date::nowTime();
    }

    /**
     * Removes password reset token
     */
    public function removePasswordResetToken()
    {
        $this->PASSWORD_RESET_TOKEN = null;
    }
}