<?php

namespace common\models;

use Yii;
use yii\behaviors\TimestampBehavior;
use yii\web\IdentityInterface;
use yii\web\NotFoundHttpException;
use yii\web\UnauthorizedHttpException;

/**
 * This is the model class for table "user".
 *
 * @property int $id
 * @property string $username 用户名
 * @property string $auth_key
 * @property string $password_hash
 * @property string $password_reset_token
 * @property string $name 姓名
 * @property int $sex 性别
 * @property string $phone 联系方式
 * @property string $email 邮箱
 * @property int $role 角色
 * @property int $status 状态
 * @property string $access_token 令牌
 * @property int $expire_at 令牌过期时间
 * @property string $nickname 昵称
 * @property string $avatar 头像
 * @property string $wx_openid 微信openid
 * @property string $mini_openid 小程序openid
 * @property string $unionid 微信联合id
 * @property string $session_key 小程序会话秘钥
 * @property string $member_code 会员编号
 * @property int $exp_point 经验值
 * @property int $consume_point 消费积分
 * @property int $created_at 创建时间
 * @property int $updated_at 更新时间
 */
class User extends \yii\db\ActiveRecord implements IdentityInterface
{

    const STATUS_DELETED = 0;
    const STATUS_ACTIVE = 1;

    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'user';
    }

    public function fields()
    {
        $fields = parent::fields();
        unset($fields['auth_key']);
        unset($fields['password_hash']);
        unset($fields['password_reset_token']);
        unset($fields['role']);
        unset($fields['status']);
        unset($fields['access_token']);
        unset($fields['expire_at']);
        unset($fields['wx_openid']);
        unset($fields['mini_openid']);
        unset($fields['session_key']);
        unset($fields['created_at']);
        unset($fields['updated_at']);
        return $fields;
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['auth_key', 'password_hash'], 'required'],
            [['sex', 'role', 'status', 'expire_at', 'exp_point', 'consume_point'], 'integer'],
            [['username', 'password_hash', 'password_reset_token', 'email', 'access_token', 'avatar'], 'string', 'max' => 255],
            [['auth_key', 'wx_openid', 'mini_openid'], 'string', 'max' => 32],
            [['name', 'nickname', 'session_key'], 'string', 'max' => 120],
            [['phone'], 'string', 'max' => 13],
            [['unionid'], 'string', 'max' => 60],
            [['member_code'], 'string', 'max' => 20],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'id',
            'username' => 'username',
            'auth_key' => 'auth_key',
            'password_hash' => 'password_hash',
            'password_reset_token' => 'password_reset_token',
            'name' => 'name',
            'sex' => 'sex',
            'phone' => '联系方式',
            'email' => 'email',
            'role' => 'role',
            'status' => 'status',
            'access_token' => 'access_token',
            'expire_at' => 'expire_at',
            'nickname' => 'nickname',
            'avatar' => 'avatar',
            'wx_openid' => '公众号openid',
            'mini_openid' => '小程序openid',
            'unionid' => 'unionid',
            'session_key' => '小程序解密密钥',
            'member_code' => '会员编号',
            'exp_point' => '经验值',
            'consume_point' => '消费积分',
            'created_at' => '创建时间',
            'updated_at' => '更新时间',
        ];
    }


    /**
     * @author linyao
     * @email 602604991@qq.com
     * @created Nov 8, 2019
     *
     * 行为存储创建时间和更新时间
     */
    public function behaviors()
    {
        return [
            [
                'class' => TimestampBehavior::className(),
                'createdAtAttribute' => 'created_at',
                'updatedAtAttribute' => 'updated_at',
                'value' => function () {
                    return time();
                },
            ],
        ];
    }

    /**
     * @inheritDoc
     */
    public static function findIdentity($id)
    {
        return static::findOne(['id' => $id, 'status' => self::STATUS_ACTIVE]);
    }

    /**
     * @param mixed $token
     * @param null $type
     * @return array|\yii\db\ActiveRecord|IdentityInterface|null
     * @throws NotFoundHttpException
     * @throws UnauthorizedHttpException
     */
    public static function findIdentityByAccessToken($token, $type = null)
    {
        $user = static::find()
            ->where(['access_token' => $token, 'status' => self::STATUS_ACTIVE])
            ->one();
        if (!$user) {
            throw new NotFoundHttpException('user not found');
        }
        if ($user->expire_at < time()) {
            throw new UnauthorizedHttpException('access - token expired ', -1);
        } else {
            return $user;
        }
    }

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

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

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