<?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;

class Config extends BaseController
{
    
    /**
     * @api {get} /config/list 系统参数列表
     *
     */
    public function list()
    {
        $flag = $this->request->param('flag', 1);
        $list = ConfigModel::where('flag', $flag)->select();
        $select = ConfigModel::getSelect($this->lang, false);
        foreach ($list as &$item) {
            if (isset($select[$item['field']])) {
                $item['select'] = $select[$item['field']];
            }
        }
        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'] = $params['language_code'] ?? 'zh';

            if (!empty($id)) {
                $exist = ConfigModel::where('id', $id)->find();
                if (!$exist) {
                    return $this->error('配置不存在');
                }
                ConfigModel::where('id', $id)->update($params);
            } else {
                ConfigModel::create($params);
            }
            DB::commit();
        } catch (Exception $e) {
            DB::rollBack();
            return $this->error($e->getMessage());
        }
        return $this->success();

    }

}