<?php

namespace Application\Controller\item;

use Application\Common\StatusCode;
use Application\Form\FieldForm;
use Application\Form\item\ItemFieldForm;
use Application\Mvc\Controller\BasicController;
use Application\Service\Extension\Formatter\Formatter;
use Application\Service\Extension\Formatter\FormFormatter;
use Application\Service\Extension\Helper\ArrayHelper;
use Application\Service\Extension\Helper\StringHelper;
use Application\Service\Extension\Helper\ValidatorHelper;
use Application\Service\Extension\Laminas;
use Application\Service\Extension\Validator\ValidatorApplication;
use Application\Service\Logs;
use Exception;
use Laminas\Db\Sql\Expression;
use Laminas\Db\Sql\Predicate\In;
use Laminas\Db\Sql\Predicate\NotIn;
use Laminas\Db\Sql\Predicate\Operator;
use Laminas\Validator\Db\RecordExists;
use Laminas\Validator\Digits;
use Laminas\Validator\Exception\InvalidArgumentException;
use Laminas\Validator\InArray;
use Laminas\Validator\NotEmpty;
use Laminas\Validator\StringLength;
use Laminas\View\Model\JsonModel;
use mysql_xdevapi\CollectionModify;
use Zend\Stdlib\ArrayUtils;


class FieldController extends \Application\Controller\FieldController
{
    /** @var string 表单字段配置key */
    public const FORM_VALIDATOR = 'ItemFormField';

    public const LOG_TARGET = 'ItemFormField';

    private function addLog($eventId)
    {
        if (!is_int($eventId)) {
            $eventId = $this->validator->attributes['id'];
            $remark = '编辑项目表单字段';
            $operate = Logs::OPERATE_EDIT;
        } else {
            $remark = '新增项目表单字段';
            $operate = Logs::OPERATE_CREATE;
        }

        // 获取config 内容
        $configFile = Laminas::$app->getConfig()['formValidator'][self::LOG_TARGET];

        if (!$configFile || !file_exists($configFile)) {
            throw new InvalidArgumentException('配置文件路径不对呀。');
        }

        $configFile = include $configFile;
        $formType = $this->validator->attributes['form_type'] ?: 'TEXT';

        // 处理type内容
        $typeValue = ArrayHelper::getValue($configFile, "{$formType}.type");

        if ($typeValue) {
            $typeValue = ArrayHelper::index(array_values($typeValue)[0] ?? [], 'prop');
        }


        $eventForm = ArrayHelper::merge(ArrayHelper::getValue($configFile, "{$formType}.form"), $typeValue);

        $this->LocalService()->log->setSaveEventForm('ItemFormField')->saveFileLog(
            $eventId,
            $eventForm,
            $this->validator->attributes,
            $operate,
            $remark,
            $this->validator->attributes['item_id'] ?: 0
        );
    }

    public function indexAction(): JsonModel
    {
        $this->validator->attach(
            [['id'], 'required'],
        );
        if (!$this->validator->isValid()) {
            return $this->RenderApiJson()->Error(StatusCode::E_FIELD_VALIDATOR, $this->validator->getFirstErrorToString());
        }

        $data = $this->LocalService()->itemFormVersion->getField([
            'form_id' => $this->validator->attributes['id'],
            'version' => 'v1.0',
        ]);
        return $this->RenderApiJson()->Success($data);
    }


    public function versionAction(): JsonModel
    {
        $validator = new ValidatorApplication();
        $validator->attach(
            [['id'], 'required']
        );
        if (!$validator->isValid()) {
            return $this->RenderApiJson()->Error(StatusCode::E_FIELD_VALIDATOR, $validator->getFirstErrorToString());
        }

        // 获取所有版本
        // 新增无版本, 返回默认值
        $query = $this->LocalService()->itemFormVersion->fetchAll([
            'columns' => ['version as label', 'version as value'],
            'where' => ['form_id' => $validator->attributes['id']]
        ]) ?: [['label' => 'v1.0', 'value' => 'v1.0']];

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

    /**
     * @url http://xxx.com/item/field/create
     * @return JsonModel
     * @throws Exception
     */
    public function createAction(): JsonModel
    {
        $this->validator->attach(
            [['form_id', 'item_id'], 'required'],
            [['form_id'], 'exist', 'targetClass' => $this->LocalService()->itemForm, 'targetAttribute' => 'id'], // 验证 form_id 是否存在
            [['form_type'], 'default', 'value' => FieldForm::FORM_CONFIG_TEXT],
            [['is_list', 'is_booked_time','is_hide','dicform_id', 'is_item_form_source'], 'default', 'value' => 0],
            [['is_export'], 'default', 'value' => 1],
            [['value'], 'function', 'targetClass' => ItemFieldForm::class, 'method' => 'invalidRadioValue'],
            [['is_booked_time'], 'function', 'targetClass' => ItemFieldForm::class, 'method' => 'invalidBookedTime'],
            [['type'], 'function', 'targetClass' => ItemFieldForm::class, 'method' => 'invalidEditType'],
            [['max'], 'function', 'targetClass' => ItemFieldForm::class, 'method' => 'validMax'],
            [['var_name'], 'function', 'targetClass' => ItemFieldForm::class, 'method' => 'validVarName'],
            [['name'], 'function', 'targetClass' => ItemFieldForm::class, 'method' => 'validName'],
            [['is_hyperwindow'], 'function', 'targetClass' => ItemFieldForm::class, 'method' => 'validHyperWindow'],
        );

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

        // 前端传的 `default` 字段可能会有前缀, 需要处理一下
        $default = 'default' . $this->validator->attributes['type'];
        if (isset($this->validator->attributes[$default]) && $this->validator->attributes[$default] !== 'null') {
            $this->validator->attributes['default'] = $this->validator->attributes[$default];
        }

        if(isset($this->validator->attributes['checktime_id'])){
            if(is_array($this->validator->attributes['checktime_id'])){
                $this->validator->attributes['checktime_id'] = !empty($this->validator->attributes['checktime_id']) ? implode(',',$this->validator->attributes['checktime_id']) : '';
            }else{
                $this->validator->attributes['checktime_id'] = !empty($this->validator->attributes['checktime_id']) ? trim($this->validator->attributes['checktime_id'],',') : '';
            }
        }

        if(isset($this->validator->attributes['checkname_id'])){
            if(is_array($this->validator->attributes['checkname_id'])){
                $this->validator->attributes['checkname_id'] = !empty($this->validator->attributes['checkname_id']) ? implode(',',$this->validator->attributes['checkname_id']) : '';
            }else{
                $this->validator->attributes['checkname_id'] = !empty($this->validator->attributes['checkname_id']) ? trim($this->validator->attributes['checkname_id'],',') : '';
            }
        }

        if(isset($this->validator->attributes['formchecktime_id'])){
            if(is_array($this->validator->attributes['formchecktime_id'])){
                $this->validator->attributes['formchecktime_id'] = !empty($this->validator->attributes['formchecktime_id']) ? implode(',',$this->validator->attributes['formchecktime_id']) : '';
            }else{
                $this->validator->attributes['formchecktime_id'] = !empty($this->validator->attributes['formchecktime_id']) ? trim($this->validator->attributes['formchecktime_id'],',') : '';
            }
        }

        if(isset($this->validator->attributes['form_field_id'])){
            if(is_array($this->validator->attributes['form_field_id'])){
                $this->validator->attributes['form_field_id'] = !empty($this->validator->attributes['form_field_id']) ? implode(',',$this->validator->attributes['form_field_id']) : '';
            }else{
                $this->validator->attributes['form_field_id'] = !empty($this->validator->attributes['form_field_id']) ? trim($this->validator->attributes['form_field_id'],',') : '';
            }
        }

        //选项无关联信息时，关联分类、关联类型默认为空值
        if(isset($this->validator->attributes['relation_information']) && empty($this->validator->attributes['relation_information'])){
            $this->validator->attributes['relation_classification'] = 0;
            $this->validator->attributes['relation_type'] = 0;
        }

        $model = new ItemFieldForm($this->validator);
        if ($this->validator->attributes['id']) {
            $model->editCheck();
            //查询选项值 判断本次是否修改了表单选项的字典项 如果修改了 提示先去删除旧的选项值  再进行修改
            $childen_count = $this->LocalService()->itemFormField->getCount([
                'is_del' => 0,
                'parent' => $this->validator->attributes['id']
            ]);
            $oldform_id = $this->LocalService()->itemFormField->getOneFieldVal('dicform_id',[
                'id' => $this->validator->attributes['id'],
            ]);
            $oldform_id = !empty($oldform_id) ? $oldform_id : 0;
            if($childen_count > 0 && $this->validator->attributes['dicform_id'] != $oldform_id){
                return $this->RenderApiJson()->Error(StatusCode::E_FIELD_VALIDATOR, '请先删除旧的选项值再进行修改选项字典！');
            }

            $model->editField();
            //处理选项值
            if($childen_count == 0 && isset($this->validator->attributes['dicform_id']) && !empty($this->validator->attributes['dicform_id'])){
                //查询对应的选项值
                $where_value = [
                    'where'=> [
                        'is_del' => 0,
                        'form_id' => $this->validator->attributes['dicform_id'],
                    ],
                    'columns'=>['id','value_name','option_value','option_variable','is_score','score_value']
                ];
                $value_datas = $this->LocalService()->dictionaryLevervalue->fetchAll($where_value);
                if(!empty($value_datas)){
                    $i = 1;
                    foreach ($value_datas as $value_data){
                        $i++;
                        $res =[
                            'parent'    => $this->validator->attributes['id'],
                            'name'      => $value_data['value_name'], //选项名称
                            'var_name'  => $value_data['option_variable'], //变量名
                            'value'     => $value_data['option_value'], //选项值
                            'is_check'  => 0, //是否默认选中
                            'is_score'  => $value_data['is_score'], //分值选项
                            'score'     => $value_data['score_value'], //分值
                            'form_id'   => $this->validator->attributes['form_id'],
                            'form_type' => 'RADIO', //分值选项
                            'version'   => $this->validator->attributes['version'],
                            'order'     => $i,
                        ];
                        //print_r($res);die;
                        //选项值入库
                        $newresult_id = $model->createField($res,1);
                        $this->addLog($newresult_id);
                    }
                }
            }
            $this->addLog(null);
        } else {
            $result_id = $model->createField();
            $res = [];
            //判断是否选择了表单选项的字典项 选了的话 把选项值直接带过来保存到本次表单字段的子集中  后面的直接进行各自编辑 不再批量处理
            if(isset($this->validator->attributes['dicform_id']) && !empty($this->validator->attributes['dicform_id'])){
                //查询对应的选项值
                $where_value = [
                    'where'=> [
                        'is_del' => 0,
                        'form_id' => $this->validator->attributes['dicform_id'],
                    ],
                    'columns'=>['id','value_name','option_value','option_variable','is_score','score_value']
                ];
                $value_datas = $this->LocalService()->dictionaryLevervalue->fetchAll($where_value);

                if(!empty($value_datas)){
                    $i = 1;
                    foreach ($value_datas as $value_data){
                        $i++;
                        $res =[
                            'parent'    => $result_id,
                            'name'      => $value_data['value_name'], //选项名称
                            'var_name'  => $value_data['option_variable'], //变量名
                            'value'     => $value_data['option_value'], //选项值
                            'is_check'  => 0, //是否默认选中
                            'is_score'  => $value_data['is_score'], //分值选项
                            'score'     => $value_data['score_value'], //分值
                            'form_id'   => $this->validator->attributes['form_id'],
                            'form_type' => 'RADIO', //分值选项
                            'version'   => $this->validator->attributes['version'] ? $this->validator->attributes['version'] : 'v1.0',
                            'order'     => $i,
                        ];
                        //选项值入库
                        $newresult_id = $model->createField($res,1);
                        $this->addLog($newresult_id);
                    }
                }
            }
            $this->addLog($result_id);
        }

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

    /**
     * 添加版本
     * @doc https://www.showdoc.com.cn/p/28696c346fb0381c8b38250b30929375
     * @url http://xx.com/dictionary/field/addVersion
     * @return JsonModel
     * @throws Exception
     */
    public function addVersionAction(): JsonModel
    {
        return $this->RenderApiJson()->Success();
    }

    /**
     * 表单详情
     * @doc https://www.showdoc.com.cn/p/45af2714da57a616fcb21b118c25fa98
     * @url http://xx.com/dictionary/item/field/view
     * @return JsonModel
     * @throws Exception
     */
    public function viewAction(): JsonModel
    {
        $validator = new ValidatorApplication();
        $validator->attach(
            [['id', 'form_type'], 'required', 'strict' => true],
        );
        if (!$validator->isValid()) {
            return $this->RenderApiJson()->Error(StatusCode::E_FIELD_VALIDATOR, $validator->getFirstErrorToString());
        }

        $model = new ItemFieldForm($validator);
        if(!empty($validator->attributes['form_type']) && !empty($validator->attributes['id'])){
            if($validator->attributes['form_type'] == 'RADIO'){
                $relation_table = 'itemFormFieldRadio';
            }else{
                $relation_table = 'itemFormFieldText';
            }
            //查询关联表信息是否存在 之前的程序问题导致不会入这个表  没有的话补充一下
            $radio_count = $this->LocalService()->$relation_table->getCount([
                'field_id' => $validator->attributes['id'],
            ]);
            if(!$radio_count){
                //补充数据
                $model->editRadioCheck($validator->attributes['id']);
            }
        }
        $query = $model->view() ?: ['order' => $this->getOrder()];

        if(!isset($query['parent']) && empty($query['parent'])){
            $query['is_export'] = $query['is_export'] ?: '1';
        }
        // 数据库`score`是 decimal 类型的. 如果是整数的话不要展示小数点。
        $query['score'] = floatval($query['score']);
        $query['is_check'] = $query['is_check'] ?: '0';
        $query['is_score'] = $query['is_score'] ?: '0';
        $query['checktime_id'] = !empty($query['checktime_id']) ? explode(',',$query['checktime_id']) : [];
        $query['checkname_id'] = !empty($query['checkname_id']) ? explode(',',$query['checkname_id']) : [];
        $query['form_field_id'] = !empty($query['form_field_id']) ? explode(',',$query['form_field_id']) : [];
        $query['formchecktime_id'] = !empty($query['formchecktime_id']) ? explode(',',$query['formchecktime_id']) : [];

        $selectTableText = [
            'checktime_id'=>'',
            'checkname_id'=>'',
            'form_field_id'=>''
        ];

        //回显参照检查点信息
        if(!empty($query['checktime_id'])){
            $checktimes = $this->LocalService()->itemChecktime->fetchAll([
                'where'=> [
                    'is_del' => 0,
                    'id' => StringHelper::toArray($query['checktime_id'])
                ],
                'columns'=>['name'=>'check_name'],
                'order'=>['check_order']
            ]);
            if(!empty($checktimes)){
                $checktime_text = [];
                foreach($checktimes as $checktimeKey=>&$checktime){
                    $checktime_text[] = $checktime['name'];
                    unset($checktimes[$checktimeKey]);
                }
                $selectTableText['checktime_id'] = implode('、',$checktime_text);
                unset($checktime_text);
            }
            unset($checktimes);
        }

        //回显参照检查点信息
        if(!empty($query['formchecktime_id'])){
            $checktimes = $this->LocalService()->itemChecktime->fetchAll([
                'where'=> [
                    'is_del' => 0,
                    'id' => $query['formchecktime_id']
                ],
                'columns'=>['name'=>'check_name'],
                'order'=>['check_order']
            ]);
            if(!empty($checktimes)){
                $checktime_text = [];
                foreach($checktimes as $checktimeKey=>&$checktime){
                    $checktime_text[] = $checktime['name'];
                    unset($checktimes[$checktimeKey]);
                }
                $selectTableText['formchecktime_id'] = implode('、',$checktime_text);
                unset($checktime_text);
            }
            unset($checktimes);
        }

        //回显参照检查项信息
        if(!empty($query['checkname_id'])){
            $checknames = $this->LocalService()->itemCheckname->fetchAll([
                'where'=> [
                    'is_del' => 0,
                    'id' => StringHelper::toArray($query['checkname_id'])
                ],
                'columns'=>['category_id','name'],
                'order'=>['category_id','checkname_order']
            ]);
            if(!empty($checknames)){
                $checkname_text = [];
                $category_name_arr = $this->LocalService()->DictionaryCheckcategory->fetchCol('category_name', [
                    'is_del' => 0,
                    'id' => StringHelper::toArray(array_values(array_column($checknames,'category_id')))
                ]);
                foreach($checknames as $checknameKey=>&$checkname){
                    if(isset($category_name_arr[$checkname['category_id']]) && !empty($category_name_arr[$checkname['category_id']])){
                        $checkname['name'] = $category_name_arr[$checkname['category_id']].'-'.$checkname['name'];
                    }
                    $checkname_text[] = $checkname['name'];
                    unset($checknames[$checknameKey]);
                }
                unset($category_name_arr);
                $selectTableText['checkname_id'] = implode('、',$checkname_text);
                unset($checkname_text);
            }
            unset($checknames);
        }

        //回显参照表单信息
        if(!empty($query['form_field_id'])){
            $form_fields = $this->LocalService()->itemFormField->fetchAll([
                'where'=> [
                    'is_del' => 0,
                    'id' => StringHelper::toArray($query['form_field_id'])
                ],
                'columns'=>['form_id','name'],
            ]);
            if(!empty($form_fields)){
                $form_field_text = [];
                $form_name_arr = $this->LocalService()->itemForm->fetchCol('name',[
                    'is_del' => 0,
                    'id' => StringHelper::toArray(array_values(array_column($form_fields,'form_id')))
                ]);

                foreach($form_fields as $form_fieldkey=>&$form_field){
                    if(isset($form_name_arr[$form_field['form_id']]) && !empty($form_name_arr[$form_field['form_id']])){
                        $form_field['name'] = $form_name_arr[$form_field['form_id']].'-'.$form_field['name'];
                        $form_field_text[] = $form_field['name'];
                    }
                    unset($form_fields[$form_fieldkey]);
                }
                unset($form_name_arr);
                $selectTableText['form_field_id'] = implode('、',$form_field_text);
                unset($form_field_text);
            }
            unset($form_fields);
        }
        $FormFileData = $model->getFieldConfig();
        if(isset($FormFileData['form']) && !empty($FormFileData['form'])){
            foreach($FormFileData['form'] as &$FormFileInfo){
                if(in_array($FormFileInfo['prop'],['checktime_id','checkname_id','form_field_id','formchecktime_id'])){
                    $FormFileInfo['showText'] = $selectTableText[$FormFileInfo['prop']];
                }
            }
        }
        unset($selectTableText);
        return $this->RenderApiJson()->Success($query, 'OK', [
            'FormFileData' => $FormFileData
        ]);
    }

    /**
     * 获取order
     * @return int
     */
    protected function getOrder(): int
    {
        return ($this->LocalService()->itemFormField->getCount(['form_id' => $this->validator->attributes['form_id']]) + 1) * 10;
    }

    public function delAction(): JsonModel
    {
        $this->validator->attach(
            [['id'], 'required'],
            [['id'], 'function', 'targetClass' => ItemFieldForm::class, 'method' => 'invalidDeleteId']
        );

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

        $model = new ItemFieldForm($this->validator);

        $this->LocalService()->log->saveFileLog($this->validator->attributes['id'], self::LOG_TARGET, $this->validator->attributes, Logs::OPERATE_DELETE, "删除字段{$model->delete()}");
        return $this->RenderApiJson()->Success();
    }

    /**
     * @url http://xxx.com/item/field/getRelationInformation
     * @return JsonModel|void
     * @throws Exception
     */
    public function getRelationInformationAction()
    {
        $this->validator->attach(
            [['type', 'item_id'], 'required'],
        );

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

        if ($this->validator->attributes['type'] == 0) {
            return $this->RenderApiJson()->Success([
                ['label' => '无关联信息', 'value' => '0']
            ]);
        } elseif ($this->validator->attributes['type'] == 1) { // 表单
            $query = $this->LocalService()->itemForm->fetchAll([
                'columns' => [ new Expression('name as label'),new Expression('id as value')],
                'where' => ['is_del' => 0, 'item_id' => $this->validator->attributes['item_id']]
            ]);

            return $this->RenderApiJson()->Success($query);
        } elseif ($this->validator->attributes['type'] == 2) { // 属性
            $query = Laminas::$serviceManager->itemFormVersion->getField([
                'form_id' => $this->validator->attributes['form_id'],
                'version' => 'v1.0'
            ], true);

            $options[] = ['label' => '无关联信息', 'value' => '0'];
            foreach ($query as $v) {
                $options[] = ['label' => $v['name'], 'value' => $v['id']];
            }

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

    /**
     * Notes: 选择参照检查点 再根据检查点选择检查点下的检查项 来控制可选择的检查项范围
     * @param
     * @return
     * @author haojinhua
     * @date 2025-02-11
     */
    public function selectchecktimeAction(){
        if($this->request->isPost()){
            $limit = $this->params()->fromPost('limit',20);
            $page = $this->params()->fromPost('page',1);
            $offset = intval(($page - 1) * $limit);
            $form_item = $this->params()->fromPost('item_id',0);//项目ID
            $form_item = empty($form_item) ? 0 : $form_item;
            $selectArr = $this->params()->fromPost('id');//选中数据

            if (empty($form_item)) return $this->RenderApiJson()->Error(StatusCode::E_FIELD_VALIDATOR, '参数不正确');

            //查询项目下的字典项检查项分类id
            $item_categoryid = $this->LocalService()->itemCheckname->fetchCol('category_id',[
                'is_del' => 0,
                'item_id' => $form_item,
            ]);
            $item_categoryid = array_unique($item_categoryid);

            //根据检查项分类ID 查询到表单ID
            $form_where = 'id<0';
            if(!empty($item_categoryid)){
                $form_where = [
                    'is_del' => 0,
                    'item_id' => $form_item,
                    'checklist_id' => StringHelper::toArray($item_categoryid),
                ];
            }
            $form_ids = $this->LocalService()->itemForm->fetchCol('id',$form_where);

            //根据$form_ids 查询检查点
            $checktime_ids = [];
            if(!empty($form_ids)){
                $checktime_ids = $this->LocalService()->itemCheckcontent->fetchCol('check_id', [
                    'is_del' => 0,
                    'item_id' => $form_item,
                    'form_id' => StringHelper::toArray($form_ids),
                ]);
            }

            $where = [
                'is_del' => 0,
                'item_id' => $form_item,
            ];

            if(!empty($checktime_ids)){
                $where['id'] = StringHelper::toArray($checktime_ids);
            }else{
                $where = [
                    'id' => 0,
                ];
            }
            $total = $this->LocalService()->itemChecktime->getCount($where);
            $datas = $this->LocalService()->itemChecktime->fetchAll([
                'where'=>$where,
                'columns'=>['id','title'=>'check_name'],
                'order'=>['check_order'],
                'limit'=>$limit,
                'offset'=>$offset
            ]);

            unset($where);

            //选中数据回显
            $selectDatas = [];
            if(!empty($selectArr)){
                if(!is_array($selectArr)){
                    $selectArr = explode(',',$selectArr);
                }
            }else{
                $selectArr = [];
            }
            if(!empty($selectArr)){
                $selectDatas = $this->LocalService()->itemChecktime->fetchAll([
                    'where'=> [
                        'is_del' => 0,
                        'item_id' => $form_item,
                        'id' => StringHelper::toArray($selectArr),
                    ],
                    'columns'=>['id','title'=>'check_name'],
                    'order'=>['check_order']
                ]);
            }

            //表单数据返回
            $FormFileData = [
                ['label' => '检查点','prop' => 'title']
            ];
            return $this->RenderApiJson()->success($datas,'',['total'=>$total,'selectData'=>$selectDatas,'FormFileData'=>$FormFileData,'limit'=>$limit,'page'=>$page]);

        }else{
            return $this->RenderApiJson()->Error(StatusCode::E_FIELD_VALIDATOR,'非法请求');
        }
    }

    /**
     * Notes: 选择参照检查项
     * User: lltyy
     * DateTime: 2024/9/2 15:41
     *
     * @return JsonModel
     */
    public function selectcheckAction(){
        if($this->request->isPost()){
            $limit = $this->params()->fromPost('limit',20);
            $page = $this->params()->fromPost('page',1);
            $offset = intval(($page - 1) * $limit);
            $form_item = $this->params()->fromPost('item_id',0);//项目ID
            $form_item = empty($form_item) ? 0 : $form_item;
            $selectArr = $this->params()->fromPost('id');//选中数据
            $checktime_id = $this->params()->fromPost('checktime_id',0);//检查点ID 不控制必填

            if (empty($form_item)) return $this->RenderApiJson()->Error(StatusCode::E_FIELD_VALIDATOR, '项目ID参数不正确');

            $check_formgroup = $this->LocalService()->dictionaryFormGroup->getOneFieldVal('id','is_del = 0 and code = "CHECKCATE"');
            $itemform_check = $check_formid = [];
            if(!empty($check_formgroup)){
                $itemform_checks = $this->LocalService()->itemForm->fetchCol('checklist_id',[
                    'is_del' => 0,
                    new Operator('checklist_id', Operator::OP_GT, 0),
                    'group_id' => $check_formgroup,
                    'item_id' => $form_item,
                ]);
                $itemform_check = !empty($itemform_checks) ? array_values($itemform_checks) : [];
                $check_formid   = !empty($itemform_checks) ? array_keys($itemform_checks) : [];
            }
            unset($check_formgroup);

            $category_where = [
                'is_del' => 0,
            ];
            if(!empty($itemform_check)){
                $category_where[] = [
                    'or' => [
                        'is_form' => 1,
                        'id' => StringHelper::toArray($itemform_check),
                    ]
                ];
            }else{
                $category_where['is_form'] = 1;
            }
            $category_name_arr = $this->LocalService()->DictionaryCheckcategory->fetchCol('category_name',$category_where);//分类名称
            unset($category_where);
            unset($itemform_check);

            //获取该项目下的检查项
            $where = [
                'is_del' => 0,
                'item_id' => $form_item,
            ];
            if(!empty($checktime_id)){
                //根据检查点 查询表单ID
                if(!empty($checktime_id)){
                    if(!is_array($checktime_id)){
                        $checktime_id = explode(',',$checktime_id);
                    }
                }
                $form_ids_where = 'id < 0';
                if(!empty($check_formid)){
                    $form_ids_where = [
                        'is_del' => 0,
                        'item_id' => $form_item,
                        'check_id' => StringHelper::toArray($checktime_id),
                        'form_id' => StringHelper::toArray($check_formid),
                    ];
                }
                $form_ids = $this->LocalService()->itemCheckcontent->fetchCol('form_id',$form_ids_where);
                //根据表单ID 查询分类
                $checklist_where = 'id<0';
                if(!empty($form_ids)){
                    $checklist_where = [
                        'is_del' => 0,
                        'item_id' => $form_item,
                        'id' => StringHelper::toArray($form_ids),
                        new Operator('checklist_id', Operator::OP_GT, 0),
                    ];
                }
                $checklist_ids = $this->LocalService()->itemForm->fetchCol('checklist_id',$checklist_where);
                if(!empty($checklist_ids)){
                    $where['category_id'] = StringHelper::toArray($checklist_ids);
                }else{
                    $where = [
                        'id' => 0,
                    ];
                }

            }else{
                if(!empty($category_name_arr)){
                    $where[] = [
                        'or' => [
                            'category_id' => StringHelper::toArray(array_values(array_keys($category_name_arr))),
                            new Operator('form_field_id', Operator::OP_GT, 0),
                        ]
                    ];
                }else{
                    $where[] = new Operator('form_field_id', Operator::OP_GT, 0);
                }
            }

            $total = $this->LocalService()->itemCheckname->getCount($where);
            $datas = $this->LocalService()->itemCheckname->fetchAll([
                'where'=>$where,
                'columns'=>['id','category_id','title'=>'name'],
                'order'=>['category_id','checkname_order'],
                'limit'=>$limit,
                'offset'=>$offset
            ]);
            unset($where);
            if(!empty($datas)){
                foreach($datas as &$data){
                    if(isset($category_name_arr[$data['category_id']]) && !empty($category_name_arr[$data['category_id']])){
                        $data['title'] = $category_name_arr[$data['category_id']].'-'.$data['title'];
                    }
                    unset($data['category_id']);
                }
            }
            unset($itemcheckDatas);

            //选中数据回显
            $selectDatas = [];
            if(!empty($selectArr)){
                if(!is_array($selectArr)){
                    $selectArr = explode(',',$selectArr);
                }
            }else{
                $selectArr = [];
            }
            if(!empty($selectArr)){
                $selectDatas = $this->LocalService()->itemCheckname->fetchAll([
                    'where'=> [
                        'is_del' => 0,
                        'item_id' => $form_item,
                        'id' => StringHelper::toArray($selectArr),
                    ],
                    'columns'=>['id','category_id','title'=>'name'],
                    'order'=>['category_id','checkname_order']
                ]);
                if(!empty($selectDatas)){
                    foreach($selectDatas as &$selectData){
                        if(isset($category_name_arr[$selectData['category_id']]) && !empty($category_name_arr[$selectData['category_id']])){
                            $selectData['title'] = $category_name_arr[$selectData['category_id']].'-'.$selectData['title'];
                        }
                        unset($selectData['category_id']);
                    }
                }
            }
            unset($category_name_arr);

            //表单数据返回
            $FormFileData = [
                ['label' => '检查项','prop' => 'title']
            ];
            return $this->RenderApiJson()->success($datas,'',['total'=>$total,'selectData'=>$selectDatas,'FormFileData'=>$FormFileData,'limit'=>$limit,'page'=>$page]);

        }else{
            return $this->RenderApiJson()->Error(StatusCode::E_FIELD_VALIDATOR,'非法请求');
        }
    }


    /**
     * Notes: 选择参考表单检查点 可选全部的检查点
     * @param
     * @return
     * @author haojinhua
     * @date 2025-04-07
     */
    public function selectformchecktimeAction(){
        if($this->request->isPost()){
            $limit = $this->params()->fromPost('limit',20);
            $page = $this->params()->fromPost('page',1);
            $offset = intval(($page - 1) * $limit);
            $form_item = $this->params()->fromPost('item_id',0);//项目ID
            $form_item = empty($form_item) ? 0 : $form_item;
            $selectArr = $this->params()->fromPost('id');//选中数据

            if (empty($form_item)) return $this->RenderApiJson()->Error(StatusCode::E_FIELD_VALIDATOR, '参数不正确');

            $where = [
                'is_del' => 0,
                'item_id' => $form_item,
            ];
            $total = $this->LocalService()->itemChecktime->getCount($where);
            $datas = $this->LocalService()->itemChecktime->fetchAll([
                'where'=>$where,
                'columns'=>['id','title'=>'check_name'],
                'order'=>['check_order'],
                'limit'=>$limit,
                'offset'=>$offset
            ]);

            unset($where);

            //选中数据回显
            $selectDatas = [];
            if(!empty($selectArr)){
                if(!is_array($selectArr)){
                    $selectArr = explode(',',$selectArr);
                }
            }else{
                $selectArr = [];
            }
            if(!empty($selectArr)){
                $selectDatas = $this->LocalService()->itemChecktime->fetchAll([
                    'where'=> [
                        'is_del' => 0,
                        'item_id' => $form_item,
                        'id' => StringHelper::toArray($selectArr),
                    ],
                    'columns'=>['id','title'=>'check_name'],
                    'order'=>['check_order']
                ]);
            }

            //表单数据返回
            $FormFileData = [
                ['label' => '检查点','prop' => 'title']
            ];
            return $this->RenderApiJson()->success($datas,'',['total'=>$total,'selectData'=>$selectDatas,'FormFileData'=>$FormFileData,'limit'=>$limit,'page'=>$page]);

        }else{
            return $this->RenderApiJson()->Error(StatusCode::E_FIELD_VALIDATOR,'非法请求');
        }
    }

    /**
     * Notes: 选择参照表单
     * User: lltyy
     * DateTime: 2024/9/2 15:41
     *
     * @return JsonModel
     */
    public function selectformAction(){
        if($this->request->isPost()){
            $limit = $this->params()->fromPost('limit',20);
            $page = $this->params()->fromPost('page',1);
            $offset = intval(($page - 1) * $limit);
            $form_item = $this->params()->fromPost('item_id',0);//项目ID
            $form_item = empty($form_item) ? 0 : $form_item;
            $form_id = $this->params()->fromPost('form_id',0);//表单ID
            $form_id = empty($form_id) ? 0 : $form_id;
            $selectArr = $this->params()->fromPost('id');//选中数据
            $form_checktime_id = $this->params()->fromPost('form_checktime_id');

            if (empty($form_item) || empty($form_id)) return $this->RenderApiJson()->Error(StatusCode::E_FIELD_VALIDATOR, '参数不正确');

            //获取该项目下的检查项 只能选择未设置为隐私的字段
            $where = [
                'is_del' => 0,
                'parent' => 0,
                new NotIn('type', [13, 14, 19]),
                'item_id' => $form_item,
                new Operator('id', Operator::OP_NE, $form_id),
                'is_hide' => 0,
            ];
            //获取表单ID
            $form_group_arr = $this->LocalService()->dictionaryFormGroup->fetchCol('id','is_del = 0 and code in ("GC","RDG","GCO","Telephone_Follow_Up")');
            $form_group_arr = !empty($form_group_arr) ? array_values($form_group_arr) : [];
            $select_form_where = [
                'is_del' => 0,
                'type' => 0,
                'item_id' => $form_item,
                new Operator('id', Operator::OP_NE, $form_id),
            ];
            if(!empty($form_group_arr)){
                $select_form_where['group_id'] = StringHelper::toArray($form_group_arr);
            }else{
                $select_form_where = [
                    'id' => 0,
                ];
            }
            unset($form_group_arr);

            $form_arr = $this->LocalService()->itemForm->fetchCol('name',$select_form_where);
            unset($select_form_where);
            if(!empty($form_arr)){
                if(!empty($form_checktime_id)){
                    //根据检查点 查询表单ID
                    if(!empty($form_checktime_id)){
                        if(!is_array($form_checktime_id)){
                            $form_checktime_id = explode(',',$form_checktime_id);
                        }
                    }
                    //查询检查点下的表单ID
                    $form_ids_where = [
                        'is_del' => 0,
                        'item_id' => $form_item,
                        'form_id' => StringHelper::toArray(array_values(array_keys($form_arr))),
                    ];
                    if(!empty($form_checktime_id)){
                        $form_ids_where['check_id'] = StringHelper::toArray($form_checktime_id);
                    }
                    $form_ids = $this->LocalService()->itemCheckcontent->fetchCol('form_id',$form_ids_where);
                    $where['form_id'] = StringHelper::toArray($form_ids);
                }else{
                    $where['form_id'] = StringHelper::toArray(array_values(array_keys($form_arr)));
                }

                //去除被关联的表单内容
                $select_relation_field_arr = $this->LocalService()->itemFormFieldRadio->fetchCol('relation_information','relation_classification = 2 and relation_information != "" and relation_information is not null');
                if(!empty($select_relation_field_arr)){
                    foreach($select_relation_field_arr as $select_relation_fieldkey=>$select_relation_field){
                        $new_arr = [];
                        $select_relation_fields = !empty($select_relation_field) ? explode(',',$select_relation_field) : [];
                        foreach($select_relation_fields as $select_relation_fieldid){
                            if(!empty($select_relation_fieldid)){
                                $new_arr[] = $select_relation_fieldid;
                            }
                        }
                        if(!empty($new_arr)){
                            $select_relation_field_arr[$select_relation_fieldkey] = implode(',',$new_arr);
                        }else{
                            unset($select_relation_field_arr[$select_relation_fieldkey]);
                        }
                    }
                }
                if(!empty($select_relation_field_arr)){
                    $where[] = new NotIn('id', array_values($select_relation_field_arr));
                }
                unset($select_relation_field_arr);
            }else{
                $where = [
                    'id' => 0,
                ];
            }

            $total = $this->LocalService()->itemFormField->getCount($where);
            $datas = $this->LocalService()->itemFormField->fetchAll([
                'where'=>$where,
                'columns'=>['id','form_id','title'=>'name'],
                'order'=>['form_id','order'],
                'limit'=>$limit,
                'offset'=>$offset
            ]);
            unset($where);
            if(!empty($datas)){
                foreach($datas as &$data){
                    if(isset($form_arr[$data['form_id']]) && !empty($form_arr[$data['form_id']])){
                        $data['title'] = $form_arr[$data['form_id']].'-'.$data['title'];
                    }
                    unset($data['form_id']);
                }
            }

            //选中数据回显
            $selectDatas = [];
            if(!empty($selectArr)){
                if(!is_array($selectArr)){
                    $selectArr = explode(',',$selectArr);
                }
            }else{
                $selectArr = [];
            }
            if(!empty($selectArr)){
                $selectDatas = $this->LocalService()->itemFormField->fetchAll([
                    'where'=> [
                        'is_del' => 0,
                        'item_id' => $form_item,
                        'id' => StringHelper::toArray($selectArr),
                    ],
                    'columns'=>['id','form_id','title'=>'name'],
                    'order'=>['form_id','order']
                ]);
                if(!empty($selectDatas)){
                    foreach($selectDatas as $selectKey=>&$selectData){
                        if(isset($form_arr[$selectData['form_id']]) && !empty($form_arr[$selectData['form_id']])){
                            $selectData['title'] = $form_arr[$selectData['form_id']].'-'.$selectData['title'];
                            unset($selectData['form_id']);
                        }else{
                            unset($selectDatas[$selectKey]);
                        }
                    }
                }
            }
            $selectDatas = array_values($selectDatas);
            unset($form_arr);

            //表单数据返回
            $FormFileData = [
                ['label' => '检查项','prop' => 'title']
            ];
            return $this->RenderApiJson()->success($datas,'',['total'=>$total,'selectData'=>$selectDatas,'FormFileData'=>$FormFileData,'limit'=>$limit,'page'=>$page]);

        }else{
            return $this->RenderApiJson()->Error(StatusCode::E_FIELD_VALIDATOR,'非法请求');
        }
    }

    public function formFieldSelectAction(): JsonModel
    {
        $item_id = $this->params()->fromPost('item_id', 0);
        // 只获取已关联检查点的表单
        $itemFormIdList = array_flip(array_unique($this->LocalService()->itemCheckcontent->fetchCol('form_id', [
            'item_id' => $item_id,
            'is_del' => 0
        ]) ?? []));

        $itemFormNameList = array_intersect_key($this->LocalService()->itemForm->fetchCol('name',[
            'item_id' => $item_id,
            'is_del' => 0,
        ]) ?? [], $itemFormIdList);

        $result = [];
        if(!empty($itemFormNameList)) {
            $itemFormFieldNameList = $this->LocalService()->itemFormField->fetchAll([
                'where' => [
                    'item_id' => $item_id,
                    'is_del' => 0,
                    'is_item_form_source' => 1
                ],
                'columns' => ['id', 'form_id', 'name'],
                'order' => ['form_id', 'order'],
            ]);

            array_walk($itemFormFieldNameList, function (&$itemFormField) use (&$itemFormNameList, &$result){
                // 医嘱共享图片字段追加“药物名称”字样
                $itemFormField['name'] .= $this->LocalService()->itemFormField->validDrugShareImg($itemFormField['id']) ? '/ 医嘱药物名称' : '';
                if(isset($itemFormNameList[$itemFormField['form_id']])) {
                    if(!isset($result[$itemFormField['form_id']])) {
                        $result[$itemFormField['form_id']] = [
                            'id' => $itemFormField['form_id'],
                            'name' => $itemFormNameList[$itemFormField['form_id']],
                        ];
                    }
                    $result[$itemFormField['form_id']]['children'][] = $itemFormField;
                }
            });
        }

        return $this->RenderApiJson()->success(
            ArrayUtils::merge(
                [ $this->LocalService()->itemFormField->generateCollecttypeFieldSelect() ],
                array_values($result)
            )
        );
    }

    public function formChecktimeSelectAction(): JsonModel
    {
        $form_id = $this->params()->fromPost('form_id', 0);
        $item_id = $this->params()->fromPost('item_id', 0);
        $checktimeIdList = array_unique($this->LocalService()->itemCheckcontent->fetchCol('check_id', ArrayUtils::merge([
            'item_id' => $item_id,
            'is_del' => 0
        ], $form_id == '-1' ? [] : ['form_id' => $form_id])));

        $result = [];
        if(!empty($checktimeIdList)) {
            $stageNameList = $this->LocalService()->itemResearchstage->fetchCol('stage_name', [
                'item_id' => $item_id,
                'is_del' => 0
            ]);

            $result = $this->LocalService()->itemChecktime->fetchAll([
                'where' => [
                    'item_id' => $item_id,
                    'is_del' => 0,
                    'id' => StringHelper::toArray($checktimeIdList),
                ],
                'columns' => ['id', 'name' => 'check_name', 'stage_id'],
                'order' => ['check_order' => 'asc']
            ]);

            foreach($result as &$checktime){
                $checktime['name'] = $stageNameList[$checktime['stage_id']] . ' / ' . $checktime['name'];
            }
        }
        return $this->RenderApiJson()->Success($result);
    }

    public function checktimeFormRealtionAction()
    {
        $main_id = $this->params()->fromPost('main_id', 0);
        if($main_id == 0) return $this->RenderApiJson()->Success();
        $checktime_id = $this->params()->fromPost('checktime_id',0);

        $type = $this->params()->fromPost('type',1); // 1 检查项 2 表单

        $item_id = $this->params()->fromPost('item_id',0);


        if($type == 1){
            //检查项对应的化验单ID
            $category_id = $this->LocalService()->itemCheckname->getOneFieldVal('category_id',[
                'id' => $main_id,
                'is_del' => 0
            ]);
            $form_id = $this->LocalService()->itemForm->getOneFieldVal('id',[
                'item_id' => $item_id,
                'checklist_id' => $category_id,
                'is_del' => 0
            ]);
        }else{
            //字段对应的表单ID
            $form_id = $this->LocalService()->itemFormField->getOneFieldVal('form_id',[
                'id' => $main_id,
                'is_del' => 0
            ]);
        }
        $check_id = $this->LocalService()->itemCheckcontent->fetchCol('check_id', [
            'is_del' => 0,
            'form_id' => $form_id,
            'check_id' => StringHelper::toArray($checktime_id)
        ]);
        if(!$check_id) return $this->RenderApiJson()->Error(StatusCode::E_FIELD_VALIDATOR,'设置有误');
        $checkInfo = $this->LocalService()->itemChecktime->fetchCol('check_name',[
            'id' => StringHelper::toArray($check_id)
        ]);
        $back = [];
        foreach($checkInfo as $k=>$v){
            $arr['id'] = $k;
            $arr['name'] = $v;
            $back[] = $arr;
        }
        return $this->RenderApiJson()->Success($back);
    }

}