<?php

namespace app\admin\model;

use app\BaseModel;
use think\facade\Lang;

class Config extends BaseModel
{

    protected $autoWriteTimestamp = true;
    protected $createTime = 'created_at';
    protected $updateTime = 'updated_at';
    // protected $json = ['val'];
    // protected $jsonAssoc = true;
    
    public static function getSelect($language_code, $select = true) {
        Lang::setLangSet($language_code);
        $data = [
            'kefu_chat_type' => [
                '1' => Lang::get('顺序分配')
            ],
            'user_vip_level' => [
                '1' => '1',
                '2' => '2',
                '3' => '3',
                '4' => '4',
                '5' => '5',
                '6' => '6',
                '7' => '7',
                '8' => '8',
                '9' => '9',
            ]
        ];
        if ($select) {
            foreach ($data as &$item) {
                $item = getSelectData($item,'value', 'label', 1);
            }
        }
        return $data;
    }

    //字段val如果是json格式，转换为数组
    // public function getValAttribute($value)
    // {
    //     return $value ? json_decode($value, true) : '';
    // }

    //获取指定配置的数据
    public static function getFieldValue($field, $language_code = '')
    {
        $where['field'] = $field;
        if($language_code){
            $where['language_code'] = $language_code;
        }
        $config = self::where($where)->find();
        if (!empty($config['type']) && $config['type'] == 'rich_text') {
            return $config['val'] ? json_decode($config['val'], true) : '';
        }
        return $config['val'];
    }

    //获取配置数据
    public static function getConfigData($fields, $flag = 1) 
    {
        if (!empty($fields)) {
            $list = Config::whereIn('field',$fields)->select();
        } else {
            $list = Config::where('flag',$flag)->whereIn('field',$fields)->select();
        }
        $data = [];
        foreach ($list as $item) {
            if ($item['type'] == 'rich_text') {
                $item['val'] = $item['val'] ? json_decode($item['val'], true) : '';
            }
            $data[$item['field']] = $item['val'];
        }
        return $data;
    }

    //获取客服接线数量的上限配置
    public static function getKefuChatMax()
    {
        //先从缓存中读取config表获取客服接线数量的上限配置
        $kefu_chat_max = cache('config_kefu_chat_max');
        if ($kefu_chat_max) {
            return $kefu_chat_max;
        }
        
        $kefu_chat_max = (int)Config::where('field','kefu_chat_max')->value('val');
        $kefu_chat_max = $kefu_chat_max ? $kefu_chat_max : 1;
        cache('config_kefu_chat_max', $kefu_chat_max);
        return $kefu_chat_max;
    }
}