<template>
    <el-dialog :close-on-click-modal="false" :close-on-press-escape="false" title="分装（分装后的编号可用于下一步关联选择）" append-to-body
        :visible.sync="visible" @close="close" width="1100px">
        <div class="dialog-content">
            <div class="header-container">
                <div class="header-item">
                    <div class="header-title">母液编号</div>
                    <HandleFormItem :fieldKey="formData.mybh + '_mybh'" :isFieldsRecord="false" :item="inputItem" :error="formErrors.mybh"
                        v-model="formData.mybh" />
                </div>
                <div class="header-item">
                    <div class="header-title">分装数量</div>
                    <HandleFormItem :isFieldsRecord="false"  :fieldKey="formData.mybh + '_fzsl'" @blur="onBlurFzsl" :item="integerInputNumberItem"
                        type="inputNumber" :error="formErrors.fzsl" v-model="formData.fzsl" />
                </div>
            </div>
            <div class="content-container">
                <div class="content-item">
                    <span>分装编号</span>
                    <span class="ml-20">单位：</span>
                    <div class="unit-select">
                        <HandleFormItem :fieldKey="formData.mybh + '_dw'" :isFieldsRecord="false" :item="unitItem" type="select" :error="formErrors.dw"
                            @blur="(e) => onCommonBlur(e, 'dw')" v-model="formData.dw" />
                    </div>
                    <span class="ml-20">每份包装量：</span>
                    <div class="unit-select">
                        <HandleFormItem :fieldKey="formData.mybh + '_mfbzl'" type="inputNumber" :error="formErrors.mfbzl" :isFieldsRecord="false"
                            :item="inputNumberItem" v-model="formData.mfbzl" />
                    </div>
                    <el-button type="primary" plain @click="onAverage">平均分配</el-button>
                    <el-button type="primary" plain @click="onReset">重置</el-button>
                </div>
                <div class="header-container header2">
                    <div v-for="(item, index) in fzList" class="list-item" :key="index">
                        <div class="list-label">{{ formData.mybh }}-set{{ item.subCode }}</div>
                        <HandleFormItem :fieldKey="formData.mybh + '_num_' + item.subCode" :isFieldsRecord="false" :item="inputNumberItem" :error="fzListErrors[index]"
                            type="inputNumber" @blur="onBlurFzNum(index)" v-model="item.num" />
                        <el-button type="primary" class="ml-5" plain @click="onPrint(item)">打印</el-button>
                    </div>
                </div>
            </div>
        </div>
        <template slot="footer" class="dialog-footer">
            <el-button @click="close">{{ $t('form.cancel') }}</el-button>
            <el-button type="primary" @click="onSubmit">{{ $t('form.saveConfirm') }}</el-button>
        </template>
    </el-dialog>
</template>

<script>
import HandleFormItem from '@/components/Template/HandleFormItem.vue';
import { compareVolume } from '@/utils/volumeTools.js';
import { EventBus } from '@/utils/eventBus';
import { getLatestSn } from '@/api/template';
import { isValueEmpty } from "@/utils/index";
import moment from 'moment';
import { getuuid } from "@/utils/index.js";
export default {
    inject: ['updateZdxgjl',"getZdxgjl"],
    dicts: [
        'business_tjdw',
    ],
    components: {
        HandleFormItem,
    },
    data() {
        return {
            visible: false,
            inputItem: {
                type: "input",
                fillType: "actFill",
                disabled: true,
            },
            integerInputNumberItem: {
                type: "inputNumber",
                fillType: "actFill",
                precision: 0,
                label: "分装数量",
                maxlength: 3
            },
            inputNumberItem: {
                type: "inputNumber",
                fillType: "actFill",
            },
            formData: {
                mybh: "",//母液编号
                fzsl: "",//分装数量
                dw: "",//单位
                mfbzl: "",//每份包装量
            },
            fzList: [],//分装列表
            // 错误状态字段
            formErrors: {
                mybh: false,
                fzsl: false,
                dw: false,
            },
            fzListErrors: [], // 分装列表错误状态
            uuid: "",//事件id
            originalData: {},//原始数据
            uuid:getuuid(),//事件id
        }
    },
    computed: {
        unitItem() {
            return {
                type: "select",
                fillType: "actFill",
                options: this.dict.type.business_tjdw
            }
        }
    },
    mounted() {
        EventBus.$on('onEditSignCallback', this.handleEditSignCallback);
		EventBus.$on('onFormEditSignCancel', this.handleEditSignCancel);
    },
    unmounted() {
		EventBus.$off('onEditSignCallback', this.handleEditSignCallback);
		EventBus.$off('onFormEditSignCancel', this.handleEditSignCancel);
	},
    methods: {
        handleEditSignCancel(data) {
			
		},
		handleEditSignCallback(data) {
			if (data.uuid === this.uuid) {
				this.updateRecords();
			}
		},
        close() {
            this.visible = false;
            this.fzList = [];
            this.formData = {};
            this.resetErrors();
        },
        show(data) {
            const cloneData = JSON.parse(JSON.stringify(data));
            console.log(cloneData, "cloneData")
            if (data && data.uuid) {//为了标识eventBus的事件id
                this.uuid = data.uuid
            }
            this.originalData = {
                fzList: [],
                mybh: cloneData.mybh,
                fzsl: cloneData.fzsl,
                dw: cloneData.dw,
                mfbzl: cloneData.mfbzl,
            }
            if (data.fzList) {
                this.fzList = JSON.parse(JSON.stringify(cloneData.fzList));
                this.originalData.fzList = JSON.parse(JSON.stringify(cloneData.fzList));
                // 初始化分装列表错误状态
                this.fzListErrors = new Array(this.fzList.length).fill(false);
                delete cloneData.fzList;
            }

            this.formData = cloneData;
            // 重置错误状态
            this.resetErrors();
            this.visible = true;
        },
        onSubmit() {
            // 验证表单数据
            if (!this.validateFormData()) {
                this.$message.error('表单内容未填完,请填写后再提交')
                return;
            } else {
                const errMsg = "分装后小份容量之和大于母液容量，是否确认分装？"
                const { maxVolume, maxVolumeUnit, dw } = this.formData;

                const totalVolume = this.fzList.reduce((acc, cur) => acc + Number(cur.num), 0);
                const compareResult = compareVolume(totalVolume, dw, maxVolume, maxVolumeUnit);
                console.log(compareResult, totalVolume, dw, maxVolume, maxVolumeUnit, "比较结果");
                if (compareResult > 0 || !maxVolume) {//没有填写实际溶液体积的也需要提示错误信息
                    this.$modal.confirm(errMsg, '提示', {
                        confirmButtonText: this.$t('form.saveConfirm'),
                        cancelButtonText: this.$t('form.cancel'),
                        type: 'warning'
                    }).then(() => {
                        this.submitEmit();
                    }).catch(() => {
                        // 取消操作，不执行任何操作
                    });
                    return;
                }
                this.submitEmit();

            }


        },
        submitEmit() {
            const { originalData } = this;
            const { mybh, fzsl, dw, mfbzl } = this.formData;
            const nowData = { fzList: this.fzList, mybh, fzsl, dw, mfbzl };

            if (!originalData.fzList.length) {
                this.updateRecords();
            } else if (JSON.stringify(nowData) !== JSON.stringify(originalData)) {
                EventBus.$emit('showEditSignDialog', { uuid: this.uuid });
                return;
            } else {
                this.updateRecords();
            }
        },
        handleSubmit() {
            EventBus.$emit('dialogSubPackageSubmit', { ...this.formData, fzList: this.fzList, uuid: this.uuid });
            setTimeout(() => {
                this.close();
            }, 500);
        },
        getCommonInfo(type){
            const { nickName, name } = this.$store.getters;
            const o ={
                mybh:"母液编号",
                fzsl:"分装数量",
                dw:"单位",
                mfbzl:"每份包装量",
                num:"分装编号"
            }
            return{
                userNameCn: nickName,
                userNameEn: name,
                time: moment().format("YYYY-MM-DD HH:mm:ss"),
                fieldCn: o[type],
                fieldEn: o[type],
            }
        },
        updateRecords() {
            const { originalData } = this;
            const records = [];
            const { mybh, fzsl, dw, mfbzl } = this.formData;
            const nowData = { fzList: this.fzList, mybh, fzsl, dw, mfbzl };
            // 定义要比较的字段
            const fieldsToCompare = ['mybh', 'fzsl', 'dw', 'mfbzl'];

            // 比较基础字段
            fieldsToCompare.forEach(field => {
                if (originalData[field] !== nowData[field]) {
                    const record = {
                        key: mybh + '_' + field,
                        oldValue: originalData[field],
                        value: nowData[field],
                        title: originalData[field] ? "修改" : "提交",
                        ...this.getCommonInfo(field),
                    }
                    records.push(record);
                    this.updateZdxgjl(record);
                }
            });
            // 比较分装列表
            this.compareFzList(originalData.fzList, nowData.fzList, records);
            
            console.log(records, "records")
          
            this.handleSubmit();
            if (records.length == 0) {
                return;
            }
            const params = {
                type: "fieldChanged",
                newRecord: records,
                resourceList: this.getZdxgjl(),
                source: "customTable",
            }
            EventBus.$emit('onModifyRecord', params);
        },

        // 比较分装列表的辅助方法
        compareFzList(originalFzList, nowFzList, records) {
            console.log(originalFzList, nowFzList, records, "compareFzList")
            const { mybh } = this.formData;
            if(!originalFzList.length){
                nowFzList.forEach(item => {
                    const record = {
                        key: mybh + '_num_' + item.subCode,
                        oldValue: '',
                        value: item.num,
                        title: item.num ? "修改" : "提交",
                        ...this.getCommonInfo('num'),
                    };
                    records.push(record);
                    this.updateZdxgjl(record);
                })
                return;
            }
            if (originalFzList.length === nowFzList.length) {
                for (let i = 0; i < originalFzList.length; i++) {
                    if (originalFzList[i].num !== nowFzList[i].num) {
                        const record = {
                            key: mybh + '_num_' + originalFzList[i].subCode,
                            oldValue: originalFzList[i].num,
                            value: nowFzList[i].num,
                            title: originalFzList[i].num ? "修改" : "提交",
                            ...this.getCommonInfo('num'),
                        };
                        records.push(record);
                        this.updateZdxgjl(record);
                    }
                }
            }else if(originalFzList.length>nowFzList.length){
                for (let i = 0; i < nowFzList.length; i++) {
                    if (originalFzList[i].num !== nowFzList[i].num) {
                        const record = {
                            key: mybh + '_num_' + nowFzList[i].subCode,
                            oldValue: originalFzList[i].num,
                            value: nowFzList[i].num,
                            title: originalFzList[i].num ? "修改" : "提交",
                            ...this.getCommonInfo('num'),
                        };
                        records.push(record);   
                        this.updateZdxgjl(record);
                    }
                }
            }else{
                for (let i = 0; i < originalFzList.length; i++) {
                    if (originalFzList[i].num !== nowFzList[i].num) {
                        const record = {    
                            key: mybh + '_num_'  + nowFzList[i].subCode,
                            oldValue: originalFzList[i].num,
                            value: nowFzList[i].num,
                            title: originalFzList[i].num ? "修改" : "提交",
                            ...this.getCommonInfo('num'),
                        };
                        records.push(record);
                        this.updateZdxgjl(record);
                    }
                }
            }

        },
        validateFormData() {
            let isValid = true;
            const { mybh, fzsl, dw, mfbzl } = this.formData;
            // 验证母液编号
            if (isValueEmpty(mybh)) {
                this.formErrors.mybh = true;
                isValid = false;
            }
            // 验证分装数量
            if (isValueEmpty(fzsl)) {
                this.formErrors.fzsl = true;
                isValid = false;
            }

            // 验证单位
            if (isValueEmpty(dw)) {
                this.formErrors.dw = true;
                isValid = false;
            }
            // 验证单位
            if (isValueEmpty(mfbzl)) {
                this.formErrors.mfbzl = true;
                isValid = false;
            }
            // 验证分装列表中的数值
            if (this.fzList && this.fzList.length > 0) {
                for (let i = 0; i < this.fzList.length; i++) {
                    if (isValueEmpty(this.fzList[i].num)) {
                        // 确保fzListErrors数组有足够的元素
                        if (this.fzListErrors.length <= i) {
                            this.$set(this.fzListErrors, i, true);
                        } else {
                            this.fzListErrors[i] = true;
                        }
                        isValid = false;
                    }
                }
            }
            return isValid;
        },
        resetErrors() {
            // 重置表单错误状态
            Object.keys(this.formErrors).forEach(key => {
                this.formErrors[key] = false;
            });

            // 重置分装列表错误状态
            this.fzListErrors.forEach((_, index) => {
                this.$set(this.fzListErrors, index, false);
            });
        },
        // 分装数量失去焦点时，根据数量生成分装列表
        async onBlurFzsl(e) {
            console.log(e, "失去焦点时的数量")
            // 清除当前字段的错误状态
            if (e) {
                this.formErrors.fzsl = false;
            }
            // 清空现有列表
            this.fzList = [];
            this.fzListErrors = [];
            const result = await getLatestSn({
                pre: this.formData.mybh,
                count: e,
                type: 2,
            })
            if (result.code === 200) {
                const codes = result.data;
                // 根据输入的数量生成新列表
                for (let i = 0; i < e; i++) {
                    this.fzList.push({
                        num: "",
                        subCode: codes[i],
                        preCode: `-set${codes[i]}`
                    });
                    // 同步初始化错误状态数组
                    this.fzListErrors.push(false);
                }
            }

        },
        onAverage() {
            const { mfbzl } = this.formData;
            this.fzList.forEach((item, index) => {
                item.num = mfbzl;
                // 同时更新错误状态
                if (this.fzListErrors[index] !== undefined) {
                    this.$set(this.fzListErrors, index, false);
                }
            })
            // 清除相关字段的错误状态
            this.formErrors.mfbzl = false;
        },
        onReset() {
            this.fzList.forEach((item, index) => {
                item.num = "";
                // 同时更新错误状态
                if (this.fzListErrors[index] !== undefined) {
                    this.$set(this.fzListErrors, index, false);
                }
            })
            // 清除相关字段的错误状态
            this.formErrors.mfbzl = false;
        },
        onPrint(item) {
            EventBus.$emit('subPackageDialogPrintTag', { ...this.formData, printCode: `${this.formData.mybh}-set${item.subCode}`, uuid: this.uuid });
        },
        onCommonBlur(e, field) {
            if (this.formData[field]) {
                this.formErrors[field] = false;
            }
        },
        onBlurFzNum(index) {
            if (this.fzList[index] && this.fzList[index].num) {
                if (this.fzListErrors[index] !== undefined) {
                    this.$set(this.fzListErrors, index, false);
                }
            }
        },
    }
}
</script>

<style lang="scss" scoped>
.dialog-content {
    padding: 20px;
}

.unit-select {
    width: 100px;
}

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

.header-container {
    display: grid;
    grid-template-columns: 1fr 1fr 1fr;
    grid-gap: 20px;
    margin-top: 20px;
}

.header2 {
    grid-template-columns: 1fr 1fr;
}

.header-item {
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    background: #fff;
    border-radius: 4px;
    padding: 20px;
}

.header-title {
    margin-bottom: 10px;
}

.content-container {
    margin-top: 20px;
    padding: 20px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    max-height: 50vh;
    overflow: auto;
}

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

.list-item {
    display: flex;
    align-items: center;
    // margin-top: 20px;
}

.list-label {
    margin-right: 5px;
    // width: 200px;
}
.ml-5{
    margin-left: 5px;
}
</style>