<?php

namespace app\controller\manager;

use app\repository\CmsRepository;
use app\model\Tag as TagModel;

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 ConsumerTag extends Base
{
    /**
     * 编辑
     *
     * @return Json|View
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @throws Exception
     */
    public function edit()
    {
        $id = input('id/d', 0);

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

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

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

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

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

        return $this->view();
    }

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

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

            if (!$info = TagModel::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, [
                'pid|父级分类'  => 'require|number',
                'name|标题' => 'require|max:100',
            ]);

            if ($validate !== true) {
                return $validate;
            }
            try {
                TagModel::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(TagModel::findOne([["pid","in",$ids]]))){
            return $this->json(5001,"该栏目还有下级 不能删除");
        }
        TagModel::destroy($ids);
        return $this->json();
    }

    /**
     * 列表
     *
     * @return Json|View
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function index()
    {
        if ($this->request->isPost()) {
            $menus = TagModel::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           = TagModel::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);
    }
}