<?php
/**
 *
 * @author: xaboy<365615158@qq.com>
 * @day: 2017/11/23
 */

namespace crmeb\services;


use app\models\system\SystemConfig;
use crmeb\utils\Arr;
use Exception;
use Throwable;

/** 获取系统配置服务类
 * Class SystemConfigService
 * @package service
 */
class SystemConfigService
{
    protected static $configList = null;

    const CACHE_SYSTEM = 'system_config';

    /**
     * 初始化
     * @param bool $mer_id
     */
    protected static function init($mer_id = false)
    {
        $configFun = function () use ($mer_id) {
            return self::getAll($mer_id);
        };
        try {
            self::$configList = CacheService::get($mer_id ? ($mer_id . "_" . self::CACHE_SYSTEM) : (self::CACHE_SYSTEM), $configFun);
        } catch (Throwable $e) {
            try {
                self::$configList = $configFun();
            } catch (Exception $e) {
                self::$configList = [];
            }
        }
    }

    /**获取系统配置
     * @param $key
     * @param bool $mer_id
     * @return mixed|null
     */
    public static function config($key, $mer_id = false)
    {
        self::init($mer_id);
        if (self::$configList === null) self::$configList = self::getAll($mer_id);
        return self::$configList[$key] ?? null;
    }

    /**
     * 获取单个配置效率更高
     * @param $key
     * @param string $default
     * @param bool $isCaChe 是否获取缓存配置
     * @param bool $mer_id
     * @return bool|mixed|string
     */
    public static function get($key, $default = '', bool $isCaChe = false, $mer_id = false)
    {
        if ($isCaChe) {
            try {
                return SystemConfig::getConfigValue($key, $mer_id);
            } catch (Throwable $e) {
                return $default;
            }
        }

        self::init($mer_id);
        return self::$configList[$key] ?? $default;
    }

    /**
     * 获取多个配置
     * @param array $keys 示例 [['appid','1'],'appkey']
     * @param bool $isCaChe 是否获取缓存配置
     * @param bool $mer_id
     * @return array
     */
    public static function more(array $keys, bool $isCaChe = false, $mer_id = false)
    {
        self::init($mer_id);
        $callable = function () use ($keys, $mer_id) {
            try {
                $list = SystemConfig::getMore($keys, $mer_id);
                return Arr::getDefaultValue($keys, $list);
            } catch (Exception $e) {
                return Arr::getDefaultValue($keys);
            }
        };
        if ($isCaChe)
            return $callable();
        try {
            return Arr::getDefaultValue($keys, self::$configList);
        } catch (Throwable $e) {
            return $callable();
        }
    }


    /**获取全部配置不缓存
     * @param bool $mer_id
     * @return array
     */
    public static function getAll($mer_id = false)
    {
        $config = SystemConfig::getAllConfig($mer_id) ?: [];
        if (is_object($config)) {
            $config = $config->toArray();
        }
        return $config;
    }

}