<?php

namespace Application\Controller;

use Application\Common\Enum;
use Application\Common\StatusCode;
use Application\Form\item\FormForm;
use Application\Mvc\Controller\BasicController;
use Application\Service\DB\Db;
use Application\Service\Extension\Formatter\Formatter;
use Application\Service\Extension\Formatter\FormFormatter;
use Application\Service\Extension\Formatter\FormViewFormatter;
use Application\Service\Extension\Helper\ArrayHelper;
use Application\Service\Extension\Laminas;
use Application\Service\Extension\Validator\ValidatorApplication;
use Application\Service\Logs;
use Exception;
use Laminas\View\Model\JsonModel;

/**
 * 字典项设置 - 表单设置
 */
class FormController extends BasicController
{
    /** @var string 表单字段配置key */
    public const FORM_VALIDATOR = 'DictionaryForm';

    public const LOG_TARGET = 'DictionaryForm';

    /**
     * 获取表单设置列表
     * @doc https://www.showdoc.com.cn/p/757c59c613bc3c71675699d33694c165
     * @url http://xx.com/dictionary/form
     * @return JsonModel
     */
    public function indexAction(): JsonModel
    {
        // 表单类型id
        $form_group_id = $this->params()->fromPost('form_group_id', '');
        // 表单tpye
        $form_type = $this->params()->fromPost('form_type', '');
        // 表单检索条件
        $formWhereArr = ['is_del' => 0];
        if($form_group_id) $formWhereArr['group_id'] = $form_group_id;
        if($form_type !== '') $formWhereArr['type'] = $form_type;

        $data = $this->LocalService()->dictionaryForm->fetchAllWithPagination([
            'order' => ['order ASC'],
            'columns' => ['id as parent', 'id', 'group_id', 'name', 'type', 'order'],
            'where' => $formWhereArr
        ]);

        Formatter::format($data['data'], new FormFormatter());

        return $this->RenderApiJson()->Success($data['data'], 'OK', [
            'total' => $data['count']
        ]);
    }

    /**
     * 创建表单
     * @doc https://www.showdoc.com.cn/p/e0d7e9989e501ccbfd039af9d025e572
     * @url http://xx.com/dictionary/form/create
     * @return JsonModel
     * @throws Exception
     */
    public function createAction(): JsonModel
    {
        $validator = new ValidatorApplication();
        $validator->attach(
            [[], 'form', 'config' => self::FORM_VALIDATOR],
            [['reference_file'], 'default', 'value' => '[]'],
            [['group_id'], 'exist', 'targetClass' => $this->LocalService()->dictionaryFormGroup, 'targetAttribute' => 'id'],
            [['name'], 'function', 'targetClass' => \Application\Form\FormForm::class, 'method' => 'invalidCreateName'],
            [['checklist_id'], 'function', 'targetClass' => \Application\Form\FormForm::class, 'method' => 'invalidCheckListId'],
        );

        if (!$validator->isValid()) {
            return $this->RenderApiJson()->Error(StatusCode::E_FIELD_VALIDATOR, $validator->getFirstErrorToString());
        }

        $model = new \Application\Form\FormForm($validator);
        if ($validator->attributes['id']) {
            $model->editForm();
            $this->LocalService()->log->saveFileLog($this->validator->attributes['id'], self::LOG_TARGET . '.form', $this->validator->attributes, Logs::OPERATE_EDIT, '编辑表单');
        } else {
            $this->LocalService()->log->saveFileLog($model->createForm(), self::LOG_TARGET . '.form', $this->validator->attributes, Logs::OPERATE_CREATE, '创建表单');
        }

        return $this->RenderApiJson()->Success();
    }

    /**
     * 表单详情
     * @doc https://www.showdoc.com.cn/p/e4c896652e7ae80c5560851e8ec8c171
     * @url http://xx.com/dictionary/form/view
     * @return JsonModel
     * @throws Exception
     */
    public function viewAction(): JsonModel
    {
        $validator = new ValidatorApplication();

        $query = $this->LocalService()->dictionaryForm->fetchOne([
            'columns' => [
                'id', 'group_id', 'name', 'type', 'order', 'is_required', 'checklist_id', 'finish_condition',
                'is_show', 'show_type', 'reference_file', 'rdg_type', 'var_name', 'can_patient_write', 'is_handwritten_signature',
                'ds_stage','identification_edit'
            ],
            'where' => ['id' => $validator->attributes['id']]
        ]) ?: ['order' => $this->getOrder()];

        Formatter::format($query, new FormViewFormatter());

        return $this->RenderApiJson()->Success($query, 'OK', [
            'FormFileData' => ($this->getFieldConfig())
        ]);
    }

    /**
     * 删除表单
     * @doc https://www.showdoc.com.cn/p/2ed2ef0a8894ed47b8226d6daed08634
     * @url http://xx.com/dictionary/form/del
     * @return JsonModel
     * @throws Exception
     */
    public function delAction(): JsonModel
    {
        $validator = new ValidatorApplication();

        $this->LocalService()->dictionaryForm->update([
           'is_del' => 1
        ], [
            'id' => $validator->attributes['id']
        ]);

        $this->LocalService()->dictionaryFormField->update([
            'is_del' => 1
        ], [
            'form_id' => $validator->attributes['id']
        ]);

        $this->LocalService()->log->saveFileLog($this->validator->attributes['id'], self::LOG_TARGET . '.form', $this->validator->attributes, Logs::OPERATE_DELETE, '删除表单');
        return $this->RenderApiJson()->Success();
    }

    /**
     * 获取字典项页面表单配置
     * @return mixed
     */
    protected function getFieldConfig(string $formValidator = self::FORM_VALIDATOR)
    {
        $config = include Laminas::$app->getConfig()['formValidator'][$formValidator];
        $config['form'] = array_values($config['form']);

        return $config;
    }

    protected function getOrder()
    {
        return $this->LocalService()->dictionaryForm->getMaxOrder('order');
    }

    /**
     * 表单预览页面~
     */
    public function previewAction()
    {
        $id = $this->params()->fromPost('id');

        if (!$id) {
            return $this->RenderApiJson()->Error(StatusCode::E_FIELD_VALIDATOR, '请传入正确的参数');
        }

        $query = $this->LocalService()->dictionaryForm->fetchOne([
            'where' => ['id' => $id]
        ]);

        return $this->RenderApiJson()->Success(ArrayHelper::merge($this->LocalService()->dictionaryForm->getPreviewConfig($id), [
            'type' => $query['type'],
            'show_type' => $query['show_type'] ?: 'right',
        ]));
    }

    /**
     * 选择表单列表
     */
    public function copyAction()
    {
        $this->validator->attach(
            [['item_id'], 'required']
        );

        if (!$this->validator->isValid()) {
            return $this->RenderApiJson()->Error(StatusCode::E_FIELD_VALIDATOR, $this->validator->getFirstErrorToString());
        }

        $model = new \Application\Form\FormForm($this->validator);
        $data = $model->getCopyList();
        return $this->RenderApiJson()->Success($data['data'], 'OK', [
            'total' => $data['total']
        ]);
    }

    /**
     * 选择表单
     * @url
     * @doc
     * @return JsonModel
     * @throws Exception
     */
    public function copyToAction(): JsonModel
    {
        $this->validator->attach(
            [['id', 'item_id'], 'required'],
            [['id'], 'exist', 'targetClass' => $this->LocalService()->dictionaryForm, 'targetAttribute' => ['id']],
            [['item_id'], 'exist', 'targetClass' => $this->LocalService()->itemInfo, 'targetAttribute' => ['id']],
            [['id'], 'function', 'targetClass' => \Application\Form\FormForm::class, 'method' => 'invalidCopyId']
        );

        if (!$this->validator->isValid()) {
            return $this->RenderApiJson()->Error(StatusCode::E_FIELD_VALIDATOR, $this->validator->getFirstErrorToString());
        }

        $model = new \Application\Form\FormForm($this->validator);
        $model->copyTo();
        return $this->RenderApiJson()->Success();
    }
}
