<?php

namespace common\models;

use common\behaviors\SoftDeleteBehavior;
use common\enums\StatusEnum;
use yii\behaviors\BlameableBehavior;
use yii\behaviors\TimestampBehavior;

/**
 * This is the model class for table "{{%vote}}".
 *
 * @property int $id
 * @property string $entity
 * @property string $entity_id
 * @property int $user_id
 * @property int $created_at
 * @property int $updated_at
 * @property int $status
 */
class Footprint extends \yii\db\ActiveRecord
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return '{{%footprint}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['entity', 'entity_id'], 'required'],
            [['user_id', 'entity_id'], 'integer'],
            [['entity'], 'string', 'max' => 255],
            ['status', 'default', 'value' => StatusEnum::STATUS_ON],
            [['user_id'], 'safe']
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'entity' => 'entity',
            'user_id' => 'User ID',
            'created_at' => 'Created At',
            'updated_at' => 'Updated At',
        ];
    }

    public function behaviors()
    {
        return [
            TimestampBehavior::className(),
            [
                'class' => SoftDeleteBehavior::className(),
                'softDeleteAttributeValues' => [
                    'updated_at' => time(),
                    'status' => StatusEnum::STATUS_OFF,
                ],
                'invokeDeleteEvents' => false // 不触发删除相关事件
            ],
            [
                'class' => BlameableBehavior::className(),
                'createdByAttribute' => 'user_id',
                'updatedByAttribute' => false,
            ],
        ];
    }

    /**
     * @return query\FootprintQuery|\yii\db\ActiveQuery
     * @author nodelog
     */
    public static function find()
    {
        return new \common\models\query\FootprintQuery(get_called_class());
    }

    /**
     * 添加访问记录
     * @author nodelog
     */
    public static function add($entity, $entity_id)
    {
        if (!\Yii::$app->user->isGuest) {
            $model = new Footprint();
            $model->entity = $entity;
            $model->entity_id = $entity_id;
            return $model->save();
        }

        return false;
    }
}
