<?php


namespace app\controller\manager;

use app\model\Log;
use app\repository\CmsRepository;
use Exception;
use app\model\Config as ConfigModel;
use app\model\ConfigGroup as ConfigGroupModel;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\exception\ValidateException;
use think\response\Json;
use think\response\View;

/**
 * 配置项
 * Class ConfigItem
 * @package app\controller\manager
 */
class ConfigItem extends Base
{
    /**
     * 删除
     *
     * @return Json
     */
    public function del(): Json
    {
        if ($this->request->isPost()) {
            $ids = input('post.ids/a', []);
            if (empty($ids)) {
                $ids[] = input('post.id/d');
            }

            ConfigModel::deleteByIds($ids);

            Log::write(get_class().'Del', 'del', '涉及到的ID为：'.implode(',', $ids));
            return $this->json();
        }
        return $this->json(4001, '非法请求!');
    }

    /**
     * 编辑
     *
     * @return Json|View
     * @throws Exception
     */
    public function edit()
    {
        $id = input('id/d', 0);

        if (!$info = ConfigModel::findById($id)) {
            return $this->json(4001, '记录不存在');
        }

        if ($this->request->isPost()) {
            $item     = input('post.');
            $validate = $this->validateByApi($item, [
                'title|配置标题' => 'require',
                'group|配置分组' => 'require|alphaDash',
                'value|配置值' => 'require',
            ]);

            if ($validate !== true) {
                return $validate;
            }

            try {
                $info->save($item);
                return $this->json();
            } catch (ValidateException $e) {
                return $this->json(4001, $e->getError());
            }
        }

        $this->data['item'] = $info;
        $this->data['jsonList'] = $this->categoryJson([$info['group']]);

        return $this->view();
    }

    /**
     * 单个字段编辑
     *
     * @return Json
     * @throws Exception
     */
    public function modify(): Json
    {
        if ($this->request->isPost()) {
            $item     = input('post.');
            $validate = $this->validateByApi($item, [
                'field' => 'require',
                'value' => 'require',
            ]);

            if ($validate !== true) {
                return $validate;
            }

            if (!$info = ConfigModel::findById($item['id'])) {
                return $this->json(4001, '记录不存在');
            }

            $update = [$item['field'] => $item['value']];

            try {
                $info->save($update);
                return $this->json();
            } catch (ValidateException $e) {
                return $this->json(4001, $e->getError());
            }
        }
        return $this->json(4000, '非法请求');
    }

    /**
     * 添加
     *
     * @return Json|View
     * @throws Exception
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $item = input('post.');

            $validate = $this->validateByApi($item, [
                'title|配置标题' => 'require',
                'group|配置分组' => 'require|alphaDash',
                'name|配置变量名' => 'require|alphaDash|unique:config',
            ]);

            if ($validate !== true) {
                return $validate;
            }

            try {
                ConfigModel::create($item);
                return $this->json();
            } catch (ValidateException $e) {
                return $this->json(4001, $e->getError());
            }
        }

        $this->data['jsonList'] = $this->categoryJson();
        return $this->view();
    }

    /**
     * 列表
     *
     * @return View|Json
     * @throws Exception
     */
    public function index()
    {
        if ($this->request->isPost()) {
            $page  = input('page/d', 1);
            $limit = input('size/d', 20);

            $searchParams = input('searchParams');
            $where        = [];
            if ($searchParams) {
                foreach ($searchParams as $key => $param) {
                    if (!empty($param)) {
                        if (is_string($param)) {
                            $where[] = [$key, 'like', '%'.$param.'%'];
                        } elseif (is_array($param)) {
                            $where[] = [$key, 'in', $param];
                        }
                    }
                }
            }

            $items = ConfigModel::findList($where, [], $page, $limit, function ($q) {
                return $q->order('sort', 'desc')->order('id', 'asc');
            });

            return $this->json(0, '操作成功', $items);
        }

        $this->data['categoryJson'] = json_encode($this->zTree(), JSON_UNESCAPED_UNICODE);

        return $this->view();
    }

    /**
     * @param  array  $selected
     * @return false|string
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    private function categoryJson(array $selected = [])
    {
        $menus = $this->zTree($selected);
        $categoryList = CmsRepository::getInstance()->handleSelectedList($menus);
        return json_encode($categoryList, JSON_UNESCAPED_UNICODE);
    }

    /**
     * @param  array  $selected
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    private function zTree(array $selected = []): array
    {
        $menus          = ConfigGroupModel::field('id,0 as pid,title,name,sort,true as open')
            ->order('sort', 'desc')
            ->order('id', 'asc')
            ->select()->toArray();
        foreach ($menus as $k => $m) {
            $menus[$k]['selected'] = in_array($m['name'], $selected);
            $menus[$k]['disabled'] = in_array($m['name'], []);
        }

        return CmsRepository::getInstance()->buildMenuChild(0, $menus);
    }
}