<?php


namespace app\controller\manager;

use app\model\Log;
use Exception;
use app\model\ArchivesModelField as MArchivesModelField;
use app\model\ArchivesModel;
use think\exception\ValidateException;
use think\response\Json;
use think\response\View;

/**
 * 文档模型字段管理
 * Class ArchivesModelField
 * @package app\controller\manager
 */
class ArchivesModelField 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');
            }

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

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

            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;

        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 = MArchivesModelField::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()
    {
        $modelId = input('model_id/d', 0);

        if ($this->request->isPost()) {
            $item             = input('post.');
            $item['model_id'] = $modelId;

            $validate = $this->validateByApi($item, [
                'title|字段标题'  => 'require',
                'model_id|模型' => 'require|number|gt:0',
                'name|字段标识'   => 'require|alphaDash|unique:archives_model_field',
            ], ['model_id.gt' => '模型不存在']);

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

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

        $this->data['modelId'] = $modelId;

        return $this->view();
    }

    /**
     * 列表
     *
     * @return View|Json
     * @throws Exception
     */
    public function index()
    {
        $modelId = input('model_id/d', 0);
        if (!$modelId) {
            return $this->json(4001, '请选择正确的模型');
        }

        if ($this->request->isPost()) {
            $page    = input('page/d', 1);
            $limit   = input('size/d', 20);
            $where[] = ['model_id', '=', $modelId];
            $items   = MArchivesModelField::findList($where, [], $page, $limit, function ($q) {
                return $q->order('status', 'desc')->order('id', 'asc');
            });

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

        $this->data['modelId'] = $modelId;

        return $this->view();
    }

    /**
     * 同步字段
     *
     * @return Json
     * @throws Exception
     */
    public function sync(): Json
    {
        if ($this->request->isPost()) {
            $modelId = input('model_id/d', 0);

            if (!$modelId) {
                return $this->json(4001, '模型错误');
            }


            if (!$info = ArchivesModel::findOne(['id' => $modelId])) {
                return $this->json(4001, '模型不存在');
            }

            try {
                MArchivesModelField::syncFieldList($modelId, $info['name']);
                return $this->json();
            } catch (ValidateException $e) {
                return $this->json(4001, $e->getError());
            }
        }
        return $this->json(4000, '非法请求');
    }
}