<?php
namespace app\model;

use think\facade\Config as CConfig;

class ConfigSetting extends Base
{
    // 是否开启同步生成扩展配置文件
    const with_write_config = true;

    public static function setConfigByName(string $name, array $content)
    {
        $config = self::getConfigByName($name);

        if(empty($config)) {
            self::create([
                'name'      => $name,
                'contents'  => json_encode($content, JSON_UNESCAPED_UNICODE)
            ]);
        } else {
            self::updateById($config['id'], [
                'contents'  => json_encode($content, JSON_UNESCAPED_UNICODE)
            ]);
        }

        // 同步写入与生成配置文件
        if (self::with_write_config) {
            self::setWithExtraConfigFile($name, $content);
        }
    }

    public static function getConfigByName(string $name)
    {
        $item = self::where('name', $name)
        ->findOrEmpty()
        ->toArray();

        return self::convertContents($item);
    }

    // 通过数据库查询配置信息
    public static function getConfigContentsByName(string $name)
    {
        $item = self::getConfigByName($name);
        return $item['contents'] ?? [];
    }

    public static function convertContents(array $item)
    {
        if(empty($item)) {
            return [];
        }
        $item['contents'] = empty($item['contents']) ? [] : json_decode($item['contents'], true);
        return $item;
    }


    // 优先通过扩展配置文件查询配置信息，没有查询到再从数据库中查询
    public static function getConfigContentsWithFileByName(string $name)
    {
        $conf   = [];
        if (self::with_write_config) {
            $extraFileName  = self::parseExtraConfigFileNameByName($name);
            CConfig::load('extra/'.$extraFileName, $name);
            $conf   = config($name);
        }

        if (!empty($conf)) {
            return $conf;

        } else {
            $item = self::getConfigByName($name);
            return $item['contents'] ?? [];
        }
    }

    // 通过配置名称解析扩展配置文件名称
    public static function parseExtraConfigFileNameByName(string $name)
    {
        // extra开头
        if (substr($name, 0, 5) == 'extra') {
            $configFileName = substr($name, 5);
            // 字符串首字母转小写
            $configFileName = lcfirst($configFileName);
        } else {
            $configFileName = $name;
        }

        return $configFileName;
    }

    // 扩展配置信息写入扩展配置文件
    public static function setWithExtraConfigFile(string $name, array $content = [])
    {
        try {
            $configFileName = self::parseExtraConfigFileNameByName($name);
            if (!is_numeric($configFileName) && empty($configFileName)) {
                return false;
            }

            $extraPath      = config_path().'extra/';
            checkPathExistWithMake($extraPath);
            $configFil      = $extraPath.$configFileName.'.php';
            $configData     = var_export($content, true);

            file_put_contents($configFil, '<?php' . PHP_EOL . 'return ' . $configData . ';');

            return true;
        } catch (\Exception $e) {
            \think\facade\Log::write('请检查扩展配置文件目录config/extra是否拥有可读写权限', 'error');

            return false;
        }
    }
}