<template>
    <div class="flex " :class="getFlexClass()">
        <div class="flex" :class="getFlexClass()">
            <!-- @copy.native.capture.prevent="handleFalse"
                @cut.native.capture.prevent="handleFalse" -->
            <el-input 
                v-if="type === 'input'" :maxlength="item.maxlength || 50" :disabled="getDisabled()"
                :class="getFillTypeStyle() + (orangeBg ? ' orange-bg' : '')" @blur="onBlur"
                type = "textarea" :autosize="{ minRows: 1, maxRows: 6 }" resize = "none"
                :placeholder="getPlaceholder()" v-model="inputValue" @input="onInputChange" @change="onInputChange" />
            <el-input v-else-if="type === 'textarea'" :maxlength="item.maxlength || 1000" :disabled="getDisabled()"
                :class="getFillTypeStyle() + (orangeBg ? ' orange-bg' : '')" type="textarea" show-word-limit
                resize="none" @blur="onBlur" :rows="item.rows || 3" :placeholder="getPlaceholder()" v-model="inputValue"
                @input="onInputChange" @change="onInputChange" />
            <DecimalInput v-else-if="type === 'inputNumber'" @blur="onCommonHandleSaveRecord"
                :maxlength="item.maxlength || 10" class="flex1" :disabled="getDisabled()"
                :controls="item.controls || false" :min="item.min || 0" :prepend="item.prepend"
                :decimalDigits="getDecimalDigits()" :class="getFillTypeStyle() + (orangeBg ? ' orange-bg' : '')"
                :placeholder="getPlaceholder()" v-model="inputValue" @input="onInputChange" @change="onInputChange" />
            <el-select v-else-if="type === 'select'" class="flex1" :multiple="item.multiple"
                :class="getFillTypeStyle() + (orangeBg ? ' orange-bg' : '')" v-model="inputValue"
                :disabled="getDisabled()" :placeholder="getPlaceholder()" @remove-tag="onRemoveTag"
                :remote = "item.selectRemote || false"
                :remote-method="remoteMethod"
                @visible-change="onSelectBlur" @change="onInputChange" filterable>
                <el-option v-for="op in item.options" :key="op.value" :label="op.label" :value="op.value">
                </el-option>
            </el-select>
            <el-checkbox v-else-if="type === 'checkbox'" class="flex1" :multiple="item.multiple"
                :class="getFillTypeStyle() + (orangeBg ? ' orange-bg' : '')" v-model="inputValue"
                :disabled="getDisabled()" :placeholder="getPlaceholder()" @change="onItemCheckboxChange">
                {{ item.checkboxLabel }}
            </el-checkbox>
            <el-radio-group v-else-if="type === 'radio'" v-model="inputValue"
                :class="getFillTypeStyle() + (orangeBg ? ' orange-bg' : '')" :disabled="getDisabled()"
                @change="onItemCheckboxChange">
                <el-radio v-for="option in item.options" :key="option.value" :label="option.value"
                    :disabled="getDisabled()">
                    {{ option.label }}
                </el-radio>
            </el-radio-group>
            <div v-else-if="type === 'checkboxTree'" class="flex1 checkbox-list-container"
                :class="getFillTypeStyle() + (orangeBg ? ' orange-bg' : '') + (error ? ' form-error-border' : '') + (item.noBorder ? ' no-border' : '') + (item.layout === 'horizontal' ? ' flex' : '')">
                <div v-for="group in item.options" :key="group.value" class="checkbox-tree-group"
                    :class="{ 'item-center': isShowOtherByCheckboxTree(group.value) }">
                    <el-checkbox :label="group.value" :disabled="getDisabled()"
                        :value="getCheckboxTreeChecked(group.value)"
                        :indeterminate="getCheckboxTreeIndeterminate(group.value)"
                        @change="onCheckboxTreeParentChange(group, $event)">
                        {{ group.label }}
                    </el-checkbox>
                    <div v-if="group.children && group.children.length > 0" class="checkbox-tree-children">
                        <div v-for="child in group.children" :key="child.value" class="checkbox-tree-item">
                            <el-checkbox :label="child.value" :disabled="getDisabled()"
                                :value="getCheckboxTreeChecked(child.value)"
                                @change="onCheckboxTreeChildChange(group, child.value, $event)">
                                {{ child.label }}
                            </el-checkbox>
                            <div v-if="isShowOtherByCheckboxTree(child.value) && isCheckboxTreeChecked(child.value)"
                                class="checkbox-tree-input-container">
                                <el-input maxlength="100" v-model="inputValue.otherValues[child.value]"
                                    :disabled="getDisabled()" placeholder="请输入"
                                    @blur="onCheckboxTreeOtherBlur(child.value, $event)" />
                            </div>
                        </div>
                    </div>
                    <div v-if="isShowOtherByCheckboxTree(group.value) && isCheckboxTreeChecked(group.value)"
                        class="checkbox-tree-input-container">
                        <el-input maxlength="100" v-model="inputValue.otherValues[group.value]"
                            :disabled="getDisabled()" placeholder="请输入"
                            @blur="onCheckboxTreeOtherBlur(group.value, $event)" />
                    </div>
                </div>
            </div>
            <el-date-picker v-else-if="type === 'dateTime' || type === 'datePicker'"
                :type="type === 'dateTime' ? 'datetime' : 'date'" class="flex1"
                :class="getFillTypeStyle() + (orangeBg ? ' orange-bg' : '')" v-model="inputValue"
                :picker-options="pickerOptions" :disabled="getDisabled()"
                :format="type === 'dateTime' ? 'yyyy/MM/dd HH:mm:ss' : 'yyyy/MM/dd'" :placeholder="getPlaceholder()"
                @change="(val) => onDateChange(val, type === 'dateTime' ? 'yyyy/MM/DD HH:mm:ss' : 'yyyy/MM/DD')">
            </el-date-picker>
            <el-date-picker
                v-else-if="type === 'dateTimeRange'"
                v-model="inputValue"
                type="datetimerange"
                range-separator="至"
                :class="getFillTypeStyle() + (orangeBg ? ' orange-bg' : '')" 
                :disabled="getDisabled()"
                :picker-options="pickerOptions"
                @change="(val) => onDateChange(val, 'yyyy/MM/DD HH:mm:ss')"
                start-placeholder="开始日期"
                end-placeholder="结束日期">
            </el-date-picker>
            <el-button v-else-if="type === 'button'" :class="getFillTypeStyle() + (orangeBg ? ' orange-bg' : '')"
                :disabled="getDisabled()" type="primary" @click="handleClickButton(item)">
                {{ $t(item.buttonName) }}
                <input type="hidden" v-model="inputValue">
            </el-button>

            <div class="clickable"
                :class="getFillTypeStyle() + (getDisabled() ? ' disabled' : '') + (orangeBg ? ' orange-bg' : '')"
                v-else-if="item.type === 'clickable'" @click="handleClickable(item, $event)">
                <span v-if="inputValue">{{ inputValue }}</span>
                <span v-else class="default-placeholder-text">{{ getPlaceholder() }}</span>
            </div>
            <div class="clickable"
                :class="getFillTypeStyle() + (getDisabled() ? ' disabled' : '') + (orangeBg ? ' orange-bg' : '')"
                v-else-if="isRegent(item)" @click="onCommonHandleRegent(item, item.type)">
                <span v-if="inputValue">{{ inputValue }}</span>
                <span v-else class="default-placeholder-text">{{ getPlaceholder() }}</span>
            </div>
            <template v-else-if="type === 'attachment'">
                <el-upload ref="uploadRef" class="upload-demo" :action="uploadFileUrl" :on-preview="handlePreview"
                    :headers="headers" :before-remove="beforeRemove" :on-remove="handleRemove" multiple :limit="10"
                    :disabled="getDisabled()"
                    :on-success="handleSuccess" :on-change="handleChange" :on-exceed="handleExceed"
                    :file-list="fileList" :auto-upload="false">
                    <el-button :disabled="getDisabled()" :class="getFillTypeStyle() + (orangeBg ? ' orange-bg' : '')"
                        size="small" type="primary">点击上传</el-button>
                    <span v-if="error" class="atta-tips">请上传附件</span>
                    <div slot="tip" class="el-upload__tip">支持扩展名：.rar .zip .doc .docx .pdf .jpg，文件大小不超过2MB</div>
                </el-upload>
            </template>
            <div v-else-if="type === 'checkboxTag'" class="flex1 checkbox-tag-wrapper"
                :class="getFillTypeStyle() + (orangeBg ? ' orange-bg' : '')">
                <div v-for="(tag, tagIndex) in checkboxTagList" :key="tagIndex" class="checkbox-tag-container">
                    <div class="checkbox-tag-item">
                        <el-checkbox v-model="tag.checked" :disabled="getDisabled()"
                            @change="onCheckboxTagChange(tagIndex, $event)"></el-checkbox>
                        <div class="tag-content blue-border">
                            <el-input v-if="templateFillType === 'preFill'" v-model="tag.tagValue"
                                :ref="'tagInput_' + tagIndex" :maxlength="item.maxlength || 20"
                                @blur="onTagBlur(tagIndex)" @keyup.enter.native="onTagBlur(tagIndex)" placeholder="请输入"
                                size="mini" class="tag-input" />
                            <el-tag v-else :type="'info'" class="tag-display" :closable="false">
                                {{ tag.tagValue }}
                            </el-tag>
                            <el-popconfirm confirm-button-text='确认' cancel-button-text='取消' icon="el-icon-info"
                                icon-color="red" title="确认删除当前编号？" @confirm="onDeleteTag(tagIndex)">
                                <i slot="reference" v-if="templateFillType === 'preFill'"
                                    class="el-icon-close delete-icon"></i>
                            </el-popconfirm>
                        </div>
                    </div>
                </div>
            </div>
            <div v-else-if="type === 'fqyq'" :class="getFillTypeStyle()">
                <el-radio-group v-model="fqyqValue.mainRadio" :disabled="getDisabled()"
                    @input="onFqyqRadioChange($event, 'mainRadio')">
                    <div class="item-center mb-10">
                        <el-radio label="是">是</el-radio>
                        <div class="item-center" v-if="fqyqValue.mainRadio === '是'">
                            <el-input class="fqyq-input" maxlength="100" v-model="fqyqValue.inputValue"
                                :disabled="getDisabled()" placeholder="请输入" @blur="onFqyqInputBlur"></el-input>
                            <div class="fs-14 mr-10">是否在规定时间完成</div>
                            <el-radio-group v-model="fqyqValue.subRadio" :disabled="getDisabled()"
                                @input="onFqyqRadioChange($event, 'subRadio')">
                                <el-radio label="是"></el-radio>
                                <el-radio label="否"></el-radio>
                            </el-radio-group>
                        </div>
                    </div>
                    <el-radio label="否">否</el-radio>
                </el-radio-group>
            </div>

        </div>
        <div class="handle-row" v-if="isShowHandle()">
            <el-checkbox v-model="checkboxValue" v-if="getIsShowCheckboxIcon()" :disabled="getCheckboxDisabled()"
                class="mr-5" @change="onCheckboxChange"></el-checkbox>
            <div class="handle-icon" v-if="getIsShowQuestionIcon()" @click="onClickQuestion"
                @mouseenter="(e) => onMouseEnter('replyRecord', e)" @mouseleave="onMouseLeave">
                <Question :class="getQuestionColor()" />
            </div>
            <img v-if="getIsShowCopyIcon()" @click="onCopy" src="@/assets/images/copy-icon.svg" class="handle-icon"
                alt="" />
            <img v-if="getIsShowRecordIcon()" @mouseenter="(e) => onMouseEnter('fieldChanged', e)"
                @mouseleave="onMouseLeave" src="@/assets/images/record-icon.svg" class="handle-icon" alt="" />
        </div>

        <!-- 修改记录模态框 -->
        <div v-if="showModal && modificationRecords.length > 0" ref="modalRef"
            :class="['modification-modal', { 'show': showModal }]" @mouseenter="onModalEnter"
            @mouseleave="onModalLeave">
            <div class="modal-content">
                <div class="records-list">
                    <div v-for="(record, index) in modificationRecords" :key="index" class="record-item">
                        <!-- 字段修改记录 -->
                        <div class="record-row" v-if="currentRecordType === 'fieldChanged'">
                            <div>
                                <span>{{ index + 1 }}.</span>
                                <span> {{ getUserName(record) }} </span>
                                <span>{{ record.time }} </span>
                                <span>{{ modificationRecords.length - 1 == index ? "提交" : "修改" }}</span>
                            </div>
                            <div v-if="modificationRecords.length - 1 !== index">
                                <div>原值：{{ record.oldValue }}</div>
                                <div>修改值：{{ record.value }}</div>
                                <div v-if="record.reason">备注：{{ record.reason }}</div>
                            </div>
                        </div>
                        <!-- 回复记录 -->
                        <div class="record-row" v-if="currentRecordType === 'replyRecord'">
                            <div>
                                <span> {{ getUserName(record) }} </span>
                                <span>{{ record.time }} </span>
                            </div>
                            <div>
                                <div v-if="record.content">复核意见：{{ record.content }}</div>
                                <div v-if="record.reply">意见回复：{{ record.reply }}</div>
                            </div>
                        </div>
                        <hr v-if="index < modificationRecords.length - 1">
                    </div>
                </div>
            </div>
        </div>
        <el-dialog :close-on-click-modal="false" append-to-body :title="(templateFillType == 'actFill' || templateFillType == 'blxjsh') ? '意见回复' : '复核意见'"
            :visible.sync="visible" width="30%">
            <el-input v-model="replyContent" type="textarea" show-word-limit resize="none" rows="8" placeholder="输入内容"
                maxlength="500" />
            <span slot="footer" class="dialog-footer">
                <el-button @click="visible = false">取 消</el-button>
                <el-button type="primary" @click="onReplyConfirm">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import Question from "./icons/Question.vue";
import DecimalInput from "./DecimalInput.vue";
import { EventBus } from "@/utils/eventBus";
import moment from "moment";
import { getuuid, isEqual, deepClone, getDefaultValueByOptions, isValueEmpty,isRegent } from "@/utils/index.js";
import { getToken } from "@/utils/auth";
import { isShowOtherByCheckboxTree } from "@/utils/formPackageCommon";

export default {
    inject: ['templateData', 'templateFillType',"getSubmittedCodes","updateSubmittedCodes", "getZdxgjl", "getFhyjjl", "updateZdxgjl", "replaceFhyjjl", "updateFhyjjl", "getFieldCheckObj", "updateFieldCheckObj"],
    components: {
        Question,
        DecimalInput,
    },
    props: {
        type: {//form类型  input/select等
            type: String,
            default: "input"
        },
        item: {
            type: Object,
            default: () => {
                return {
                    placeholder: "",
                    maxlength: 30,
                    label: "",
                    disabled: false,
                }
            }
        },
        // v-model 值
        value: {
            type: [String, Number, Array, Boolean, Object],
            default: ''
        },
        // 错误状态
        error: {
            type: Boolean,
            default: false
        },
        // 橙色背景状态
        orangeBg: {
            type: Boolean,
            default: false
        },
        fieldKey: {
            type: String,
            default: ""
        },
        fieldItemLabel: {
            type: String,
            default: "",
        },
        //是否记录修改
        isFieldsRecord: {
            type: Boolean,
            default: true,
        },
        sourceFrom: {
            type: String,
            default: ""
        },
    },
    data() {
        let initialValue = this.value;
        let initialOtherValues = {}, checkboxTagList = [];

        if (this.type === 'checkboxTag' && Array.isArray(this.value)) {
            // checkboxTag类型，value是数组格式
            checkboxTagList = this.value.map(tag => ({
                checked: tag.checked,
                tagValue: tag.tagValue || ''
            }));
        } else if (this.type === 'fqyq' && !this.value) {
            initialValue = { mainRadio: '', subRadio: '', inputValue: "" };
        } else if (this.type === 'checkboxTree' && !this.value) {
            const defaultCheckedValue = getDefaultValueByOptions(this.item.options || []);
            initialValue = { checkedValues: defaultCheckedValue, otherValues: {} };
        }
        const {type} = this;
        return {
            inputValue: initialValue,
            oldValue: typeof initialValue === 'object' ? JSON.parse(JSON.stringify(initialValue)) : initialValue, // 记录上一次的值
            showModal: false, // 控制模态框显示
            modificationRecords: [], // 存储修改记录
            modalTimer: null, // 用于延迟隐藏模态框
            isHoveringModal: false, // 是否悬停在模态框上
            isHoveringMain: false, // 是否悬停在主元素上（这个实际上不需要，因为我们有事件处理）
            currentRecordType: '', // 当前悬停的记录类型（replyRecord 或 modifyRecord）
            replyContent: '', // 回复内容
            visible: false,//是否显示弹窗
            checkboxValue: this.getChecked(),//是否选中
            checkboxTagList: checkboxTagList, // checkboxTag类型的列表数据
            oldCheckboxTagList: JSON.parse(JSON.stringify(checkboxTagList)), // 记录上一次的checkboxTagList
            fqyqValue: initialValue, // fqyq类型的值
            oldFqyqValue: { ...initialValue }, // 记录上一次的fqyq值
            uuid: getuuid(), // 唯一标识符，用于EventBus事件匹配
            isRegent,  //试剂/仪器/供试品等类型
            selectRegentInfo: {},//选择的试剂/仪器/供试品等信息
            fileList: [],//上传的文件列表
            uploadFileUrl: process.env.VUE_APP_BASE_API + "/file/upload",
            headers: {
                Authorization: "Bearer " + getToken(),
            },
            pendingUploadFile: null, // 用于存储待上传的文件
            pendingRemoveFile: null, // 用于存储待删除的文件
            currentTagIndex: -1,//当前选中的checkboxTag索引
            currentHandleType: '',//当前操作的类型
            currentOtherCode: '',//当前操作的otherCode
            currentCheckboxTreeValue: '',//当前操作的checkboxTree值
            isShowOtherByCheckboxTree,
            pickerOptions: {
                // disabledDate(time) {
                //     return time.getTime() > Date.now();
                // },
                shortcuts: type === 'dateTimeRange' ? undefined:[{
                    text: '今天',
                    onClick(picker) {
                        picker.$emit('pick', new Date());
                    }
                }]
            }

        }
    },
    watch: {
        
        value(newVal) {
            if (this.type === 'checkboxTag' && Array.isArray(newVal)) {
                // checkboxTag类型，value是数组格式
                this.checkboxTagList = newVal.map(tag => ({
                    checked: tag.checked,
                    tagValue: tag.tagValue || ''
                }));
            } else if (this.type === 'fqyq' && newVal && typeof newVal === 'object') {
                // fqyq类型
                this.fqyqValue = {
                    mainRadio: newVal.mainRadio || '',
                    inputValue: newVal.inputValue || '',
                    subRadio: newVal.subRadio || ''
                };
            } else {
                this.inputValue = typeof newVal === 'object' ? JSON.parse(JSON.stringify(newVal)) : newVal;
            }
        }
    },
    filters: {


    },
    mounted() {
        if (this.item.type === 'attachment') {
            try {
                this.fileList = JSON.parse(this.value);
            } catch (e) {
                this.fileList = [];
            }
        }
        EventBus.$on('onExternalFieldUpdate', this.handleExternalFieldUpdate);
        EventBus.$on('onEditSignCancel', this.handleEditSignCancel);
        EventBus.$on('onEditSignCallback', this.handleEditSignCallback);
        //试剂
        EventBus.$on("onReagentSubmit", this.onReagentSubmit)
        //仪器
        EventBus.$on("onInstrumentSubmit", this.onMixReagentSubmit)
        //供试品/试剂/给药制剂等
        EventBus.$on("onMixReagentSubmit", this.onMixReagentSubmit)
    },
    unmounted() {
        EventBus.$off('onExternalFieldUpdate', this.handleExternalFieldUpdate);
        EventBus.$off('onEditSignCancel', this.handleEditSignCancel);
        EventBus.$off('onEditSignCallback', this.handleEditSignCallback);
        EventBus.$off("onReagentSubmit", this.onReagentSubmit)
        EventBus.$off("onInstrumentSubmit", this.onMixReagentSubmit)
        EventBus.$off("onMixReagentSubmit", this.onMixReagentSubmit)
    },
    methods: {
        remoteMethod(query) {
            this.$emit('remoteMethod', query);
        },
        handleFalse() {
            return false;
        },
        getFlexClass() {
            const noFlexArr = ["radio", "checkboxTag", "fqyq"]
            return noFlexArr.includes(this.type) ? '' : 'flex1'
        },
        getDecimalDigits() {
            const { precision } = this.item;
            if (!isNaN(precision)) {
                return Number(precision)
            }
            return 6
        },
        onInstrumentSubmit(data) {
            if (data.uuid !== this.uuid) return;
            this.selectRegentInfo = data;
        },

        // 文件状态改变时的钩子，添加文件、上传成功、上传失败时都会被调用
        handleChange(file, fileList) {
            // 如果是新添加的文件（status为ready），进行验证
            if (file.status === 'ready') {
                const isAllowedType = ['image/jpeg', 'image/png', 'image/gif', 'application/pdf',
                    'application/x-rar-compressed', 'application/zip',
                    'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'].includes(file.raw.type)
                const isLt2M = file.size / 1024 / 1024 < 2

                if (!isAllowedType) {
                    this.$message.error(`文件 ${file.name} 格式不支持!只能上传 JPG/PNG/GIF/PDF/RAR/ZIP/DOC/DOCX 格式的文件`)
                    // 从fileList中移除该文件
                    const index = fileList.indexOf(file);
                    if (index > -1) {
                        fileList.splice(index, 1);
                    }
                    this.fileList = [...fileList];
                    return
                }
                if (!isLt2M) {
                    this.$message.error(`文件 ${file.name} 大小超过2MB!`)
                    // 从fileList中移除该文件
                    const index = fileList.indexOf(file);
                    if (index > -1) {
                        fileList.splice(index, 1);
                    }
                    this.fileList = [...fileList];
                    return
                }

                // 如果已经有文件在列表中（不包括当前新添加的），需要验证电子签名
                const existingFiles = fileList.filter(f => f !== file && f.status === 'success');
                if (existingFiles.length > 0) {
                    // 保存待上传的文件信息
                    this.pendingUploadFile = file;

                    // 从fileList中暂时移除新文件，等待签名验证
                    const index = fileList.indexOf(file);
                    if (index > -1) {
                        fileList.splice(index, 1);
                    }
                    this.fileList = [...fileList];

                    // 触发电子签名弹窗
                    EventBus.$emit('showEditSignDialog', { uuid: this.uuid });
                    return;
                }

                // 没有现有文件或验证通过，手动提交上传
                this.$nextTick(() => {
                    // 找到对应的upload组件并提交
                    const uploadComponent = this.$refs.uploadRef;
                    if (uploadComponent) {
                        uploadComponent.submit();
                    }
                });
            }

            // 更新fileList
            this.fileList = fileList;
        },
        handleSuccess(res, file, fileList) {
            if (res.code == 200) {
                this.fileList = fileList;
                // 更新inputValue为文件路径列表，方便后续保存
                this.inputValue = JSON.stringify(this.getFileList(fileList));
                this.$emit("change", this.inputValue)
                this.onCommonHandleSaveRecord();
                this.$message.success('文件上传成功');
            } else {
                this.$message.error(res.message || '文件上传失败');
                // 上传失败，从列表中移除
                const index = fileList.indexOf(file);
                if (index > -1) {
                    fileList.splice(index, 1);
                    this.fileList = [...fileList];
                }
            }
        },
        getFileList(fileList) {
            const list = [];
            fileList.forEach(item => {
                const o = { name: item.name };
                if (item.url) {//回填的数据
                    o.url = item.url
                } else {//新上传的
                    o.url = item.response.data.url
                }
                list.push(o)
            })
            return list;
        },
        // 删除前验证电子签名
        beforeRemove(file) {
            // 所有删除操作都需要验证电子签名
            // 保存待删除的文件信息
            this.pendingRemoveFile = { file, fileList: this.fileList };
console.log("fillll")
            // 触发电子签名弹窗
            EventBus.$emit('showEditSignDialog', { uuid: this.uuid });

            // 返回false阻止默认删除行为，等待签名验证通过后再删除
            return false;
        },
        handleRemove(file, fileList) {
            // on-remove事件在before-remove返回false时不会触发
            // 这个方法在签名验证通过后通过executeRemove调用
            // 这里不需要额外处理，因为executeRemove已经处理了删除逻辑
        },
        // 执行实际的文件删除操作
        executeRemove(file, fileList) {
            // 从el-upload的内部uploadFiles中移除文件
            const uploadComponent = this.$refs.uploadRef;
            if (uploadComponent && uploadComponent.uploadFiles) {
                const uploadFileIndex = uploadComponent.uploadFiles.indexOf(file);
                if (uploadFileIndex > -1) {
                    uploadComponent.uploadFiles.splice(uploadFileIndex, 1);
                }
            }

            // 从fileList中移除文件
            const index = fileList.indexOf(file);
            if (index > -1) {
                fileList.splice(index, 1);
            }

            // 更新fileList
            this.fileList = [...fileList];

            // 更新inputValue为剩余文件路径列表
            this.inputValue = JSON.stringify(this.getFileList(fileList));
            this.$emit("change", this.inputValue);

            // 触发保存记录
            this.onCommonHandleSaveRecord();

            this.$message.success(`文件 ${file.name} 已移除`);
        },
        handlePreview(file) {
            console.log(file)
            const url = file.url || file.response?.data?.url;
            if (url) {
                window.open(process.env.VUE_APP_FILE_DOMAIN + url, '_blank');
            }
        },
        handleExceed(files, fileList) {
            this.$message.warning(`当前限制选择 10 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
        },
        //试剂弹窗提交
        onMixReagentSubmit(data) {
            if (data.uuid !== this.uuid) return;

            // 创建一个验证控制器，用于收集各级验证结果
            const validationController = {
                isPrevented: false,
                errorMsg: '',
                prevent(msg) {
                    this.isPrevented = true;
                    if (msg) this.errorMsg = msg;
                }
            };

            // 触发自定义验证事件，让父组件判断是否满足需求
            // 父组件可以通过validationController.prevent(msg)来阻止提交
            this.$emit('beforeReagentSubmit', data, validationController);

            // 检查是否被阻止
            if (validationController.isPrevented) {
                // 验证不通过，显示错误信息
                if (validationController.errorMsg) {
                    this.$message.error(validationController.errorMsg);
                }
                return;
            }

            // 验证通过，继续执行
            this.executeReagentSubmit(data);
        },

        // 执行试剂提交的共同逻辑
        executeReagentSubmit(data) {
            this.inputValue = data.selectedId;
            const { filledCodes = [] } = this.item;
            console.log(filledCodes, "filledCodes")
            const { selectInfo, row,checkType } = data;
            if (filledCodes.length > 0 && checkType !=="checkbox") {
                this.inputValue = row[filledCodes[0]] + "(" + row[filledCodes[1]] + ")";
            }
            this.selectRegentInfo = data;
            EventBus.$emit("hideSelectMixReagentDialog");
            this.onCommonHandleSaveRecord(this.inputValue);
        },
        //统一处理试剂/供试品等弹窗
        onCommonHandleRegent(item, type) {
            const {fillType = "actFill"} = item;
            if (this.templateFillType !== fillType) {
                return
            }
            let params = {
                studyFormId: this.templateData.id,
                uuid: this.uuid,
                sourceFrom: this.sourceFrom,
            }
            let eventName = "showSelectMixReagentDialog";
            if (type === "yq") {
                eventName = "showSelectInstrumentDialog";
            } else {
                const sjType = {
                    sj: "1",//试剂
                    gsp: "7",//供试品
                    mix: "1",//试剂/供试品/试剂
                    gyzj: "3",//给药制剂
                    mjy: "5",//麻精药
                    xj: "9",//细菌
                    xb: "11",//细胞
                    jcb: "13",//检测板
                    qxbd: "15",//前序表单
                }
                params = {
                    ...params,
                    type: sjType[type]
                };
                if (type === "mix") {
                    params.mixType = true;
                } 
                if (item.qxbdType) {
                    params.qxbdType = item.qxbdType;
                } 
                if (item.checkType) {
                    params.checkType = item.checkType;
                }
            }
            EventBus.$emit(eventName, params)
            // this.$emit('regent', item,type);
        },
        // 点击按钮
        handleClickButton(item) {
            this.inputValue = `button-${new Date().getTime()}`;
            this.onCommonHandleSaveRecord(this.inputValue);
        },
        onDateChange(val, format) {
            if (this.type === 'dateTimeRange') {
                this.inputValue = [moment(val[0]).format(format), moment(val[1]).format(format)];
            }else{
                this.inputValue = moment(val).format(format);
            }
            this.onCommonHandleSaveRecord(this.inputValue);
        },
        getUserName(record) {
            const locale = this.$i18n.locale;
            if (locale === 'zh_CN') {
                return record.userNameCn;
            }
            return record.userNameEn;
        },
        // 处理电子签名取消事件
        handleEditSignCancel(data) {
            if (data.uuid === this.uuid) {
                // 如果有待上传的文件，清空它
                if (this.pendingUploadFile) {
                    this.pendingUploadFile = null;
                    this.$message.info('已取消文件上传');
                } else if (this.pendingRemoveFile) {
                    // 如果有待删除的文件，清空它
                    this.pendingRemoveFile = null;
                    this.$message.info('已取消文件删除');
                } else {
                    this.resetRecord();
                }
            }
        },
        // 处理电子签名确认回调事件
        handleEditSignCallback(data) {
            if (data.uuid === this.uuid) {
                this.onEditSignSave(data.data);
            }
        },
        onEditSignSave(data) {
            // 检查是否有待上传的文件
            if (this.pendingUploadFile) {
                // 签名验证通过，将文件添加到列表并上传
                const file = this.pendingUploadFile;

                // 将文件添加到 fileList
                this.fileList.push(file);

                // 清空待上传文件标记
                this.pendingUploadFile = null;

                // 手动触发上传
                this.$nextTick(() => {
                    const uploadComponent = this.$refs.uploadRef;
                    if (uploadComponent) {
                        uploadComponent.submit();
                    }
                });
            } else if (this.pendingRemoveFile) {
                // 签名验证通过，执行文件删除
                const { file, fileList } = this.pendingRemoveFile;

                // 清空待删除文件标记
                this.pendingRemoveFile = null;

                // 执行删除操作
                this.executeRemove(file, fileList);
            } else {
                // 没有待上传/删除文件，执行正常的记录更新
                this.handleUpdateRecord(data);
            }
        },
        getChecked() {
            return !!this.getFieldCheckObj()[this.fieldKey]?.checked;
        },
        getFillTypeStyle(type) {
            const { fillType } = this.item;
            const filterType = ["attachment", "checkboxTag", "fqyq", "checkboxTree","radio"]
            const typeObj = {
                actFill: "orange-border",//实际填写的边框颜色
                blxjsh: "orange-border",//实际填写的边框颜色
                green: "green-border",
                preFill: "blue-border",//预填写的边框颜色
            }
            // 如果有错误状态，返回红色边框样式，覆盖原有的边框颜色
            if (this.error && !filterType.includes(this.type)) {
                return "error-border";
            }
            return typeObj[fillType] || ""
        },
        //确认回复
        onReplyConfirm() {
            if (!this.replyContent) {
                this.$message({
                    message: '请输入内容',
                    type: 'error'
                });
                return;
            }
            const baseInfo = this.getCommonRecordInfo();
            const record = {
                ...baseInfo,
                title: (this.templateFillType == 'actFill' || this.templateFillType == 'blxjsh') ? "意见回复" : "复核意见",
                time: moment().format("YYYY-MM-DD HH:mm:ss"),
            }
            if (this.templateFillType == 'actFill' || this.templateFillType == 'blxjsh') {
                record.reply = this.replyContent;
                const deepList = deepClone(this.getFhyjjl());//实际填报应该是修改指定的字段
                const item = deepList.find(o => o.key == record.key);
                if (item) {
                    item.reply = this.replyContent;
                }
                this.replaceFhyjjl(deepList);//实际填报应该是修改指定的字段
            } else {
                const records = this.getReplyRecords();
                record.content = this.replyContent;
                if (records.length > 0) {
                    const o = records[0];
                    if (o.reply && o.content) {//如果填报人员已回复，那么就产生一条新的记录。
                        this.updateFhyjjl(record);//qc直接插入数据源
                    } else {//如果填报人员未填报，只更新当条记录的复核内容
                        const deepList = deepClone(this.getFhyjjl());
                        const item = deepList.find(it => it.key == record.key);
                        if (item) {
                            item.content = this.replyContent;
                        }
                        this.replaceFhyjjl(deepList);
                    }
                } else {
                    this.updateFhyjjl(record);//qc直接插入数据源
                }

            }
            const params = {
                //reply:回复，content:复核
                type: (this.templateFillType == 'actFill' || this.templateFillType == 'blxjsh') ? "reply" : "content",
                newRecord: [record],
                resourceList: this.getFhyjjl(),
            }
            // 触发回复记录事件
            EventBus.$emit('onModifyRecord', params);
            // 清空回复内容
            this.replyContent = '';
            // 隐藏弹窗
            this.visible = false;

        },
        //获取question图标颜色
        getQuestionColor() {
            const records = this.getReplyRecords();
            if (records.length > 0) {
                const o = records[0];
                if (o.reply && o.content) {//有意见回复和复核意见
                    return "green"
                } else if (o.content && !o.reply) {//只有复核意见
                    return "orange"
                } else {
                    return "gray"
                }
            } else {//没有回复记录
                return "gray"
            }

        },
        // 复选框变化处理
        onCheckboxChange(val) {
            //有提出意见就不能勾选
            if (this.templateFillType == 'qc' && this.getQuestionColor() === "orange") {
                this.checkboxValue = false;
                this.$message({
                    message: '该表单还有质疑项未处理，无法勾选',
                    type: 'error'
                });
                return;
            }
            this.checkboxValue = val;
            // 触发修改记录事件
            EventBus.$emit('onModifyRecord', {
                type: "checkbox",
                fieldCheckObj: JSON.stringify({ ...this.getFieldCheckObj(), [this.fieldKey]: { checked: val } }),//复选框状态对象
            });
            this.updateFieldCheckObj({ [this.fieldKey]: { checked: val } });
            // this.$emit('input', val);
            // this.$emit('change', val);
        },
        onRemoveTag(e) {
            this.onCommonHandleSaveRecord(this.inputValue);
        },
        onItemCheckboxChange() {
            this.onCommonHandleSaveRecord(this.inputValue);
        },
        // 下拉框失去焦点处理
        onSelectBlur(visible) {
            if (!visible) {
                this.onCommonHandleSaveRecord(this.inputValue);
            }
        },
        // 统一处理输入变化
        onInputChange(val) {
            let value = val !== undefined ? val : this.inputValue;
            this.$emit('input', value);
            this.$emit('change', value);

            // 根据输入值判断是否显示错误状态
            const isEmpty = isValueEmpty(value);
            if (this.error && !isEmpty) {
                this.$emit('update:error', false);
            } else if (!this.error && isEmpty) {
                this.$emit('update:error', true);
            }
        },
        // checkboxTag的checkbox变化处理
        onCheckboxTagChange(tagIndex, e) {
            this.currentTagIndex = tagIndex;
            this.checkboxTagList[tagIndex].checked = e;
            this.emitCheckboxTagValue();
            this.onCommonHandleSaveRecord();
        },

        // tag输入框失去焦点
        onTagBlur(tagIndex) {
            this.currentTagIndex = tagIndex;
            const value = this.checkboxTagList[tagIndex].tagValue;
            this.emitCheckboxTagValue();
            this.onCommonHandleSaveRecord(value);
        },
        // 删除tag
        onDeleteTag(tagIndex) {
            this.currentTagIndex = tagIndex;
            // 从列表中删除指定索引的tag
            this.emitCheckboxTagValue();
            this.$emit("deleteTag", tagIndex);
        },
        // 发送checkboxTag的值
        emitCheckboxTagValue() {
            // 发送整个数组
            this.$emit('input', [...this.checkboxTagList]);
            this.$emit('change', [...this.checkboxTagList]);
        },

        // fqyq 主radio变化处理
        onFqyqRadioChange(val, radioType) {
            this.fqyqValue[radioType] = val;
            this.currentHandleType = radioType;
            this.onCommonHandleSaveRecord();
        },

        // fqyq 输入框失去焦点
        onFqyqInputBlur(e) {
            this.fqyqValue.inputValue = e.target.value;
            this.currentHandleType = 'inputValue';
            this.onCommonHandleSaveRecord(this.fqyqValue.inputValue);
        },

        // 统一处理失去焦点事件
        onBlur(e) {
            this.onCommonHandleSaveRecord(e.target.value);
        },

        // 检查checkboxTree的某个值是否被选中
        isCheckboxTreeChecked(value) {
            if (!this.inputValue || !this.inputValue.checkedValues) {
                return false;
            }
            const checkedItem = this.inputValue.checkedValues.find(item => item.label === value);
            return checkedItem && checkedItem.checked;
        },

        // 检查checkboxTree的其他输入框是否有错误
        isCheckboxTreeOtherInputError(value) {
            if (!this.error) {
                return false;
            }
            return isValueEmpty(this.inputValue.otherValues[value]);
        },

        // 获取checkboxTree的选中值
        getCheckboxTreeChecked(value) {
            const { checkedValues } = this.inputValue
            const o = checkedValues.find(item => item.label === value) || {};
            return !!o.checked;
        },

        // 获取或创建checkedItem
        getOrCreateCheckedItem(value) {
            let checkedItem = this.inputValue.checkedValues.find(item => item.label === value);
            if (!checkedItem) {
                checkedItem = { label: value, checked: false };
                this.inputValue.checkedValues.push(checkedItem);
            }
            return checkedItem;
        },

        // 父级checkbox变化处理
        onCheckboxTreeParentChange(group, checked) {
            this.currentHandleType = 'checkboxTreeCheckbox';
            this.currentCheckboxTreeValue = group.value;

            // 设置父级状态
            const parentItem = this.getOrCreateCheckedItem(group.value);
            parentItem.checked = checked;

            // 同步所有子级状态
            if (group.children && group.children.length > 0) {
                group.children.forEach(child => {
                    const childItem = this.getOrCreateCheckedItem(child.value);
                    childItem.checked = checked;
                    // 如果取消选中，清除otherValues
                    if (!checked) {
                        delete this.inputValue.otherValues[child.value];
                    }
                });
            }

            this.onCommonHandleSaveRecord();
        },

        // 子级checkbox变化处理
        onCheckboxTreeChildChange(group, childValue, checked) {
            this.currentHandleType = 'checkboxTreeCheckbox';
            this.currentCheckboxTreeValue = childValue;

            // 设置子级状态
            const childItem = this.getOrCreateCheckedItem(childValue);
            childItem.checked = checked;

            // 如果取消选中，清除otherValues
            if (!checked) {
                delete this.inputValue.otherValues[childValue];
            }

            // 更新父级状态
            this.updateParentState(group);

            this.onCommonHandleSaveRecord();
        },

        // 更新父级状态（根据子级状态）
        updateParentState(group) {
            if (!group.children || group.children.length === 0) return;

            const parentItem = this.getOrCreateCheckedItem(group.value);
            const childValues = group.children.map(child => child.value);

            // 统计子级选中状态
            let checkedCount = 0;
            let totalCount = childValues.length;

            childValues.forEach(childValue => {
                const childItem = this.inputValue.checkedValues.find(item => item.label === childValue);
                if (childItem && childItem.checked) {
                    checkedCount++;
                }
            });

            // 根据子级状态设置父级状态
            if (checkedCount === 0) {
                // 全部未选中，父级取消选中
                parentItem.checked = false;
            } else if (checkedCount === totalCount) {
                // 全部选中，父级选中
                parentItem.checked = true;
            }
            // 部分选中时，父级保持当前状态（由indeterminate显示半选）
        },

        // 获取父级的半选状态
        getCheckboxTreeIndeterminate(groupValue) {
            if (!this.inputValue || !this.inputValue.checkedValues) {
                return false;
            }

            // 找到对应的group
            const group = this.item.options.find(opt => opt.value === groupValue);
            if (!group || !group.children || group.children.length === 0) {
                return false;
            }

            const childValues = group.children.map(child => child.value);
            let checkedCount = 0;

            childValues.forEach(childValue => {
                const childItem = this.inputValue.checkedValues.find(item => item.label === childValue);
                if (childItem && childItem.checked) {
                    checkedCount++;
                }
            });

            // 半选状态：有子级被选中但不是全部
            return checkedCount > 0 && checkedCount < childValues.length;
        },

        // checkboxTree的其他输入框失去焦点处理
        onCheckboxTreeOtherBlur(value, e) {
            this.currentHandleType = "checkboxTreeOther";
            this.currentCheckboxTreeValue = value;
            this.inputValue.otherValues[value] = e.target.value;
            this.onCommonHandleSaveRecord(e.target.value);
        },

        // 点击question图标
        onClickQuestion() {
            const { templateFillType } = this;
            if (templateFillType == 'actFill' || templateFillType == 'qc' || templateFillType == 'blxjsh') {
                if (templateFillType == 'qc') {
                    const field = this.getFieldCheckObj()[this.fieldKey];
                    if (field && field.checked) {
                        this.$message({
                            message: '该字段已勾选复核框，请先取消勾选后再进行提交疑问',
                            type: 'error'
                        });
                        return;
                    }
                }
                const records = this.getReplyRecords();
                let content = "";
                if (records.length > 0) {
                    const o = records[0];
                    if (!o.reply && templateFillType == 'qc') {//如果填报人员没有回复，qc点击的时候需要回填上次填报的信息
                        content = o.content;
                    } else if (templateFillType == 'actFill' || templateFillType == 'blxjsh') {//如果qc没有复核，填报点击的时候需要回填上次填报的信息
                        content = o.reply;
                    }
                }
                this.replyContent = content;
                this.visible = true;
            }
        },
        getFqyqInfo() {
            const { mainRadio, inputValue, subRadio } = this.fqyqValue;
            const { mainRadio: oldMainRadio, inputValue: oldInputValue, subRadio: oldSubRadio } = this.oldFqyqValue;
            const o = {
                "mainRadio": { oldValue: oldMainRadio, newValue: mainRadio, des: "" },
                "inputValue": { oldValue: oldInputValue, newValue: inputValue, des: "",key: this.fieldKey+"_inputValue" },
                "subRadio": { oldValue: oldSubRadio, newValue: subRadio, des: "是否在规定时间完成：" }
            }
            console.log(o, this.currentHandleType, this.fqyqValue,"fqyqValue")
            return o[this.currentHandleType];
        },
        getCheckboxTreeInfo() {
            const { checkedValues, otherValues } = this.inputValue;
            const { checkedValues: oldCheckedValues, otherValues: oldOtherValues } = this.oldValue;
            const { currentHandleType, currentCheckboxTreeValue } = this;
            const newItem = checkedValues.find(item => item.label === currentCheckboxTreeValue);
            const oldItem = oldCheckedValues.find(item => item.label === currentCheckboxTreeValue);
            const o = {
                "checkboxTreeCheckbox": { oldValue: oldItem, newValue: newItem, des: "" },
                "checkboxTreeOther": { oldValue: oldOtherValues[currentCheckboxTreeValue], newValue: otherValues[currentCheckboxTreeValue], des: `${currentCheckboxTreeValue}：`,key: this.fieldKey+"_"+currentCheckboxTreeValue },
            }
            return o[currentHandleType];
        },
        async onCommonHandleSaveRecord(val) {
            const isEmpty = isValueEmpty(this.inputValue);
            if (this.error && !isEmpty) {
                this.$emit('update:error', false);
            } else if (!this.error && isEmpty) {
                this.$emit('update:error', true);
            }

            // 创建验证控制器，让父组件可以在保存前进行验证
            const validationController = {
                isPrevented: false,
                errorMsg: '',
                prevent(msg) {
                    this.isPrevented = true;
                    if (msg) this.errorMsg = msg;
                }
            };

            // 触发beforeSaveRecord事件，让父组件进行验证
            this.$emit('beforeSaveRecord', {
                value: this.inputValue,
                oldValue: this.oldValue,
                fieldKey: this.fieldKey
            }, validationController);

            // 检查是否被阻止
            if (validationController.isPrevented) {
                // 验证不通过，显示错误信息
                if (validationController.errorMsg) {
                    this.$message.error(validationController.errorMsg);
                }
                // 回退到旧值
                this.inputValue = this.oldValue;
                this.$emit('input', this.inputValue);
                return;
            }

            if (!this.isFieldsRecord) {//是否需要记录修改记录
                this.$emit("blur", this.inputValue);
                this.$emit('input', this.inputValue);
                this.$emit("change", this.inputValue);
                return;
            }
            // 值发生了变化，需要弹出密码输入框
            let isSame = true, isOldValueEmpty = true;
            const { currentHandleType } = this;
            if (this.type === "checkboxTag") {
                // checkboxTag类型，只比较当前tagIndex的数据
                const currentTag = this.checkboxTagList[this.currentTagIndex];
                const oldTag = this.oldCheckboxTagList[this.currentTagIndex] || {};
                isSame = isEqual(oldTag.checked, currentTag.checked);
                isOldValueEmpty = oldTag.checked === undefined;
            } else if (this.type === "fqyq") {
                const current = this.getFqyqInfo();
                isSame = isEqual(current.oldValue, current.newValue);
                if(this.currentHandleType === "inputValue"){
                    isOldValueEmpty =this.isUnSubmitted(current.key);
                }else{
                    isOldValueEmpty = isValueEmpty(current.oldValue);
                }
            } else if (this.type === "checkboxTree") {
                const current = this.getCheckboxTreeInfo() || {};
                const { oldValue = {}, newValue = {} } = current;
                if (currentHandleType === "checkboxTreeCheckbox") {
                    isSame = isEqual(oldValue.checked, newValue.checked);
                    isOldValueEmpty = oldValue.checked === undefined;
                } else {
                    isSame = isEqual(current.oldValue, current.newValue);
                    isOldValueEmpty = this.isUnSubmitted(current.key);
                }


            } else if(this.type === "checkbox"){
                isSame = isEqual(this.oldValue, this.inputValue)
                isOldValueEmpty =this.isUnSubmitted();
            }else {
                isSame = isEqual(this.oldValue, this.inputValue)
                isOldValueEmpty = this.isUnSubmitted();
            }
            console.log(isSame, isOldValueEmpty, this.currentCheckboxTreeValue, this.oldValue, this.inputValue, "isSame")
            if (isSame) {
                return;
            }
            if (!isOldValueEmpty && !(isSame) && (this.templateFillType === "actFill" || this.templateFillType === "blxjsh")&&this.type !== "attachment") {
                console.log("需要电子签名")
                // 通过EventBus触发电子签名弹窗
                EventBus.$emit('showEditSignDialog', { uuid: this.uuid });
            } else {//如果是第一次填写，不需要密码验证
                this.handleUpdateRecord()
            }
        },

        //是否提交过
        isUnSubmitted(key){
            const finallyKey = key || this.fieldKey;
            const has =  this.getSubmittedCodes().includes(finallyKey)
            return !has;
        },

        //如果用户取消，那么回退到上一次的值
        resetRecord() {
            // 用户点击取消，还原数据
            let oldValue = this.oldValue;
            if (this.type === "checkboxTag") {
                // checkboxTag类型，只回退当前tagIndex的数据
                if (this.currentTagIndex >= 0 && this.currentTagIndex < this.oldCheckboxTagList.length) {
                    const oldTag = this.oldCheckboxTagList[this.currentTagIndex];
                    this.checkboxTagList[this.currentTagIndex] = { ...oldTag };
                    oldValue = [...this.checkboxTagList];
                } else {
                    // 如果没有指定tagIndex，回退整个数组
                    this.checkboxTagList = JSON.parse(JSON.stringify(this.oldCheckboxTagList));
                    oldValue = [...this.checkboxTagList];
                }
            } else if (this.type === "fqyq") {
                // 如果没有指定字段，回退整个对象
                this.fqyqValue = JSON.parse(JSON.stringify(this.oldFqyqValue));
                oldValue = { ...this.fqyqValue };
            }
            this.inputValue = typeof oldValue === 'object' ? JSON.parse(JSON.stringify(oldValue)) : oldValue;
            this.$emit('input', oldValue); // 触发 v-model 更新
            // this.$emit("blur", this.oldValue);
            this.$emit("change", oldValue, "cancel");
        },

        //处理更新记录
        handleUpdateRecord(data, recordData) {
            const baseInfo = this.getCommonRecordInfo();
            //有recordData表示从组件外部调用的更新操作，
            if (!this.oldValue && !this.inputValue && !recordData) {
                return
            }
            let finallyKey = this.fieldKey;
            if (recordData) {
                this.oldValue = recordData.oldValue;
                this.inputValue = recordData.inputValue;
            }
            let recordOldVlaue = this.oldValue, recordValue = this.inputValue, isModify = !!this.oldValue;
            if (this.type === "checkboxTag") {
                // checkboxTag类型，只记录当前tagIndex的数据变化
                const oldTag = this.oldCheckboxTagList[this.currentTagIndex] || {};
                const currentTag = this.checkboxTagList[this.currentTagIndex] || {};
                recordOldVlaue = `${oldTag.tagValue || ''}:${oldTag.checked ? '勾选' : '未勾选'}`;
                recordValue = `${currentTag.tagValue || ''}:${currentTag.checked ? '勾选' : '未勾选'}`;
                isModify = oldTag.checked !== undefined;
            } else if (this.type === "fqyq") {
                const current = this.getFqyqInfo();
                recordOldVlaue = `${current.des + current.oldValue}`;
                recordValue = `${current.des + current.newValue}`;
                if(this.currentHandleType === "inputValue"){
                    finallyKey = current.key;
                }
                isModify = !!this.oldFqyqValue.mainRadio
            } else if (this.type === "checkboxTree") {
                // checkboxTree类型，记录当前操作的值变化
                const current = this.getCheckboxTreeInfo();
                if (this.currentHandleType === "checkboxTreeCheckbox") {
                    const { oldValue = {}, newValue = {} } = current;
                    recordOldVlaue = `${oldValue?.label || ''}:${oldValue?.checked ? '勾选' : '未勾选'}`;
                    recordValue = `${newValue.label || ''}:${newValue.checked ? '勾选' : '未勾选'}`;
                    isModify = newValue.checked !== undefined;
                    finallyKey = current.key;
                } else {
                    recordOldVlaue = `${current.des + (current.oldValue || '')}`;
                    recordValue = `${current.des + (current.newValue || '')}`;
                    isModify = !!current.oldValue;
                }
            }else if(this.type === "checkbox"){
                recordOldVlaue = `${this.item.checkboxLabel || ""}:${this.oldValue?'勾选':'未勾选'}`;
                recordValue = `${this.item.checkboxLabel||""}:${this.inputValue?'勾选':'未勾选'}`;
                isModify = this.oldValue !== '';
            }else if(this.type === "attachment"){
                const attList = JSON.parse(recordValue);
                const oldAttList = JSON.parse(recordOldVlaue || "[]");
                recordValue = attList.map(item => item.name).join(";");
                recordOldVlaue = oldAttList.map(item => item.name).join(";");
            }

            const record = {
                ...baseInfo,
                oldValue: recordOldVlaue,
                value: recordValue,
                title: !this.isUnSubmitted(finallyKey) ? "修改" : "提交",
                time: moment().format("YYYY-MM-DD HH:mm:ss"),
            }
            if (data) {
                record.reason = data.remark
            }

            const params = {
                type: "fieldChanged",
                newRecord: [record],
                submittedCodes: this.getSubmittedCodes(),
                resourceList: this.getZdxgjl(),
            }

            // 更新oldValue和oldOtherValues
            if (this.type === "checkboxTag") {
                // checkboxTag类型，只更新当前tagIndex的数据
                if (this.currentTagIndex >= 0 && this.currentTagIndex < this.checkboxTagList.length) {
                    this.oldCheckboxTagList[this.currentTagIndex] = { ...this.checkboxTagList[this.currentTagIndex] };
                } else {
                    // 如果没有指定tagIndex，更新整个数组
                    this.oldCheckboxTagList = JSON.parse(JSON.stringify(this.checkboxTagList));
                }
            } else if (this.type === "fqyq") {
                // 如果没有指定字段，更新整个对象
                this.oldFqyqValue = JSON.parse(JSON.stringify(this.fqyqValue));
            }
            let value = this.inputValue;
            if (this.type === "checkboxTag") {
                value = [...this.checkboxTagList];
            } else if (this.type === "fqyq") {
                value = { ...this.fqyqValue };
            }
            if (this.type === "button") {
                this.$emit('clickButton', this.item, this.inputValue, data);
                if (this.templateFillType === "preFill") {
                    return;
                }
            }
            //用户输入密码并点击确定，保存修改
            this.oldValue = typeof value === 'object' ? JSON.parse(JSON.stringify(value)) : value; // 更新旧值
            this.$emit("blur", value);
            this.$emit('input', value);
            this.$emit("change", value, data ? "save" : "");
            if (this.item.type === "clickable") {//clickable的丢给父级去处理
                return;
            }

            if (this.templateFillType === "actFill" || this.templateFillType === "blxjsh") {//只有实际填报的时候才记录修改记录
                this.updateZdxgjl(record);
                this.updateSubmittedCodes(finallyKey);
            }
            this.$nextTick(() => {
                EventBus.$emit('onModifyRecord', params,)
                console.log(params, "onModifyRecord")
                if (isRegent(this.item)) {
                    this.$emit("onRegentSubmit", this.selectRegentInfo, this.inputValue);
                }
            })
        },

        //获取公共记录信息
        getCommonRecordInfo() {
            const { nickName, name } = this.$store.getters;
            //locale:zh-CN 中文 en-US 英文
            const { label, parentLabel } = this.item;
            let fieldLabelCn = this.$i18n.t(label, "zh_CN"), fieldLabelEn = this.$i18n.t(label, "en_US");
            if (label === "template.common.other") {
                fieldLabelCn = this.$i18n.t(parentLabel, "zh_CN") + this.$i18n.t("template.common.otherInfo", "zh_CN");
                fieldLabelEn = this.$i18n.t(parentLabel, "en_US") + this.$i18n.t("template.common.otherInfo", "en_US");
            } else if (!label && parentLabel == "template.common.remark") {
                fieldLabelCn = this.$i18n.t(parentLabel, "zh_CN") + this.$i18n.t("template.common.unit", "zh_CN");
                fieldLabelEn = this.$i18n.t(parentLabel, "en_US") + this.$i18n.t("template.common.unit", "en_US");
            }
            const commonInfo = {
                userNameCn: nickName,
                userNameEn: name,
                key: this.fieldKey,
                fieldCn: `${this.$i18n.t(this.fieldItemLabel, "zh_CN")}` + (fieldLabelCn ? ("-" + fieldLabelCn) : ""),
                fieldEn: `${this.$i18n.t(this.fieldItemLabel, "en_US")}` + (fieldLabelEn ? ("-" + fieldLabelEn) : ""),
            }
            return commonInfo;
        },
        handleClickable(item, event) {
            if (this.templateFillType !== 'actFill') {
                return
            }
            this.$emit("clickable", item)
        },
        //判断是否禁用复选框
        getCheckboxDisabled() {
            //只有qc能操作checkbox，其他都只能看。
            return this.templateFillType !== 'qc'
        },
        //判断是否显示复选框图标
        getIsShowCheckboxIcon() {
            if (this.templateFillType === 'qc') {
                return true;
            }
            return this.getChecked();
        },
        //判断是否显示复制按钮
        getIsShowCopyIcon() {
            const { copyFrom } = this.item;
            return copyFrom && this.templateFillType === "actFill";
        },
        //判断是否显示操作按钮
        isShowHandle() {
            const { fillType } = this.item;
            //只有当模板状态不是预填时，才显示操作按钮
            return this.templateFillType !== "preFill" && (fillType === "actFill" || fillType === "blxjsh") && this.type !== "button"
        },
        //判断是否禁用
        getDisabled() {
            const { item } = this;
            const { fillType } = item;
            if (item.hasOwnProperty("disabled")) {
                return item.disabled
            } else {
                if (fillType === "actFill") {//当模板状态是实际填写时，只有当fillType是actFill时才能填写
                    return this.templateFillType !== "actFill"
                } else if (fillType === "preFill") {//当模板状态是预填写时，只有当fillType是preFill才能填写
                    return this.templateFillType !== "preFill"
                } else if (fillType === "blxjsh") {//当模板状态是预填写时，只有当fillType是blxjsh才能填写
                    return this.templateFillType !== "blxjsh"
                }else {
                    return true
                }
            }
        },
        getPlaceholder() {
            const { placeholder, label } = this.item;
            const { type } = this;
            if (this.getDisabled()) {
                return ""
            }
            if (isRegent(this.item) || type === "clickable" || type === "fqyq") {
                return this.$t("template.common.pleaseSelect")
            }
            let prex = "template.common.pleaseFillIn"
            if (type === "select" || type === "dateTime" || type === "datePicker") {
                prex = "template.common.pleaseSelect"
            }
            return placeholder ? this.$t(placeholder) : (this.$t(prex) + this.$t(label))

        },
        async onCopy() {
            // 触发复制事件
            this.$emit("copy");
            // 等待复制操作完成后，调用保存记录方法
            this.$nextTick(async () => {
                await this.onCommonHandleSaveRecord(this.inputValue);
            });
        },
        //判断是否显示问题图标
        getIsShowQuestionIcon() {
            if (this.templateFillType === "qc") {//qc可以直接查看
                return true;
            }
            return this.getReplyRecords().length > 0;

        },
        //判断是否显示修改记录图标
        getIsShowRecordIcon() {
            return this.getModifyRecords().length > 0
        },
        //获取回复记录
        getReplyRecords() {
            const { fieldKey, getFhyjjl } = this;
            const records = getFhyjjl()?.filter(item => item.key === fieldKey) || [];
            return records;
        },
        //获取字段修改记录
        getModifyRecords() {
            const { fieldKey, getZdxgjl } = this;
            const records = getZdxgjl().filter(item => item.key === fieldKey);
            return records;
        },
        // 鼠标进入主容器
        async onMouseEnter(type, event) {
            this.currentRecordType = type;
            clearTimeout(this.modalTimer);
            let record = [];
            if (type === "fieldChanged") {
                record = this.getModifyRecords();
            } else if (type === "replyRecord") {
                record = this.getReplyRecords();
            }
            this.modificationRecords = record;
            // 先计算模态框位置，避免闪烁
            this.showModal = true;
            this.$nextTick(() => {
                if (this.$refs.modalRef) {
                    const elementRect = event.target.getBoundingClientRect();
                    const modalEl = this.$refs.modalRef;

                    // 获取模态框的宽度和高度
                    const modalWidth = modalEl.offsetWidth || 250; // 默认宽度
                    const modalHeight = modalEl.offsetHeight || 300; // 默认高度
                    const viewportWidth = window.innerWidth;
                    const viewportHeight = window.innerHeight;

                    // 计算模态框位置
                    let leftPos, topPos;

                    // 检查右侧空间是否足够
                    if (elementRect.right + modalWidth + 5 <= viewportWidth) {
                        // 右侧空间充足，显示在右侧
                        leftPos = elementRect.right + 5 + 'px';
                    } else if (elementRect.left - modalWidth - 5 >= 0) {
                        // 左侧空间充足，显示在左侧
                        leftPos = elementRect.left - modalWidth - 5 + 'px';
                    } else {
                        // 两侧空间都不足，选择空间更大的一边
                        if (elementRect.left > viewportWidth - elementRect.right) {
                            // 左侧空间更大，显示在左侧
                            leftPos = Math.max(5, elementRect.left - modalWidth - 5) + 'px';
                        } else {
                            // 右侧空间更大，显示在右侧（可能会超出屏幕，但尽量靠近边缘）
                            leftPos = Math.min(elementRect.right + 5, viewportWidth - 5) + 'px';
                        }
                    }

                    // 计算顶部位置，确保不超出屏幕上下边界
                    topPos = Math.max(5, Math.min(elementRect.top, viewportHeight - modalHeight - 5)) + 'px';

                    // 设置模态框位置
                    modalEl.style.left = leftPos;
                    modalEl.style.top = topPos;
                }
            });
        },

        // 鼠标离开主容器
        onMouseLeave() {
            // this.currentRecordType = '';
            // this.modificationRecords = [];//清空数据源
            // 延迟隐藏模态框，让用户有机会移动到模态框上
            this.modalTimer = setTimeout(() => {
                if (!this.isHoveringModal) {
                    this.showModal = false;
                }
            }, 100);
        },

        // 鼠标进入模态框
        onModalEnter() {
            this.isHoveringModal = true;
            clearTimeout(this.modalTimer);
        },

        // 鼠标离开模态框
        onModalLeave() {
            this.isHoveringModal = false;
            this.currentRecordType = "";
            this.modificationRecords = [];//清空数据源
            this.modalTimer = setTimeout(() => {
                this.showModal = false;
            }, 100);
        },
    },
}
</script>

<style lang="scss">
.flex {
    display: flex;
    align-items: center;
}

.flex1 {
    flex: 1;
}

.handle-row {
    margin-left: 5px;
    display: flex;
    align-items: center;
    cursor: pointer;
}

.w-100 {
    width: 100%;
}

.handle-icon {
    width: 18px;
    height: 18px;

    &:not(:last-child) {
        margin-right: 5px;
    }
}

.mr-5 {
    margin-right: 5px !important;
}

.orange {
    color: #f9c588;
}

.green {
    color: green;
}

.gray {
    color: #b2b2b2;
}

.orange-border {

    .el-input-group__prepend,
    input,
    textarea {
        border-color: #f9c588;

        &:focus {
            border-color: #f9c588;
        }

        &:hover {
            border-color: #f9c588;
        }

        &:disabled {
            border-color: #f9c588 !important;
        }
    }

    .el-checkbox__inner {
        border-color: #f9c588 !important;
    }
    &.is-checked {
        .el-checkbox__label {
            color: #606266;
        }

        .el-checkbox__inner {
            background-color: #f9c588;
            border-color: #f9c588;
        }
    }

}

.el-button--primary {
    &.orange-border {
        background-color: #f79b31 !important;
        border-color: #f79b31 !important;

        &:hover {
            background-color: #f79b31 !important;
        }

        &:disabled {
            background-color: rgba(#f79b31, .8) !important;
            border-color: rgba(#f79b31, .8) !important;
        }

        &:active {
            background-color: rgba(#f79b31, .8) !important;
            border-color: rgba(#f79b31, .8) !important;

        }
    }

    &.blue-border {
        background-color: #4ea2ff !important;
        border-color: #4ea2ff !important;

        &:hover {
            background-color: #4ea2ff !important;
        }

        &:disabled {
            background-color: rgba(#4ea2ff, .8) !important;
            border-color: rgba(#4ea2ff, .8) !important;
        }

        &:active {
            background-color: rgba(#4ea2ff, .8) !important;
            border-color: rgba(#4ea2ff, .8) !important;
        }
    }

}

.green-border {

    .el-input-group__prepend,
    input,
    textarea {
        border-color: green;

        &:focus {
            border-color: green;
        }

        &:hover {
            border-color: green;
        }

        &:disabled {
            border-color: green !important;
        }
    }

}

.blue-border {

    .el-input-group__prepend,
    input,
    .el-checkbox__inner,
    textarea {
        border-color: #4ea2ff;

        &:focus {
            border-color: #4ea2ff;
        }

        &:hover {
            border-color: #4ea2ff;
        }

        &:disabled {
            border-color: #4ea2ff !important;
        }
    }

}

.error-border {

    .el-input-group__prepend,
    .el-input__inner,
    textarea,
    .el-select,
    .clickable,
    .el-date-editor,
    .el-checkbox__inner {
        border-color: #ff5d5d;
        box-shadow: 0 0 6px #ffc3c3 !important;

        &:focus {
            border-color: #ff5d5d;
            box-shadow: 0 0 6px #ffc3c3 !important;
        }

        &:hover {
            border-color: #ff5d5d;
            box-shadow: 0 0 6px #ffc3c3 !important;
        }
    }

    // 为 el-select 和 el-date-picker 添加错误边框样式
    .el-select .el-input__inner,
    .el-date-editor .el-input__inner .el-checkbox__inner {
        border-color: #ff5d5d;
        box-shadow: 0 0 6px #ffc3c3 !important;
    }

    // 处理 DecimalInput 组件的错误边框样式
    :deep(.el-input-number) {
        .el-input__inner {
            border-color: #ff5d5d;
            box-shadow: 0 0 6px #ffc3c3 !important;
        }
    }

    // 为点击式表单项添加错误边框样式
    .clickable {
        border-color: #ff5d5d;
        box-shadow: 0 0 6px #ffc3c3 !important;
    }
}

.orange-bg {
    background-color: #FFF1F1 !important; // 橙色背景，透明度适中

    input,
    textarea,
    .el-input__inner,
    .el-textarea__inner {
        background-color: #FFF1F1 !important;
    }
}

.modification-modal {
    position: fixed;
    z-index: 9999;
    background-color: rgba(0, 0, 0, 0.7);
    border-radius: 4px;
    padding: 10px;
    color: white;
    max-height: 300px;
    min-width: 250px;
    overflow: hidden;
    pointer-events: auto;
    opacity: 0;
    transform: scale(0.9);
    transition: opacity 0.2s ease, transform 0.2s ease;
}

.modification-modal.show {
    opacity: 1;
    transform: scale(1);
}

.modification-modal .modal-content {
    max-height: 280px;
    overflow-y: auto;
    padding-right: 5px;
}

.modification-modal .modal-content h4 {
    margin: 0 0 10px 0;
    font-size: 14px;
    border-bottom: 1px solid #ccc;
    padding-bottom: 5px;
}

.modification-modal .records-list {
    font-size: 12px;
}

.modification-modal .record-item p {
    margin: 5px 0;
    word-break: break-all;
}

.modification-modal .record-item hr {
    border: 0;
    border-top: 1px solid #555;
    margin: 8px 0;
}

.modification-modal .no-records {
    text-align: center;
    color: #aaa;
    font-style: italic;
}

.clickable {
    cursor: pointer;
    width: auto;
    // margin-left: 10px;
    min-height: 28px;
    line-height: 28px;
    word-break: break-all;
    border-radius: 4px;
    border: 1px solid #4ea2ff;
    display: flex;
    align-items: center;
    padding: 0 15px;
    font-size: 14px;
    font-weight: normal;
    color: #606266;
    flex: 1;
    background-color: #fff;
    &.disabled {
        cursor: not-allowed;
        color: #c0c4cc;
        background-color: #f5f7fa;
    }

    &.error-border {
        border-color: #ff5d5d !important;
        box-shadow: 0 0 6px #ffc3c3 !important;
    }
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
}

.atta-tips {
    color: #ff5d5d;
    font-size: 12px;
    margin-left: 5px;
}

.checkbox-list-container {
    padding: 12px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    transition: all 0.3s;

    &.error-border {
        border-color: #ff5d5d !important;
        box-shadow: 0 0 6px #ffc3c3 !important;
    }

    .checkbox-item {
        margin-right: 16px;
        display: flex;
        align-items: center;

        &:not(:last-child) {
            margin-bottom: 10px;
        }

        // display: inline-block;

        .el-input {
            width: 200px;
            margin-left: 10px;

            &.error-border {
                .el-input__inner {
                    border-color: #ff5d5d !important;
                    box-shadow: 0 0 6px #ffc3c3 !important;
                }
            }
        }
    }


}

.orange-border {
    .checkbox-list-container {
        border-color: #f9c588;

        &:hover {
            border-color: #f79b31;
        }

    }

    .el-checkbox {
        &.is-checked {
            .el-checkbox__label {
                color: #606266;
            }

            .el-checkbox__inner {
                background-color: #f9c588;
                border-color: #f9c588;
            }
        }
    }

    .el-checkbox__input.is-indeterminate .el-checkbox__inner {
        background-color: #f9c588;
        border-color: #f9c588;
    }

    .el-radio {
        &.is-checked {
            .el-radio__label {
                color: #606266;
            }

            .el-radio__inner {
                background-color: #f9c588;
                border-color: #f9c588;
            }
        }

        .el-radio__inner {
            border-color: #f9c588;
        }
    }
}

.orange-bg {
    .checkbox-list-container {
        background-color: #FFF1F1 !important;
        border-color: #f9c588;
    }
}

// checkboxTag样式
.checkbox-tag-wrapper {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    padding: 8px;
}

.checkbox-tag-container {
    border-radius: 4px;

    .checkbox-tag-item {
        display: flex;
        align-items: center;
        gap: 8px;

        .tag-content {
            cursor: pointer;
            position: relative;

            .tag-input {
                width: 100px;
            }

            .tag-display {
                cursor: pointer;
                user-select: none;
            }
        }

        .delete-icon {
            cursor: pointer;
            color: #909399;
            font-size: 12px;
            padding: 2px;
            border-radius: 50%;
            position: absolute;
            top: 6px;
            right: 5px;
            color: red;
            background-color: #f5f5f5;
        }
    }
}

.fqyq-input {
    width: 500px;
    margin-right: 10px;
}

.mb-10 {
    margin-bottom: 10px;
}

.fs-14 {
    font-size: 14px;
}

.mr-10 {
    margin-right: 10px;
}

.checkbox-tree-children {
    margin-left: 30px;
    padding: 16px 0;
    gap: 16px;
    display: grid;
    grid-template-columns: repeat(4, 1fr);
}

.checkbox-tree-item {
    box-sizing: border-box;
    display: flex;
    align-items: center;
}

.checkbox-tree-input-container {
    margin-left: 10px;
    width: 500px;
}

.item-center {
    display: flex;
    align-items: center;
}

.checkbox-tree-group {
    padding: 5px 10px 5px 0;
}

.form-error-border {
    box-shadow: 0 0 6px #ffc3c3;
    padding: 8px;
    border-radius: 4px;
    border: 1px solid #ff5d5d;
}
.no-border {
    border: none;
}
</style>