<?php
/**
 * Created by PhpStorm.
 * User: leo
 * Date: 2018/2/24
 * Time: 下午1:02
 */

namespace frontendApi\modules\v1\models;

use common\components\Redis;
use common\helpers\Date;
use common\models\UserToken;
use Yii;
use yii\web\IdentityInterface;

class User extends \common\models\User implements IdentityInterface {
    const CACHE_IS_QUICKLY_LOGIN = 'quickly:user:';

    /**
     * @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['PAY_PASSWORD']);

        return $fields;
    }

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

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

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

    /**
     * 通过用户名获取信息并带着token表内容
     * @param $username
     * @return array
     */
    public static function findByUsernameWithToken($username) {
        $result = static::find()->select(static::tableName() . '.*,T.ACCESS_TOKEN,T.REFRESH_TOKEN,T.CREATED_AT,T.UPDATED_AT')->join('LEFT JOIN', UserToken::tableName() . ' AS T', static::tableName() . '.ID=T.USER_ID')->where(static::tableName() . '.USER_NAME=:USER_NAME', ['USER_NAME' => $username])->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');
        // upa(user_pc_access)
        return md5('u' . $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');
        // upr(user_pc_access)
        return md5('u' . $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 password_verify($password, $this->PASSWORD_HASH);
        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;
    }


    /**
     * 简单的缓存信息，此信息是在登录时缓存的
     * @return mixed
     */
    public static function isQuicklyLogin() {
        $authHeader = Yii::$app->request->getHeaders()->get('Authorization');
        if ($authHeader !== null && preg_match('/^Bearer\s+(.*?)$/', $authHeader, $matches)) {
            $token = ($matches && isset($matches[1])) ? $matches[1] : null;
            if ($token) {
                $key = Redis::key(self::CACHE_IS_QUICKLY_LOGIN . $token);
                $value = (int)Yii::$app->redis->get($key);
                return $value;
            }
        }
        return 0;
    }
}