<?php
/**
 * raingad IM [ThinkPHP6]
 * @author xiekunyu <raingad@foxmail.com>
 */
namespace app\manage\model;

use app\BaseModel;
use think\facade\Cache;
class Config extends BaseModel
{
    // protected $json = ['val'];
    // protected $jsonAssoc = true;
    
    public static function autoTask(){
        $autoTask=Config::getFieldValue('autoTask');
        if($autoTask){
            return $autoTask;
        }
    }
    public static function changeList($list) {
        foreach($list as &$item) {
            $item['name'] = $item['field'];
            $item['value'] = $item['val'];
        }
        return $list;
    }
    // 获取系统配置信息
    public static function getSystemInfo($update=false){
        $name='systemInfo';
        // $auth=request()->header('Authorization');
        $nameFields=['sysInfo','fileUpload','chatInfo','compass','kefu_cancel_message','user_open_comment', 'user_open_special_comment', 'user_send_gap_time', 'user_open_speech', 'user_show_kefu_read','user_cancel_message','user_cancel_message_time','platform_head_logo','platform_head_logo_night','pc_title_color','platform_logo','platform_name','platform_logo_night'];
        // 如果是登录状态才会返回chatINfo
        // if($auth){
        //     $name='all'.$name;
        //     $nameFields[]="chatInfo";
        // }
        if(Cache::has($name) && !$update){
            $systemInfo=Cache::get($name);
        }else{
            $systemInfo=[];
            $conf=Config::where([['field','in',$nameFields]])->select()->toArray();
            foreach($conf as $v){
                $value=[];
                if ($v['type'] == 'rich_text') {
                    $v['val'] = json_decode($v['val'], true);
                }
                if($v['field']=='fileUpload'){
                    $value['size'] = $v['val']['size'];
                    $value['preview'] = $v['val']['preview'];
                    $value['fileExt'] = $v['val']['fileExt'];
                }else{
                    $value=$v['val'];
                }
                $systemInfo[$v['field']]=$value;
            }
            Cache::set($name,$systemInfo,7*86400);
        }
        return $systemInfo;
    }

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