<template>
    <div class="flex flex1">
        <div class="flex1 flex">
            <el-input v-if="type === 'input'" :maxlength="item.maxlength || 50" :disabled="getDisabled()"
                :class="getFillTypeStyle() + (orangeBg ? ' orange-bg' : '')" @blur="onBlur"
                :placeholder="getPlaceholder()" v-model="inputValue" @input="onInputChange" @change="onInputChange" />
            <el-input v-else-if="type === 'textarea'" :maxlength="item.maxlength || 50" :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="item.precision || 6" :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"
                @visible-change="onSelectBlur" @change="onInputChange">
                <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">
            </el-checkbox>
            <el-date-picker v-else-if="type === 'dateTime'" type="datetime" class="flex1"
                :class="getFillTypeStyle() + (orangeBg ? ' orange-bg' : '')" v-model="inputValue"
                :disabled="getDisabled()" format="yyyy/MM/dd HH:mm:ss" :placeholder="getPlaceholder()"
                @change="(val) => onDateChange(val, 'yyyy/MM/DD HH:mm:ss')">
            </el-date-picker>
            <el-date-picker v-else-if="type === 'datePicker'" class="flex1"
                :class="getFillTypeStyle() + (orangeBg ? ' orange-bg' : '')" v-model="inputValue"
                :disabled="getDisabled()" format="yyyy/MM/dd" :placeholder="getPlaceholder()"
                @change="(val) => onDateChange(val, 'yyyy/MM/DD')">
            </el-date-picker>
            <el-button v-else-if="type === 'button'" :class="getFillTypeStyle() + (orangeBg ? ' orange-bg' : '')"
                :disabled="getDisabled()" type="primary" @click="handleClickButton(item)">
                {{ item.buttonName }}
            </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="regentType.includes(item.type)" @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"
                    :on-success="handleSuccess"
                    :on-change="handleChange"
                    :on-exceed="handleExceed" :file-list="fileList"
                    :auto-upload="false">
                    <el-button  :class="getFillTypeStyle() + (orangeBg ? ' orange-bg' : '')" size="small" type="primary">点击上传</el-button>
                    <div slot="tip" class="el-upload__tip">支持扩展名：.rar .zip .doc .docx .pdf .jpg，文件大小不超过2MB</div>
                </el-upload>
            </template>

        </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' ? '回复意见' : '复核意见'"
            :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 { deepClone } from "@/utils/index";
import { getuuid } from "@/utils/index.js";
import { getToken } from "@/utils/auth"
export default {
    inject: ['templateData', 'templateFillType', "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],
            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() {
        return {
            inputValue: this.value,
            oldValue: this.value, // 记录上一次的值
            showModal: false, // 控制模态框显示
            modificationRecords: [], // 存储修改记录
            modalTimer: null, // 用于延迟隐藏模态框
            isHoveringModal: false, // 是否悬停在模态框上
            isHoveringMain: false, // 是否悬停在主元素上（这个实际上不需要，因为我们有事件处理）
            currentRecordType: '', // 当前悬停的记录类型（replyRecord 或 modifyRecord）
            replyContent: '', // 回复内容
            visible: false,//是否显示弹窗
            checkboxValue: this.getChecked(),//是否选中
            uuid: getuuid(), // 唯一标识符，用于EventBus事件匹配
            regentType: ['sj', 'gsp', 'mix', 'xj', 'xb', 'gyzj', 'mjy', 'yq'],  //试剂/仪器/供试品等类型
            selectRegentInfo: {},//选择的试剂/仪器/供试品等信息
            fileList: [],//上传的文件列表
            uploadFileUrl: process.env.VUE_APP_BASE_API + "/file/upload",
             headers: {
                Authorization: "Bearer " + getToken(),
            },
        }
    },
    watch: {
        value(newVal) {
            this.inputValue = 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: {
        onInstrumentSubmit(data){
            if(data.uuid !== this.uuid) return;
            this.selectRegentInfo = data;
            console.log(data,"yq")
        },
           // 删除前确认
        beforeRemove(file) {
            return this.$confirm(`确定移除 ${file.name} ？`)
        },
        // 文件状态改变时的钩子，添加文件、上传成功、上传失败时都会被调用
        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
                }
                
                // 验证通过，手动提交上传
                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;
        },
        handleRemove(file, fileList) {
            // 从列表中移除文件
            const index = fileList.indexOf(file);
            if (index > -1) {
                fileList.splice(index, 1);
            }
            
            // 更新inputValue为剩余文件路径列表
            this.inputValue = JSON.stringify(this.getFileList(fileList));
            this.$emit("change",this.inputValue)
            
            // 触发保存记录
            this.onCommonHandleSaveRecord();
            
            this.$message.success(`文件 ${file.name} 已移除`);
        },
        handlePreview(file) {
            if (file.url) {
                window.open(process.env.VUE_APP_FILE_DOMAIN + file.url, '_blank');
            }
        },
        handleExceed(files, fileList) {
            this.$message.warning(`当前限制选择 10 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
        },
        //试剂弹窗提交
        onMixReagentSubmit(data) {
            if (data.uuid !== this.uuid) return;
            this.inputValue = data.selectedId;
            this.selectRegentInfo = data;
            this.onCommonHandleSaveRecord(this.inputValue);
            // this.inputValue = this.item.label;
        },
        //统一处理试剂/供试品等弹窗
        onCommonHandleRegent(item, type) {
            if (this.templateFillType !== 'actFill') {
                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",//细胞
                }
                params = {
                    ...params,
                    type: sjType[type]
                }
            }
            EventBus.$emit(eventName, params)
            // this.$emit('regent', item,type);
        },
        // 点击按钮
        handleClickButton(item) {
            this.$emit('clickButton', item);
        },
        onDateChange(val, format) {
            this.inputValue = moment(val).format(format);
            console.log(this.inputValue, "inputValue")
            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) {
                this.resetRecord();
            }
        },
        // 处理电子签名确认回调事件
        handleEditSignCallback(data) {
            if (data.uuid === this.uuid) {
                this.onEditSignSave(data.data);
            }
        },
        onEditSignSave(data) {
            this.handleUpdateRecord(data)
        },
        getChecked() {
            return !!this.getFieldCheckObj()[this.fieldKey]?.checked;
        },
        getFillTypeStyle(type) {
            const { fillType } = this.item;
            const typeObj = {
                actFill: "orange-border",//实际填写的边框颜色
                green: "green-border",
                preFill: "blue-border",//预填写的边框颜色
            }
            // 如果有错误状态，返回红色边框样式，覆盖原有的边框颜色
            if (this.error) {
                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' ? "回复意见" : "复核意见",
                time: moment().format("YYYY-MM-DD HH:mm:ss"),
            }
            if (this.templateFillType == 'actFill') {
                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' ? "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) {
            const value = val !== undefined ? val : this.inputValue;
            this.$emit('input', value);
            this.$emit('change', value);

            // 根据输入值判断是否显示错误状态
            const isEmpty = this.isValueEmpty(value);
            if (this.error && !isEmpty) {
                this.$emit('update:error', false);
            } else if (!this.error && isEmpty) {
                this.$emit('update:error', true);
            }
        },
        // 统一处理失去焦点事件
        onBlur(e) {
            this.onCommonHandleSaveRecord(e.target.value);
        },
        // 点击question图标
        onClickQuestion() {
            const { templateFillType } = this;
            if (templateFillType == 'actFill' || templateFillType == 'qc') {
                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') {//如果qc没有复核，填报点击的时候需要回填上次填报的信息
                        content = o.reply;
                    }
                }
                this.replyContent = content;
                this.visible = true;
            }
        },
        async onCommonHandleSaveRecord(val) {
            const isEmpty = this.isValueEmpty(this.inputValue);
            if (this.error && !isEmpty) {
                this.$emit('update:error', false);
            } else if (!this.error && isEmpty) {
                this.$emit('update:error', true);
            }
            if (!this.isFieldsRecord) {//是否需要记录修改记录
                this.$emit("blur", this.inputValue);
                this.$emit('input', this.inputValue);
                this.$emit("change", this.inputValue);
                return;
            }
            // 值发生了变化，需要弹出密码输入框
            const isSame = this.isEqual(this.oldValue, this.inputValue);
            if (isSame) {
                return;
            }
            if (!this.isValueEmpty(this.oldValue) && !isSame && this.templateFillType === "actFill") {
                // 通过EventBus触发电子签名弹窗
                EventBus.$emit('showEditSignDialog', { uuid: this.uuid });
            } else {//如果是第一次填写，不需要密码验证
                this.handleUpdateRecord()
            }
        },

        //如果用户取消，那么回退到上一次的值
        resetRecord() {
            // 用户点击取消，还原数据
            this.inputValue = this.oldValue;
            this.$emit('input', this.inputValue); // 触发 v-model 更新
            // this.$emit("blur", this.oldValue);
            this.$emit("change", this.oldValue, "cancel");
            if (this.item.type === "clickable") {
                this.$emit("resetRecord");
            }
        },

        //处理更新记录
        handleUpdateRecord(data) {
            const baseInfo = this.getCommonRecordInfo();
            if (!this.oldValue && !this.inputValue) return;
            const record = {
                ...baseInfo,
                oldValue: this.oldValue,
                value: this.inputValue,
                title: this.oldValue ? "修改" : "提交",
                time: moment().format("YYYY-MM-DD HH:mm:ss"),
            }
            if (data) {
                record.reason = data.remark
            }

            const params = {
                type: "fieldChanged",
                newRecord: [record],
                resourceList: this.getZdxgjl(),
            }
            //用户输入密码并点击确定，保存修改
            this.oldValue = this.inputValue; // 更新旧值
            this.$emit("blur", this.inputValue);
            this.$emit('input', this.inputValue);
            this.$emit("change", this.inputValue, data ? "save" : "");
            if (this.item.type === "clickable") {//clickable的丢给父级去处理
                return;
            }

            if (this.templateFillType === "actFill") {//只有实际填报的时候才记录修改记录
                this.updateZdxgjl(record);
            }
            this.$nextTick(()=>{
                EventBus.$emit('onModifyRecord', params,)
                if (this.regentType.includes(this.item.type)) {
                    this.$emit("onRegentSubmit", this.selectRegentInfo);
                }
            })
        },

        //判断两个值是否相等
        isEqual(oldValue, nowValue) {
            if (oldValue === null || nowValue === null) {
                return oldValue === nowValue;
            }
            if (typeof oldValue === 'object' && typeof nowValue === 'object') {
                return JSON.stringify(oldValue) === JSON.stringify(nowValue);
            }
            return oldValue === nowValue;
        },

        //获取公共记录信息
        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;
        },

        // 判断值是否为空
        isValueEmpty(value) {
            if (value === null || value === undefined || value === '') {
                return true;
            }
            if (typeof value === 'string' && value.trim() === '') {
                return true;
            }
            if (Array.isArray(value) && value.length === 0) {
                return true;
            }
            return false;
        },
        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"
        },
        //判断是否禁用
        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 {
                    return true
                }
            }
        },
        getPlaceholder() {
            const { placeholder, label } = this.item;
            const { type } = this;
            if (this.getDisabled()) {
                return ""
            }
            if (this.regentType.includes(type) || type === "clickable") {
                return this.$t("template.common.pleaseSelect")
            }
            let prex = "template.common.pleaseFillIn"
            if (type === "select" || type === "dateTime") {
                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;
    }

}

.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,
    input,
    textarea,
    .el-select,
    .clickable,
    .el-date-editor {
        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;

    &.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;
}
</style>