<?php

namespace common\models;

use common\helpers\Cache;
use Yii;

/**
 * This is the model class for table "{{%FREE_TEMPLATE}}".
 *
 * @property string ID
 * @property string country_id 国家ID
 * @property int freight 运费
 * @property int free_shipping 免运费阈值
 * @property int created_at 创建时间
 * @property int updated_at 更新时间
 */
class FreeTemplate extends \common\components\ActiveRecord
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return '{{%FREE_TEMPLATE}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['country_id',  'freight', 'free_shipping'], 'required'],
            [['freight', 'free_shipping'], 'number'],
            [['country_id'], 'unique'],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'ID' => 'ID',
            'country_id' => '国家ID',
            'freight' => '运费',
            'free_shipping' => '免运费阈值',
            'created_at' => '创建时间',
            'updated_at' => '更新时间',
        ];
    }

    public function country()
    {
        return $this->hasOne(Countries::class, ['id' => 'country_id']);
    }

    /**
     * 从缓存获取信息
     * @return array|mixed|\yii\db\ActiveRecord[]
     */
    public static function getFromCache()
    {
        $data = Yii::$app->cache->get(Cache::FREE_TEMPLATE_KEY);
        Yii::$app->cache->delete(Cache::FREE_TEMPLATE_KEY);
        if (!$data) {
            // 获取信息
            $data = self::getAllData();
            Yii::$app->cache->set(Cache::FREE_TEMPLATE_KEY, $data);
        }

        return $data;
    }

    /**
     * @return array|\yii\db\ActiveRecord[]
     */
    public static function getAllData()
    {
        return static::find()->indexBy('ID')->orderBy('ID ASC')->asArray()->all();
    }

    /**
     *  更新缓存
     * @return array|\yii\db\ActiveRecord[]
     */
    public static function updateToCache()
    {
        // 获取配置
        $data = self::getAllData();
        Yii::$app->cache->set(Cache::FREE_TEMPLATE_KEY, $data);
        return $data;
    }

    /**
     * 通过$countryId获取
     * @param string $countryId
     * @return array|null
     */
    public static function getByCountryId(string $countryId): ?array
    {
        return self::findOneAsArray('country_id=:country_id', [':country_id' => $countryId]);
    }

    public static function deleteOne(string $countryId): bool
    {
        return self::deleteAll('country_id=:country_id', [':country_id' => $countryId]);
    }
}
