<?php

namespace app\admin\controller;

use app\BaseController;
use app\admin\model\Config as ConfigModel;
use app\admin\validate\ConfigValidate;
use Exception;
use think\facade\Db;
use think\facade\Cache;

class Config extends BaseController
{
    
    /**
     * @api {get} /config/list 系统参数列表
     *
     */
    public function list()
    {
        $flag = $this->request->param('flag', 1);
        $where['flag'] = $flag;
        if ($flag == 3) {
            $where['language_code'] = $this->request->param('language_code', $this->lang);
        }
        $list = ConfigModel::where($where)->select();
        $select = ConfigModel::getSelect($this->lang, true);
        foreach ($list as &$item) {
            if (isset($select[$item['field']])) {
                $item['select'] = $select[$item['field']];
            }
            if ($item['type'] == 'rich_text') {
                $item['val'] = $item['val'] ? json_decode($item['val'], true) : '';
            }
        }
        return $this->success(['count' => count($list), 'list' => $list]);
    }

    /**
     * @api {post} /config/update 更新系统配置
     */
    function update()
    {
        Db::startTrans();
        try {
            $id = $this->request->post('id');
            if ($id) {
                $params = (new ConfigValidate())->post()->goCheck('edit');
            } else {
                $params = (new ConfigValidate())->post()->goCheck('add');
            }
            $params['language_code'] = $this->request->post('language_code') ?? 'zh';

            if (!empty($id)) {
                $exist = ConfigModel::where('id', $id)->find();
                if (!$exist) {
                    return $this->error('配置不存在');
                }
                $params['val'] = $exist['type'] == 'rich_text' ? json_encode($params['val']) : $params['val'];
                $params['field'] = $exist['field'];
                ConfigModel::where('id', $id)->update($params);
            } else {
                $params['val'] = $params['type'] == 'rich_text' ? json_encode($params['val']) : $params['val'];
            
                ConfigModel::create($params);
            }
            Db::commit();
        } catch (Exception $e) {
            Db::rollBack();
            return $this->error($e->getMessage());
        }
        //删除缓存
        Cache::delete('systemInfo');
        //删除客服接数量上限的缓存
        if (isset($params['field']) && $params['field'] == 'kefu_chat_max') {
            Cache::delete('config_kefu_chat_max');
        }
        return $this->success();

    }

}