<?php


namespace app\common\model;

/**
 * 配置模型类
 * @package app\common\model
 */
class Config extends Base
{
    const CODE_WECHAT = 'wechat';

    // 设置json类型字段
    protected $json = ['content'];

    /**
     * 获取配置对象
     * @param string $code
     * @return array|mixed|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getConfig($code)
    {
        $config = (new self)->where('code', $code)->cache(true, 60)->find();
        if (empty($config)) {
            $configData = [
                'code' => $code,
                'create_time' => getNow(),
                'update_time' => getNow(),
            ];

            $config = self::create($configData);
        }
        return $config;
    }

    /**
     * 获取配置数据内容
     * @param $code
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getConfigContent($code)
    {
        $config = self::getConfig($code);
        return $config->content;
    }

    /**
     * 获取配置数据中指定的值
     * @param $code
     * @param $content_code 如果读取的为json值才有效
     * @return bool|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getConfigValue($code, $content_code = '')
    {
        $content = self::getConfigContent($code);
        return $content->$content_code;
    }
}