<template>
    <div>
        <el-popconfirm confirm-button-text='确认' cancel-button-text='取消' icon="el-icon-info" icon-color="red"
            title="确认删除当前数据？" @confirm="deleteRow(rowIndex)">
            <el-button v-if="fillType === 'preFill'" slot="reference" type="text" size="small" class="delete-button">
                删除
            </el-button>

        </el-popconfirm>
        <template v-if="fillType === 'actFill'">
            <el-button type="text" size="small" @click="onSubPackage">分装</el-button>
            <el-button type="text" size="small" @click="onStartConfig">开始配制</el-button>
            <el-button type="text" size="small" @click="onConfigComplete">配制完成</el-button>
            <el-button type="text" size="small" @click="()=>onPrintTag()">打印标签</el-button>
        </template>
    </div>
</template>

<script>
import { EventBus } from "@/utils/eventBus";
import { addTj } from "@/utils/calUnitTools";
import {getuuid} from "@/utils/index"

export default {
    name: "TableOpertaion",
    props: {
        row: {
            type: Object,
            default: () => { },
        },
        columns: {
            type: Object,
            default: () => { },
        },
        rowIndex: {
            type: Number,
            default: 0,
        },
        fillType: {
            type: String,
            default: "preFill",
        },
    },

    mounted() {
        EventBus.$on("dialogSubPackageSubmit", (data) => {
            this.onSubPackageSubmit(data)
        })
        EventBus.$on("subPackageDialogPrintTag", (data) => {
            this.onPrintTag(data)
        })
    },
    destroyed() {
        EventBus.$off("dialogSubPackageSubmit")
        EventBus.$off("subPackageDialogPrintTag")
    },  
    watch: {
        row: {
            handler(newVal, oldVal) {
                this.innerRow = newVal;
            },
            deep: true,
        }
    },
    data() {
        return {
            innerRow: this.row,
            uuid:getuuid(),
        }
    },
  
    methods: {
        //获取实际填报的config
        getColumnConfig(){
            const { columns } = this;
            const { columnsData } = columns;
            let o = {};
            columnsData.forEach((item) => {
                if(item.bodyFillType === "actFill"){
                    o[item.prop] = "";
                }else if(item.bodySubFillType === "actFill"){
                    o[item.bodySubKey] = "";
                }
            });
            return o;
        },
        // 开始配置
        onStartConfig() {
            this.$emit("startConfig", { rowData: this.innerRow, rowIndex: this.rowIndex, headerSelectFields: this.columns.headerSelectFields })
        },
        // 配置完成
        onConfigComplete() {
            const actConfig = this.getColumnConfig();
            const cloneRow = JSON.parse(JSON.stringify(this.innerRow));
            const isComplete = Object.values({...actConfig,...cloneRow}).every((val)=>{
                // 0 算有值
                if (val === 0) return true;
                if (val === "0") return true;
                // 其他情况：非 null、非 undefined、非空字符串
                return val != null && val != undefined && val != "";
            });
            if(!isComplete){
                this.$message.error("表单内容未填完，请填写完成后才能配制完成")
                return
            }
            this.$emit("configComplete", { rowData: this.innerRow, rowIndex: this.rowIndex, headerSelectFields: this.columns.headerSelectFields })
        },
        // 打印标签
        onPrintTag(data) {
            if(data) {
                if(data.rowIndex === this.rowIndex){
                    this.$emit("printTag", { printCode: data.printCode,type:"subPackage",row: this.innerRow })
                }
            }else{
                this.$emit("printTag", { row: this.innerRow,type:"row" })
            }
        },
        // 分装
        onSubPackage() {
            const { columns, innerRow } = this;
            console.log(columns,innerRow,"inner")
            
            const { headerSelectFields, columnsData } = columns;
            const col = columnsData.find((item) => item.myCodeFields);
            const { myCodeFields, maxVolumeField, maxVolumeFieldUnit } = col;
            const fields = [], cols = [], units = [];
            if(!myCodeFields || myCodeFields.length === 0){
                console.warn("请先配置myCodeFields字段")
                return
            }
            myCodeFields.forEach((key) => {
                fields.push(innerRow[key])
            });
            maxVolumeField.split(",").forEach((key) => {
                cols.push(innerRow[key] || 0)
            })
            maxVolumeFieldUnit.split(",").forEach((key) => {
                units.push(headerSelectFields[key])
            })
            const {total,unit} = addTj(cols,units)

            let defaultData = { mybh: fields.join(""), maxVolume: total, maxVolumeUnit: unit, rowIndex: this.rowIndex }
            if (innerRow.fzsj) {
                defaultData = {...innerRow.fzsj,...defaultData}
            }
            EventBus.$emit("showSubPackageDialog", {...defaultData,uuid:this.uuid})
        },
        onSubPackageSubmit(data) {
            console.log(data,"submit")
            if (data.uuid === this.uuid) {
                console.log(data,"inner submit")
                this.innerRow.fzsj = data;
                //通知后端保存数据
                const params = {
                    type: "fieldChanged",
                    newRecord: null,
                    resourceList: null,
                }
                EventBus.$emit('onModifyRecord', params);
                this.$emit("subPackageSubmit", { fzsj: data, rowData: this.innerRow, headerSelectFields: this.columns.headerSelectFields });
            }
        },
        // 删除行
        deleteRow(index) {
            this.$emit("deleteRow", index);
                setTimeout(() => {
                    const params = {
                    type: "fieldChanged",
                    newRecord: null,
                    resourceList: null,
                }
                EventBus.$emit('onModifyRecord', params,)
            }, 30);
        }
    }
}
</script>

<style lang="scss" scoped>
.delete-button {
    color: red;
}
</style>