<?php


namespace app\controller\manager;

use app\model\Log;
use Exception;
use app\model\ArchivesModel as MArchivesModel;
use app\model\Archives;
use app\model\ArchivesModelField;
use think\exception\ValidateException;
use think\facade\Db;
use think\response\Json;
use think\response\View;

/**
 * 文档模型管理
 * Class ArchivesModel
 * @package app\controller\manager
 */
class ArchivesModel 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');
            }
            $groupNames = MArchivesModel::whereIn('id', $ids)->column('name');
            if (ArchivesModelField::whereIn('name', $groupNames)->count() > 0) {
                return $this->json(4002, '模型下已存在字段,无法删除!');
            }

            MArchivesModel::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 = MArchivesModel::findById($id)) {
            return $this->json(4001, '记录不存在');
        }

        if ($this->request->isPost()) {
            $item     = input('post.');
            $validate = $this->validateByApi($item, [
                'title|模型标题' => 'require',
                'name|模型标识'  => 'alphaDash|unique:archives_model,name,'.$id,
            ]);

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

            try {
                ArchivesModelField::setFieldList($id, $info['name']);
                $info->save($item);
                return $this->json();
            } catch (ValidateException $e) {
                return $this->json(4001, $e->getError());
            }
        }

        $this->data['item'] = $info;

        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 = MArchivesModel::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',
                'name|模型标识'  => 'require|alphaDash|unique:archives_model',
            ]);

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

            try {
                $model = MArchivesModel::create($item);
                ArchivesModelField::setFieldList($model['id'], $model['name']);
                return $this->json();
            } catch (ValidateException $e) {
                return $this->json(4001, $e->getError());
            }
        }

        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);
            $items = MArchivesModel::findList([], [], $page, $limit, function ($q) {
                return $q->order('sort', 'desc')->order('id', 'asc');
            });

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