<?php

namespace common\models;

use common\helpers\Cache;
use Yii;

/**
 * This is the model class for table "{{%CURRENCIES}}".
 *
 * @property string $ID
 * @property string $NAME 名字
 * @property string $CODE 简码
 * @property int $ACTIVE 状态
 * @property int $CREATED_AT 创建时间
 * @property int $UPDATED_AT 更新时间
 */
class Currency extends \common\components\ActiveRecord
{
    const USD = 149;

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

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['ID'], 'unique'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'ID' => 'ID',
            'NAME' => '币种',
            'CODE' => '简码',
            'ACTIVE' => '状态：1正常 0异常',
            'CREATED_AT' => '创建时间',
            'UPDATED_AT' => '更新时间',
        ];
    }

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

        return $data;
    }

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

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

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

    /**
     * 通过ID获取
     * @param string $id
     * @return string|null
     */
    public static function getNameById(string $id): ?string
    {
        $record = self::findOneAsArray('ID=:ID', [':ID' => $id]);
        return $record['NAME'] ?? '';
    }
}
