<?php
namespace Application\Service\DB\Dictionary;

use Application\Form\FieldForm;
use Application\Service\Extension\Helper\ArrayHelper;
use Application\Service\Extension\Laminas;
use Application\Service\Extension\ValidatorV2\RulesContainer;
use Interop\Container\ContainerInterface;

/**
 * 字典项表单字段表
 */
class FormField extends \Application\Service\DB\AbstractDb
{

    /** 文本模板 */
    public const FORM_CONFIG_TEXT = 'TEXT';

    /** 单选模板 */
    public const FORM_CONFIG_RADIO = 'RADIO';

    /** @var string 开具医嘱/化验单*/
    public const FORM_OCR_FIELD_LABORATORY_TEST = 'ISCHECK';
    /** @var string 已开具 */
    public const FORM_OCR_FIELD_LABORATORY_TEST_TRUE = 'YC';
    /** @var string 不检查 */
    public const FORM_OCR_FIELD_LABORATORY_TEST_FALSE = 'NC';
    /** @var string 化验单 */
    public const FORM_OCR_FIELD_CHECK_IMG = 'CHECKIMG';
    /** @var string 计划外检查 */
    public const FORM_OCR_FIELD_OUT_PLAN_CHECK = 'OUTPLANCHECK';
    /** @var string 备注说明 */
    public const FORM_OCR_FIELD_CHECK_REMARK = 'CHECKREMARK';


    public const FORM_FIELD_TYPE_TEXT = '1';
    public const FORM_FIELD_TYPE_DATE_UK = '2';
    public const FORM_FIELD_TYPE_DATE = '3';
    public const FORM_FIELD_TYPE_DATE_SECOND = '4';
    public const FORM_FIELD_TYPE_DATETIME = '5';
    public const FORM_FIELD_TYPE_INTEGER = '6';
    public const FORM_FIELD_TYPE_FLOAT_1 = '7';
    public const FORM_FIELD_TYPE_FLOAT_2 = '8';
    public const FORM_FIELD_TYPE_FLOAT_3 = '9';
    public const FORM_FIELD_TYPE_RADIO = '10';
    public const FORM_FIELD_TYPE_CHECKBOX = '11';
    public const FORM_FIELD_TYPE_DROPDOWN = '12';
    public const FORM_FIELD_TYPE_UPLOAD_FILE = '13';
    public const FORM_FIELD_TYPE_UPLOAD_IMAGE = '14';
    public const FORM_FIELD_TYPE_EDITOR = '15';
    public const FORM_FIELD_TYPE_TEXTAREA = '16';
    public const FORM_FIELD_TYPE_LABEL = '17';
    public const FORM_FIELD_TYPE_SPAN = '18';
    public const FORM_FIELD_TYPE_UPLOAD_SHARE_IMAGE = '19';
    public const FORM_FIELD_TYPE_DATETIME_UK = '20';
    public const FORM_FIELD_TYPE_DATETIME_SECOND_UK = '21';
    public const FORM_FIELD_TYPE_TIME_UK = '22';
    public const FORM_FIELD_TYPE_TIME_SECOND_UK = '23';
    public const FORM_FIELD_TYPE_ITEM_FORM_SOURCE = '24';
    public const FORM_FIELD_TYPE_REGION_OPTION = '25';


    public function __construct($dbAdapter, ContainerInterface $container)
    {
        if (!$this->tableName) {
            $this->tableName = 'yikeen_dictionary_form_field';
        }

        parent::__construct($dbAdapter, $container);
    }

    protected function getField($formId)
    {
        return $this->getFormVersion()->getField([
            'version' => 'v1.0',
            'form_id' => $formId,
        ]);
    }

    public function getFormData($id, string $formType = self::FORM_CONFIG_TEXT)
    {
        $field = $this->fetchOne([
            'columns' => [
                'id', 'form_id', 'name', 'type', 'order', 'parent', 'is_list','is_export',
                'is_anchor', 'is_booked_time', 'var_name', 'default', 'unit', 'rules', 'is_hyperwindow',
                'english', 'cut_pre', 'cut_after','is_csae', 'cut_start', 'cut_length', 'medical_type','checkname_id','form_field_id','default_field_id','default_field_type','is_hide','dicform_id','checktime_id','showfiled_name',
                'is_item_form_source', 'item_form_source_set','formchecktime_id','remind_type','default_checktimefield_id'
            ],
            'where' => ['id' => $id]
        ]);
        if (!$field) {
            return [];
        }

        $field['rules'] = $field['rules'] ?: '';
        $field['dicform_id'] = $field['dicform_id'] ?: '';
        if ($field['rules']) {
            /** @var RulesContainer $rulesClass */
            $rulesClass = unserialize($field['rules']);
            if ($rulesClass) {
                $field['rules'] = $rulesClass->originRules;
            }
        }

        $field['default' . $field['type']] = $field['default'];
        unset($field['default']);
//        unset($field['rules']);

        // 0 是表单选项
        if ($field['type'] == 0) {
            $formType = self::FORM_CONFIG_RADIO;
        }

        if ($formType == FieldForm::FORM_CONFIG_TEXT) {
            $attach = $this->getFormFieldText()->fetchOne([
                'columns' => ['tips', 'placeholder', 'var_name'],
                'where' => ['field_id' => $id]
            ]) ?: [];
        } elseif ($formType == FieldForm::FORM_CONFIG_RADIO) {
            $attach = $this->getFormFieldRadio()->fetchOne([
                'columns' => ['value', 'is_check', 'relation_classification', 'relation_type', 'relation_information', 'score', 'is_score'],
                'where' => ['field_id' => $id]
            ]);
        }

        if (isset($attach['relation_information']) && $attach['relation_information'] == 2) {
            $inf = $this->getFormField()->fetchAll([
                'columns' => ['id'],
                'order' => ['order ASC'],
                'where' => [
                    'id' => explode(',', $attach['relation_information'])
                ]
            ]);

            $attach['relation_information'] = ArrayHelper::getColumn($inf, 'id');
        } else {
            $attach['relation_information'] = explode(',', $attach['relation_information'] ?? '');
        }

        $field['medical_type'] = $field['medical_type'] ? explode(',', $field['medical_type']) : [];

        return ArrayHelper::merge($field, $attach);
    }

    public function buildFieldVersion()
    {

    }


    /**
     * 获取字典项表单单选模板字段表结构
     * @return FormField|mixed
     */
    protected function getFormFieldRadio()
    {
        return Laminas::$serviceManager->dictionaryFormFieldRadio;
    }

    protected function getForm()
    {
        return Laminas::$serviceManager->dictionaryForm;
    }

    protected function getFormField()
    {
        return Laminas::$serviceManager->dictionaryFormField;
    }

    /**
     * 获取字典项版本数据表结构
     * @return FormField|mixed
     */
    protected function getFormVersion()
    {
        return Laminas::$serviceManager->dictionaryFormVersion;
    }

    /**
     * 获取字典项表单文本模板字段表结构
     * @return FormField|mixed
     */
    protected function getFormFieldText()
    {
        return Laminas::$serviceManager->dictionaryFormFieldText;
    }

    /**
     * Notes: 添加需要开启CS/AE的表单内容至检查项
     * User: lltyy
     * DateTime: 2024/6/27 13:24
     *
     * @param array $info
     * @return int
     */
    public function saveFormFieldToCheck($info = []){
        $form_category = $field_check = $item_field_check = 0;
        $field_id = isset($info['field_id']) && !empty($info['field_id']) ? $info['field_id'] : 0;
        $item_id = isset($info['item_id']) && !empty($info['item_id']) ? $info['item_id'] : 0;
        if(!empty($field_id)){
            //获取字段信息
            $fieldData = $this->getFormField()->fetchOne(['where'=>[
                'is_del' => 0,
                'id' => $field_id,
            ],'columns'=>['id','name','var_name','form_id','is_csae']]);
            if(!empty($fieldData)){
                $field_csae = !empty($fieldData['is_csae']) ? $fieldData['is_csae'] : 0;
                $formData = $this->getForm()->fetchOne(['where'=> [
                    'is_del' => 0,
                    'id' => $fieldData['form_id'],
                ],'columns'=>['name','var_name']]);
                if(!empty($formData)){
                    //增加表单至检查项分类
                    $form_category = Laminas::$serviceManager->dictionaryCheckcategory->getOneFieldVal('id',[
                        'is_del' => 0,
                        'category_name' => $formData['name'],
                        'category_variable' => $formData['var_name'],
                        'is_form' => 1,
                    ]);
                    if(empty($form_category) && $field_csae == 1){
                        $max_category_order = Laminas::$serviceManager->dictionaryCheckcategory->getMaxOrder('category_order','is_del = 0');
                        $save_form_category = [
                            'category_name'=>$formData['name'],
                            'category_variable'=>$formData['var_name'],
                            'category_order'=>$max_category_order,
                            'report_type'=>0,
                            'is_form'=>1
                        ];
                        $form_category = Laminas::$serviceManager->dictionaryCheckcategory->save($save_form_category);
                        unset($max_category_order);
                        unset($save_form_category);
                        $this->getForm()->update(['checklist_id'=>$form_category],[
                            'id' => $fieldData['form_id'],
                        ]);
                    }

                    //增加表单内容至检查项
                    if(!empty($form_category)){
                        $field_check = Laminas::$serviceManager->dictionaryCheckname->getOneFieldVal('id',[
                            'is_del' => 0,
                            'category_id' => $form_category,
                            'name' => $fieldData['name'],
                            'variable' => $fieldData['var_name'],
                            'is_form' => 1,
                        ]);
                    }
                    if(empty($field_check) && $field_csae == 1){
                        $max_check_order = Laminas::$serviceManager->dictionaryCheckname->getMaxOrder('checkname_order','is_del = 0');
                        $save_check = [
                            'category_id'=>$form_category,
                            'name'=>$fieldData['name'],
                            'variable'=>$fieldData['var_name'],
                            'checkname_order'=>$max_check_order,
                            'check_type'=>5,
                            'is_form'=>1
                        ];
                        $field_check = Laminas::$serviceManager->dictionaryCheckname->save($save_check);
                        $this->getForm()->update(['checklist_id'=>$form_category],[
                            'id' => $fieldData['form_id'],
                        ]);
                        unset($max_check_order);
                        unset($save_check);
                    }

                    //判断该项目下是否存在该表单内容检查项
                    if(!empty($item_id)){
                        $item_field_check = Laminas::$serviceManager->itemCheckname->getOneFieldVal('id', [
                            'is_del' => 0,
                            'item_id' => $item_id,
                            'form_id' => $fieldData['form_id'],
                            'form_field_id' => $field_id,
                        ]);
                        if($field_csae == 1){
                            $save_itemcheck = [
                                'id'=>empty($item_field_check) ? 0 : $item_field_check,
                                'item_id'=>$item_id,
                                'category_id'=>$form_category,
                                'checkname_id'=>$field_check,
                                'name'=>$fieldData['name'],
                                'variable'=>$fieldData['var_name'],
                                'check_type'=>5,
                                'form_id'=>$fieldData['form_id'],
                                'form_field_id'=>$field_id
                            ];
                            if(empty($item_field_check)){
                                $max_itemcheck_order = Laminas::$serviceManager->itemCheckname->getMaxOrder('checkname_order',[
                                    'is_del' => 0,
                                    'item_id' => $item_id,
                                ]);
                                $save_itemcheck['checkname_order'] = $max_itemcheck_order;
                                unset($max_itemcheck_order);
                            }
                            $item_field_check = Laminas::$serviceManager->itemCheckname->save($save_itemcheck);
                            $this->getForm()->update(['checklist_id'=>$form_category],[
                                'id' => $fieldData['form_id'],
                            ]);
                            unset($save_itemcheck);
                        }else if(!empty($item_field_check) && $field_csae != 1){
                            Laminas::$serviceManager->itemCheckname->update(['is_del'=>1],[
                                'is_del' => 0,
                                'id' => $item_field_check,
                            ]);
                            $isCsaeField = $this->getFormField()->getCount([
                                'is_del' => 0,
                                'is_csae' => 1,
                                'form_id' => $fieldData['form_id'],
                            ]);
                            if(empty($isCsaeField)){
                                $this->getForm()->update(['checklist_id'=>0],[
                                    'id' => $fieldData['form_id'],
                                ]);
                            }
                            unset($isCsaeField);
                        }
                    }
                }
                unset($formData);
            }
            unset($fieldData);
        }
        return ['category_id'=>$form_category,'checkname_id'=>$field_check,'item_checkname_id'=>$item_field_check];
    }

}