<?php

namespace app\controller\manager;

use app\repository\CmsRepository;
use app\model\Log;
use app\model\Category as CategoryModel;

use Exception;
use think\facade\Db;
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 Category
 * @package app\controller\manager
 */
class Category extends Base
{
    /**
     * 编辑
     *
     * @return Json|View
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @throws Exception
     */
    public function edit()
    {
        $id = input('id/d', 0);

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

        if ($this->request->isPost()) {
            $item     = input('post.');
            $validate = $this->validateByApi($item, [
                'pid|父级分类' => 'require|number',
                'name|标题'  => 'require|max:100|unique:disease,name,'.$id,
            ]);

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

            Db::startTrans();
            try {
                $oldPath      = $info['path'] ?? '';
                $item['path'] = CategoryModel::getPath($item['pid']);
                $info->save($item);

                //刷新所有路径
                $oldPath = $oldPath.','.$id;
                $newPath = $item['path'].','.$id;
                if ($oldPath != $newPath) {
                    CategoryModel::refreshPath();
                }
                Db::commit();
                return $this->json();
            } catch (ValidateException $e) {
                Db::rollback();
                return $this->json(4001, $e->getError());
            }
        }

        $disabled                = CategoryModel::getAllChildrenIds($id);
        $disabled[]              = $id;
        $this->data['jsonList']  = $this->categoryJson([$info['pid']], $disabled);
        $this->data['item']      = $info;

        return $this->view();
    }

    /**
     * 添加
     *
     * @return Json|View
     * @throws Exception
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $item     = input('post.');
            $validate = $this->validateByApi($item, [
                'pid|父级分类'  => 'require|number',
                'name|标题' => 'require|max:100',
            ]);

            if ($validate !== true) {
                return $validate;
            }
            try {
                CategoryModel::create($item);
                return $this->json();
            } catch (ValidateException $e) {
                return $this->json(4001, $e->getError());
            }
        }

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

        return $this->view();
    }


    /**
     * 删除
     * @return Json
     */
    public function del()
    {
        if (!$this->request->isPost()) {
            return $this->json(4000, '非法请求');
        }

        $ids = $this->request->param('ids/a', []);
        if(!empty(CategoryModel::findOne([["pid","in",$ids]]))){
            return $this->json(5001,"该栏目还有下级 不能删除");
        }
        CategoryModel::destroy($ids);
        return $this->json();
    }

    /**
     * 列表
     *
     * @return Json|View
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function index()
    {
        if ($this->request->isPost()) {
            $menus = CategoryModel::getList();
            $res   = [
                'code'  => 0,
                'msg'   => 'success',
                'count' => $menus->count(),
                'data'  => $menus->toArray(),
            ];
            return json($res);
        }
        return $this->view();
    }

    /**
     * @param  array  $selected
     * @param  array  $disabled
     * @return false|string
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    private function categoryJson(array $selected = [], array $disabled = [])
    {
        $categoryList[] = ['name' => '顶级分类', 'id' => 0, 'disabled' => false, 'selected' => in_array(0, $selected)];
        $list           = CategoryModel::getListByPid();
        $list           = $list->toArray();
        foreach ($list as $k => $m) {
            $list[$k]['selected'] = in_array($m['id'], $selected);
            $list[$k]['disabled'] = in_array($m['id'], $disabled);
        }
        $list         = CmsRepository::getInstance()->buildMenuChild(0, $list);
        $categoryList = array_merge($categoryList, CmsRepository::getInstance()->handleSelectedList($list));
        return json_encode($categoryList, JSON_UNESCAPED_UNICODE);
    }
}