<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 :isFieldsRecord="false" :item="inputItem" :error="formErrors.mybh"
                        v-model="formData.mybh" />
                </div>
                <div class="header-item">
                    <div class="header-title">分装数量</div>
                    <HandleFormItem :isFieldsRecord="false" @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 :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 type="inputNumber" :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">
                    <div v-for="(item, index) in fzList" class="list-item" :key="index">
                        <div class="list-label">{{ formData.mybh }}-set{{ item.subCode }}</div>
                        <HandleFormItem :isFieldsRecord="false" :item="inputNumberItem" :error="fzListErrors[index]"
                         type="inputNumber"   @blur="onBlurFzNum(index)" v-model="item.num" />
                        <el-button type="primary" 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';
export default {
    dicts: [
        'business_tjdw',
    ],
    components: {
        HandleFormItem,
    },
    data() {
        return {
            visible: false,
            inputItem: {
                type: "input",
                fillType: "actFill",
                disabled: true,
            },
            integerInputNumberItem: {
                type: "inputNumber",
                fillType: "actFill",
                precision: 0,
                maxlength: 3
            },
            inputNumberItem: {
                type: "inputNumber",
                fillType: "actFill",
            },
            formData: {
                mybh: "",//母液编号
                fzsl: "",//分装数量
                dw: "",//单位
                mfbzl: "",//每份包装量
            },
            fzList: [],//分装列表
            // 错误状态字段
            formErrors: {
                mybh: false,
                fzsl: false,
                dw: false,
            },
            fzListErrors: [], // 分装列表错误状态
            uuid:"",//事件id
        }
    },
    computed: {
        unitItem() {
            return {
                type: "select",
                fillType: "actFill",
                options: this.dict.type.business_tjdw
            }
        }
    },
    methods: {
        close() {
            this.visible = false;
            this.fzList = [];
            this.formData = {};
            this.resetErrors();
        },
        show(data) {
            const cloneData = JSON.parse(JSON.stringify(data));
            if(data && data.uuid) {//为了标识eventBus的事件id
                this.uuid = data.uuid
            }
            if (data.fzList) {
                this.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(){
            EventBus.$emit('dialogSubPackageSubmit', {...this.formData, fzList: this.fzList,uuid:this.uuid});
            setTimeout(() => {
                this.close();
            }, 500);
        },
        validateFormData() {
            let isValid = true;

            // 验证母液编号
            if (!this.formData.mybh) {
                this.formErrors.mybh = true;
                isValid = false;
            }

            // 验证分装数量
            if (!this.formData.fzsl) {
                this.formErrors.fzsl = true;
                isValid = false;
            }

            // 验证单位
            if (!this.formData.dw) {
                this.formErrors.dw = true;
                isValid = false;
            }

            // 验证分装列表中的数值
            if (this.fzList && this.fzList.length > 0) {
                for (let i = 0; i < this.fzList.length; i++) {
                    if (!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({
                my: this.formData.mybh,
                count: e,
            })
            if(result.code === 200){
                const codes = result.data;
                // 根据输入的数量生成新列表
                for (let i = 0; i < e; i++) {
                    this.fzList.push({
                        num: "",
                        subCode: 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;
}

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