<?php

namespace common\models;

use common\helpers\Cache;
use Yii;

/**
 * This is the model class for table "{{%LANGUAGES}}".
 *
 * @property string $ID
 * @property string $NAME 名字
 * @property string $CODE 简码
 * @property string KEY KEY
 * @property string LOCAL_CODE 简码
 * @property int $ORDER 排序
 * @property int $ACTIVE 状态
 * @property int $CREATED_AT 创建时间
 * @property int $UPDATED_AT 更新时间
 */
class Language extends \common\components\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%LANGUAGES}}';
    }

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

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'ID' => 'ID',
            'NAME' => '名字',
            'KEY' => 'KEY',
            'LOCAL_CODE' => '简码',
            'ORDER' => '排序值',
            'ACTIVE' => '状态：1正常 0异常',
            'LANGUAGE_KEY' => '语言KEY',
            'CREATED_AT' => '创建时间',
            'UPDATED_AT' => '更新时间',
        ];
    }

    /**
     * 从缓存获取信息
     * @return array|mixed|\yii\db\ActiveRecord[]
     */
    public static function getFromCache()
    {
        $data = Yii::$app->cache->get(Cache::LANGUAGE_KEY);
        Yii::$app->cache->delete(Cache::LANGUAGE_KEY);
        if (!$data) {
            // 获取信息
            $data = self::getAllData();
            Yii::$app->cache->set(Cache::LANGUAGE_KEY, $data);
        }
        // i18n转换
//        foreach ($data as &$item) {
//            $item['COUNTRY_NAME'] = Yii::t('ctx', $item['LANGUAGE_KEY']);
//        }

        return $data;
    }

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

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

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

    public static function getEn()
    {
        $data = self::findOneAsArray('ID=:ID', [':ID' => '620713695651307520']);
        return $data['ID'];
    }
}
