<?php

namespace app\admin\controller;

use app\admin\common\AdminController;
use think\facade\Db;

/**
 * Description of SysConfig
 *
 * @author sgq
 */
class SysConfig extends AdminController {

    private $valid_key = ["register"];

    public function index() {
        if ($this->request->isPost()) {
            $params = $this->request->param();
            $data = [];
            foreach ($params as $key => $value) {
                if (in_array($key, $this->valid_key)) {
                    $_config = Db::table("sys_config")->where("key", $key)->find();
                    if ($_config) {
                        $data[] = ["id" => $_config["id"], "value" => json_encode($value), "updateTime" => date("Y-m-d H:i:s"), "updateUser" => session("user")["uid"]];
                    } else {
                        $data[] = ["key" => $key, "value" => json_encode($value), "createTime" => date("Y-m-d H:i:s"), "createUser" => session("user")["uid"]];
                    }
                }
            }
            $model = new \app\common\model\SysConfig();
            $model->saveAll($data);
            $res = ["code" => 200, "msg" => "保存成功"];
            echo sprintf("<script>parent.SysConfig.callback(%s);</script>", json_encode($res));
            exit;
        }
        $configs = \think\facade\Db::table("sys_config")->select();
        $tmp = [];
        foreach ($configs as $config) {
            $tmp[$config["key"]] = json_decode($config["value"], true);
        }unset($config);
        return view("", ["config" => $tmp]);
    }

}
