<?php

namespace app\controller\admin\system;

use app\BaseController;
use app\entity\SysConfig;
use app\service\CurdService;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\facade\Cache;
use think\response\Json;

class ConfigController extends BaseController
{
    public function list(): Json
    {
        $model = SysConfig::with([])->order(['sort'=>'asc'])
            ->withSearch(['group'], [
                'group'=> $this->request->get('group/s','')
            ]);

        $data = CurdService::getList($this->request, $model)->toArray();

//        $data = list_build_tree($list);

        return $this->writeSuccess('success', $data);
    }

    public function data(string $name)
    {
        $config = SysConfig::where('name', $name)->findOrEmpty();

        return $this->writeSuccess('success', $config->toArray());
    }
    public function existence()
    {
        $id = $this->request->get('id/d',0);
        $field = $this->request->get('field/s', '');
        $value = $this->request->get('value/s', '');
        try {
            $model = SysConfig::field('id');
            if($id > 0) {
                $model = $model->where('id', '<>', $id);
            }
            $model->where([$field => $value])->findOrFail();
        } catch (ModelNotFoundException|DataNotFoundException) {
            return $this->writeError("配置不存在");
        }
        return $this->writeSuccess('配置已存在');
    }
    public function add()
    {
        $data = $this->request->post([
            'pid'   => 0,
            'title' => '',
            'value' => '',
            'tips' => '',
            'type' => '',
            'option' => '',
            'name' => '',
            'comments' => '',
            'group'=> ''
        ]);
        $data['item_bind'] = $this->request->post('itemBind','{}');
        $data['item_style'] = $this->request->post('itemStyle','');
        $data['item_class'] = $this->request->post('itemClass','');


        $user = new SysConfig();
        $user->save($data);

        return $this->writeSuccess('添加成功');
    }

    public function update()
    {
        $data = $this->request->put([
            'id'    => 0,
            'pid'   => 0,
            'title' => '',
            'value' => '',
            'type' => '',
            'tips' => '',
            'option' => '',
            'name' => '',
            'comments' => '',
            'group'=> '',
        ]);
        $data['item_bind'] = $this->request->post('itemBind');
        $data['item_style'] = $this->request->post('itemStyle');
        $data['item_class'] = $this->request->post('itemClass');

        $user = SysConfig::findOrFail($data['id']);
        $user->save($data);

        return $this->writeSuccess('修改成功');
    }

    public function updateStatus()
    {
        $id = $this->request->put('id');
        $status = $this->request->put('status');
        $cfg = SysConfig::findOrFail($id);
        $cfg->save(['status'=>$status]);
        return $this->writeSuccess('修改成功');
    }

    public function updateSort()
    {
        $id = $this->request->put('id');
        $sort = $this->request->put('sort');
        $cfg = SysConfig::findOrFail($id);
        $cfg->save(['sort'=>$sort]);
        return $this->writeSuccess('修改成功');
    }

    public function batchDelete()
    {
        $data = $this->request->delete();
        SysConfig::destroy($data);
        return $this->writeSuccess('删除成功');
    }

    public function sync()
    {
        $lists = SysConfig::where(['status'=>1])->order(['name'=>'asc'])
            ->select();
        $version = md5($lists->toJson());

        Cache::set('sysConfigInfo', $lists->column('value','name'));
        Cache::set('sysConfigVersion', $version);// 最后的配置版本号
        return $this->writeSuccess('同步成功');
    }

    public function updateData()
    {
        $data = $this->request->put();
        foreach ($data as $name=>$value) {
            if($name) {
                $config = SysConfig::where('name', $name)->find();
                $config && $config->save(['value'=> (string)$value]);
            }
        }
        return $this->writeSuccess('更新成功', $data);
    }

    public function info()
    {
        $table_php = SysConfig::where(['status'=>1])->order(['name'=>'asc'])
            ->select();
        $table_version = md5($table_php->toJson());

        $cache_php = Cache::get('sysConfigInfo');
        $cache_version = Cache::get('sysConfigVersion');

        return $this->writeSuccess('success', [
            // 表版本
            'table_version'=> $table_version,
            'table_php'    => var_export($table_php->column('value','name'), true),
            // 缓存版本
            'cache_version'=> $cache_version,
            'cache_php'    => var_export($cache_php, true),
        ]);
    }
}