<?php

namespace app\controller\manager;

use app\repository\CmsRepository;

use app\model\Area as AreaModel;

use think\exception\ValidateException;
use think\response\Json;
use think\response\View;

/**
 * 地域管理
 *
 * Class Menu
 * @package app\controller\manager
 */
class Area extends Base
{
    /**
     * 列表
     *
     * @return View|Json
     */
    public function index()
    {
        if ($this->request->isPost()) {
            $menus = AreaModel::getAllList();
            $res = [
                'code'  => 0,
                'msg'   => 'success',
                'count' => $menus->count(),
                'data'  => $menus->toArray(),
            ];
            return json($res);
        }
        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, [
                'field' => 'require',
                'value' => 'require',
            ]);

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

            if (!$info = AreaModel::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, '非法请求');
    }

}