<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="onCommonHandleSaveRecord"
                :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="onCommonHandleSaveRecord"
                :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" :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()" @change="onInputChange">
                <el-option v-for="op in item.options" :key="op.value" :label="op.label" :value="op.value">
                </el-option>
            </el-select>
            <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"
                value-format="yyyy/MM/DD HH:mm:ss"
                :placeholder="getPlaceholder()" @change="onCommonHandleSaveRecord">
            </el-date-picker>
            <div class="clickable" :class="getFillTypeStyle() + (getDisabled()?' disabled':'') + (orangeBg ? ' orange-bg' : '')" v-else-if = "item.type ==='clickable'" @click="handleClickable(item,$event)">
                <span v-if="value">{{ value }}</span>
                <span v-else class="default-placeholder-text">{{getPlaceholder()}}</span>
            </div>
        </div>
        <!-- qc才能操作 -->
        <div class="handle-row" v-if="isShowHandle()">
            <el-checkbox class="ml-5"></el-checkbox>
            <div @mouseenter="onMouseEnter" @mouseleave="onMouseLeave">
                <Question   class="handle-icon" :class="getQuestionColor()" />
            </div>
            <img v-if="getIsShowCopyIcon()" @click="onCopy" src="@/assets/images/copy-icon.svg" class="handle-icon"
                alt="" />
            <img 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">
                <h4>修改记录</h4>
                <div class="records-list">
                    <div 
                        v-for="(record, index) in modificationRecords" 
                        :key="index" 
                        class="record-item"
                    >
                        <p><strong>时间:</strong> {{ record.timestamp }}</p>
                        <p><strong>旧值:</strong> {{ record.oldValue }}</p>
                        <p><strong>新值:</strong> {{ record.newValue }}</p>
                        <hr v-if="index < modificationRecords.length - 1">
                    </div>
                    <div v-if="!modificationRecords || modificationRecords.length === 0" class="no-records">
                        暂无修改记录
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import Question from "./icons/Question.vue";
import DecimalInput from "./DecimalInput.vue";
export default {
    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],
            default: ''
        },
        // 错误状态
        error: {
            type: Boolean,
            default: false
        },
        // 橙色背景状态
        orangeBg: {
            type: Boolean,
            default: false
        },
    },
    data() {
        return {
            inputValue: this.value,
            oldValue: this.value, // 记录上一次的值
            showModal: false, // 控制模态框显示
            modificationRecords: [], // 存储修改记录
            modalTimer: null, // 用于延迟隐藏模态框
            isHoveringModal: false, // 是否悬停在模态框上
            isHoveringMain: false, // 是否悬停在主元素上（这个实际上不需要，因为我们有事件处理）
            db: null, // IndexedDB 实例
        }
    },
    watch: {
        value(newVal) {
            this.inputValue = newVal;
            console.log(newVal,"newVal")
        }
    },
    filters: {
        

    },
    methods: {
        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] || ""
        },
        //获取question图标颜色
        getQuestionColor() {
            //gray 灰色 green 绿色 orange 橙色
            return "green"
        },
        // 统一处理输入变化
        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);
            }
        },
        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);
            }
            const {templateStatus} = this.$store.state.template;
            // 检查值是否发生变化
            if (this.inputValue !== this.oldValue && templateStatus === "actFill") {
                // 值发生了变化，需要弹出密码输入框
                try {
                    // const passwordResult = await this.$prompt('请输入密码以确认修改', '密码验证', {
                    //     confirmButtonText: '确定',
                    //     cancelButtonText: '取消',
                    //     inputType: 'password',
                    //     inputPattern: /.+/,
                    //     inputErrorMessage: '请输入密码',
                    //     zIndex: 10000,
                    // });
                    // 用户输入密码并点击确定，保存修改
                    this.oldValue = this.inputValue; // 更新旧值
                    this.$emit("blur", val);
                    this.$emit('input', this.inputValue);
                    this.$emit("change", val);
                    // 调用后端接口记录修改记录
                    await this.saveModificationRecord();
                } catch {
                    // 用户点击取消，还原数据
                    this.inputValue = this.oldValue;
                    this.$emit('input', this.inputValue); // 触发 v-model 更新
                    this.$emit("blur", this.oldValue);
                    this.$emit("change", this.oldValue);
                }
            } else {
                // 值没有变化，正常触发 blur和change 事件
                this.$emit("blur", val)
                // this.$emit('input', val);
                this.$emit("change", val)
            }
        },
        // 通用的值变化处理方法
        async handleValueChange(val, componentType = '') {
            const oldValue = this.oldValue; // 保存旧值
            this.$emit('input', val);
            this.$emit('change', val);
            
            // 根据输入值判断是否显示错误状态
            const isEmpty = this.isValueEmpty(val);
            if (this.error && !isEmpty) {
                this.$emit('update:error', false);
            } else if (!this.error && isEmpty) {
                this.$emit('update:error', true);
            }
            
            // 值发生改变，记录修改
            const { templateStatus } = this.$store.state.template;
            if (val !== oldValue && templateStatus === "actFill") {
                // 值发生了变化，记录修改
                try {
                    this.oldValue = val; // 更新旧值
                    
                    // 调用后端接口记录修改记录
                    await this.saveModificationRecord();
                } catch (error) {
                    const componentName = componentType || '组件';
                    console.error(`记录${componentName}修改失败:`, error);
                }
            }
        },
        
        // 判断值是否为空
        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(item.fillType !== 'actFill'){
                return
            }
            this.$emit("clickable",item)
        },
        //判断是否显示复制按钮
        getIsShowCopyIcon() {
            const { copyFrom } = this.item;
            const { templateStatus } = this.$store.state.template;
            return copyFrom && templateStatus === "actFill";
        },
        //判断是否显示操作按钮
        isShowHandle() {
            const { fillType } = this.item;
            const { templateStatus } = this.$store.state.template;
            //只有当模板状态是qc和实际填报时，才显示操作按钮
            return (templateStatus === "qc" || templateStatus === "actFill") && fillType === "actFill";
        },
        //判断是否禁用
        getDisabled() {
            const { item } = this;
            const { fillType } = item;
            if (item.hasOwnProperty("disabled")) {
                return item.disabled
            } else {
                const { templateStatus } = this.$store.state.template;
                if (fillType === "actFill") {//当模板状态是实际填写时，只有当fillType是actFill时才能填写
                    return templateStatus !== "actFill"
                } else if (fillType === "preFill") {//当模板状态是预填写时，只有当fillType是preFill才能填写
                    return templateStatus !== "preFill"
                } else {
                    return true
                }
            }
        },
        getPlaceholder() {
            const { placeholder,label } = this.item;
            const {type} = this;
            if(this.getDisabled()){
                return ""
            }
            if(type === "clickable"){
               return "请选择"
            }
            let prex = "请输入";
            if(type === "select"  || type === "dateTime"){
                prex = "请选择"
            }
            return placeholder ? placeholder : (prex + label)
            
        },
        onCopy() {
            this.$emit("copy")
        },
        
        // 记录数据修改

        
        // 鼠标进入主容器

        
        // 初始化 IndexedDB
        initDB() {
            return new Promise((resolve, reject) => {
                const request = indexedDB.open('ModificationRecordsDB', 1);
                
                request.onerror = (event) => {
                    console.error('IndexedDB error:', event.target.error);
                    reject(event.target.error);
                };
                
                request.onsuccess = (event) => {
                    this.db = event.target.result;
                    resolve(this.db);
                };
                
                request.onupgradeneeded = (event) => {
                    const db = event.target.result;
                    if (!db.objectStoreNames.contains('modificationRecords')) {
                        const objectStore = db.createObjectStore('modificationRecords', { keyPath: 'id' });
                        objectStore.createIndex('fieldId', 'fieldId', { unique: false });
                        objectStore.createIndex('timestamp', 'timestamp', { unique: false });
                    }
                };
            });
        },
        
        // 生成唯一字段ID (id + key值)
        getFieldId() {
            const templateId = 'template_123'; // 这里是写死的id
            const fieldKey = this.item.key || this.item.prop || this.item.label || 'default_key';
            
            // 考虑到CustomTable组件可能有重复的key值，我们需要额外标识
            // 如果在表格中，可能需要添加行索引等信息
            const tableRowIndex = this.item.rowIndex !== undefined ? `_${this.item.rowIndex}` : '';
            
            return `${templateId}_${fieldKey}${tableRowIndex}`;
        },
        
        // 获取 IndexedDB 对象存储实例
        async getObjectStore(storeName = 'modificationRecords', mode = 'readonly') {
            if (!this.db) {
                await this.initDB();
            }
            const transaction = this.db.transaction([storeName], mode);
            return transaction.objectStore(storeName);
        },
        
        // 保存单条修改记录到 IndexedDB
        async saveRecordToDB(record) {
            const objectStore = await this.getObjectStore('modificationRecords', 'readwrite');
            
            const fieldId = this.getFieldId();
            const newRecord = {
                id: `${fieldId}_${Date.now()}`, // 使用时间戳确保唯一性
                fieldId: fieldId,
                oldValue: record.oldValue,
                newValue: record.newValue,
                timestamp: new Date().toLocaleString(),
            };
            
            return new Promise((resolve, reject) => {
                const request = objectStore.add(newRecord);
                
                request.onsuccess = () => {
                    resolve(request.result);
                };
                
                request.onerror = (event) => {
                    reject(event.target.error);
                };
            });
        },
        
        // 从 IndexedDB 获取修改记录
        async getRecordsFromDB() {
            if (!this.db) {
                await this.initDB();
            }
            
            const transaction = this.db.transaction(['modificationRecords'], 'readonly');
            const objectStore = transaction.objectStore('modificationRecords');
            const fieldIdIndex = objectStore.index('fieldId');
            
            const fieldId = this.getFieldId();
            
            return new Promise((resolve, reject) => {
                const request = fieldIdIndex.getAll(IDBKeyRange.only(fieldId));
                
                request.onsuccess = (event) => {
                    // 按时间戳排序，最新的在前
                    const records = event.target.result.sort((a, b) => {
                        return new Date(b.timestamp) - new Date(a.timestamp);
                    });
                    resolve(records);
                };
                
                request.onerror = (event) => {
                    reject(event.target.error);
                };
            });
        },
        
        // 同步后端修改记录到 IndexedDB
        async syncRecordsToDB(backendRecords) {
            // 清空当前字段的记录
            await this.clearFieldRecords();
            
            // 批量添加后端记录到 IndexedDB
            const objectStore = await this.getObjectStore('modificationRecords', 'readwrite');
            
            const fieldId = this.getFieldId();
            
            return new Promise((resolve, reject) => {
                let completed = 0;
                const total = backendRecords.length;
                
                if (total === 0) {
                    resolve();
                    return;
                }
                
                backendRecords.forEach((record) => {
                    // 标准化记录格式以匹配 IndexedDB 存储格式
                    const newRecord = {
                        id: `${fieldId}_${Date.parse(record.timestamp) || Date.now()}`, // 使用时间戳或当前时间戳作为 ID
                        fieldId: fieldId,
                        oldValue: record.oldValue,
                        newValue: record.newValue,
                        timestamp: record.timestamp || new Date().toLocaleString(),
                        password: record.password ? '***' : '' // 不直接存储密码
                    };
                    
                    const request = objectStore.add(newRecord);
                    
                    request.onsuccess = () => {
                        completed++;
                        if (completed === total) {
                            resolve();
                        }
                    };
                    
                    request.onerror = (event) => {
                        console.error('同步单条记录失败:', event.target.error);
                        completed++;
                        if (completed === total) {
                            resolve(); // 即使有错误也继续，避免单条记录失败影响整体同步
                        }
                    };
                });
            });
        },
        
        // 清空当前字段的记录
        async clearFieldRecords() {
            if (!this.db) {
                await this.initDB();
            }
            
            const transaction = this.db.transaction(['modificationRecords'], 'readwrite');
            const objectStore = transaction.objectStore('modificationRecords');
            const fieldIdIndex = objectStore.index('fieldId');
            
            const fieldId = this.getFieldId();
            
            return new Promise((resolve, reject) => {
                const request = fieldIdIndex.openCursor(IDBKeyRange.only(fieldId));
                
                request.onsuccess = (event) => {
                    const cursor = event.target.result;
                    if (cursor) {
                        cursor.delete(); // 删除匹配的记录
                        cursor.continue();
                    } else {
                        // 所有匹配的记录已删除
                        resolve();
                    }
                };
                
                request.onerror = (event) => {
                    reject(event.target.error);
                };
            });
        },
        
        // 鼠标进入主容器
        async onMouseEnter(event) {
            clearTimeout(this.modalTimer);
            
            // 从 IndexedDB 加载修改记录
            try {
                const records = await this.getRecordsFromDB();
                this.modificationRecords = records;
            } catch (error) {
                console.error('获取修改记录失败:', error);
                this.modificationRecords = [];
            }
            
            // 先计算模态框位置，避免闪烁
            this.showModal = true;
            this.$nextTick(() => {
                if (this.$refs.modalRef) {
                    const elementRect = event.target.getBoundingClientRect();
                    const modalEl = this.$refs.modalRef;
                    
                    // 设置模态框位置在元素右侧
                    modalEl.style.left = elementRect.right + 5 + 'px'; // 5px间距
                    modalEl.style.top = elementRect.top + 'px';
                }
            });
        },
        
        // 鼠标离开主容器
        onMouseLeave() {
            // 延迟隐藏模态框，让用户有机会移动到模态框上
            this.modalTimer = setTimeout(() => {
                if (!this.isHoveringModal) {
                    this.showModal = false;
                }
            }, 300);
        },
        
        // 鼠标进入模态框
        onModalEnter() {
            this.isHoveringModal = true;
            clearTimeout(this.modalTimer);
        },
        
        // 鼠标离开模态框
        onModalLeave() {
            this.isHoveringModal = false;
            this.modalTimer = setTimeout(() => {
                this.showModal = false;
            }, 300);
        },
        
        // 记录数据修改
        async saveModificationRecord() {
            // 添加修改记录到本地存储
            const record = {
                oldValue: this.oldValue,
                newValue: this.inputValue,
                timestamp: new Date().toLocaleString(), // 格式化时间
            };
            
            // 保存到 IndexedDB
            try {
                await this.saveRecordToDB(record);
                // 保存成功后更新本地记录（可选，取决于是否需要立即显示）
                // const records = await this.getRecordsFromDB();
                // this.modificationRecords = records;
            } catch (error) {
                console.error('保存修改记录失败:', error);
            }
            
            // 发送事件告知父组件值已修改
            this.$emit('modification-recorded', {
                field: this.item.label || '',
                oldValue: this.oldValue,
                newValue: this.inputValue,
            });
        }
    },
}
</script>

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

.flex1 {
    flex: 1;
}

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

.w-100 {
    width: 100%;
}

.handle-icon {
    width: 18px;
    height: 18px;
    margin-left: 5px;
}

.ml-5 {
    margin-left: 5px;
}

.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;
        }
    }

}

.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,
    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: #f56c6c;

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

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

    // 为 el-select 和 el-date-picker 添加错误边框样式
    .el-select .el-input__inner,
    .el-date-editor .el-input__inner {
        border-color: #f56c6c;
    }

    // 处理 DecimalInput 组件的错误边框样式
    :deep(.el-input-number) {
        .el-input__inner {
            border-color: #f56c6c;
        }
    }
    
    // 为点击式表单项添加错误边框样式
    .clickable {
        border-color: #f56c6c;
    }
}

.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-width: 100px;
    height: 28px;
    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: #f56c6c !important;
    }
}
</style>