<template>
    <basic-container>
        <avue-crud style="height: 200px;" :option="option" :table-loading="loading"
            :data="assemblyForm.preContainersList" :page.sync="page" :permission="permissionList"
            :before-open="beforeOpen" v-model="form" ref="crud" :cell-style="{ padding: '0px', textAlign: 'center' }"
            @row-update="rowUpdate" @row-save="rowSave" @row-del="rowDel" @selection-change="selectionChange"
            @refresh-change="refreshChange" @resetColumn="resetColumnTwo('crud', 'option', 'optionBack', 309.15)"
            @saveColumn="saveColumnTwo('crud', 'option', 'optionBack', 309.15)">
            <template slot="menuLeft">
                <el-button type="primary" size="small" :disabled="seeDisabled" @click.stop="addfun">新 增</el-button>
                <el-button type="danger" size="small" plain
                    :disabled="seeDisabled || assemblyForm.preContainersList.length == 0"
                    @click.stop="handleDelete">一键删除
                </el-button>
                <el-button type="primary" size="small"
                    :disabled="seeDisabled || assemblyForm.preContainersList.length == 0"
                    @click="batchSavefun">一键保存</el-button>
                <el-button type="info" plain size="small"
                    :disabled="seeDisabled || assemblyForm.preContainersList.length == 0" @click="onclickEdit">一键编辑
                </el-button>
            </template>
            <template slot-scope="scope" slot="menu">
                <el-button size="mini" type="text" @click.stop="editfun(scope.row, scope.index)"
                    :disabled="seeDisabled">
                    {{ scope.row.$cellEdit ? '保存' : '编辑' }}
                </el-button>
                <!--<el-button-->
                <!--    size="mini"-->
                <!--    type="text"-->
                <!--    icon="el-icon-delete"-->
                <!--    :disabled="seeDisabled"-->
                <!--    @click.stop="rowDel(scope.row)"-->
                <!--&gt;删 除</el-button>-->
            </template>
            <template slot-scope="{row}" slot="cntrTypeCodeForm">
                <!-- <search-query :datalist="cntrTypeCodeData"
                          :selectValue="row.cntrTypeCode"
                          :filterable="true"
                          :clearable="true"
                          :remote="true"
                          :buttonIf="false"
                          :forParameter="{key:'id',label:'cntrType',value:'cntrType'}"
                          placeholder="请选择尺码箱型"
                          @remoteMethod="remoteMethod($event,'cntrTypeCode')"
                          @corpChange="corpChange($event,row)"
                          @corpFocus="remoteMethod($event,'cntrTypeCode')" 
                          @corpClear="corpClear($event, row)">
            </search-query> -->
                <search-query :datalist="cntrTypeCodeData" :selectValue="row.cntrTypeCode" :filterable="true"
                    :clearable="true" :remote="true" :buttonIf="false"
                    :forParameter="{ key: 'id', label: 'cnName', value: 'cnName' }" placeholder="请选择尺码箱型"
                    @remoteMethod="remoteMethod($event, 'cntrTypeCode')" @corpChange="corpChange($event, row)"
                    @corpFocus="remoteMethod($event, 'cntrTypeCode')" @corpClear="corpClear($event, row)">
                </search-query>
            </template>
            <template slot="number" slot-scope="{ row }">
                <el-input v-if="row.$cellEdit" style="width: 100%;" v-model="row.number" size="small" autocomplete="off"
                    min="0" @blur="numberBlur(row)" clearable placeholder="请输入件数"></el-input>
                <span v-else>{{ row.number }}</span>
            </template>
            <template slot="grossWeight" slot-scope="{ row }">
                <el-input v-if="row.$cellEdit" style="width: 100%;" v-model="row.grossWeight" size="small"
                    autocomplete="off" min="0" @blur="grossWeightBlur(row)" clearable placeholder="请输入毛重"></el-input>
                <span v-else>{{ row.grossWeight }}</span>
            </template>
            <template slot="measurement" slot-scope="{ row }">
                <el-input v-if="row.$cellEdit" style="width: 100%;" v-model="row.measurement" size="small"
                    autocomplete="off" min="0" @blur="measurementBlur(row)" clearable placeholder="请输入尺码"></el-input>
                <span v-else>{{ row.measurement }}</span>
            </template>

        </avue-crud>
    </basic-container>
</template>

<script>
import {
    precontainersList,
    precontainersDetail,
    precontainersSubmit,
    precontainersRemove,
    precontainersSubmitList
} from "@/api/iosBasicData/ReceivingOrders/precontainers";
import { getWorkDicts } from "@/api/system/dictbiz";
import { mapGetters } from "vuex";
import SearchQuery from "@/components/iosbasic-data/searchquery.vue";
import { bcntrtypesList } from "@/api/iosBasicData/bcntrtypes";
import { containersEqualDistribution } from "@/api/iosBasicData/containers";
import { requiredMessage } from "@/util/messageReminder";
import { number } from "echarts";

export default {
    components: { SearchQuery },
    props: {
        pid: {},
        assemblyForm: {},
        seeDisabled: {
            type: Boolean,
            default: false,
        }
    },
    data() {
        return {
            // 集装箱尺码箱型
            cntrTypeCodeData: [],
            form: {},
            query: {},
            loading: false,
            page: {
                pageSize: 10,
                currentPage: 1,
                total: 0
            },
            selectionList: [],
            option: {},
            optionBack: {
                height: '150',
                maxHeight: '150',
                // calcHeight: 30,
                tip: false,
                searchShow: true,
                searchMenuSpan: 6,
                border: true,
                index: true,
                viewBtn: true,
                selection: true,
                labelWidth: '120',
                dialogClickModal: false,
                updateBtn: false,
                saveBtn: false,
                cancelBtn: false,
                cellBtn: true, // 行编辑
                menuWidth: 80,
                menu: false,
                column: [
                    {
                        label: "尺码箱型",
                        prop: "cntrTypeCode",
                        formslot: true,
                        width: '120',
                        cell: true,
                        rules: [{
                            required: true,
                            message: " ",
                            trigger: "blur"
                        }]
                    },
                    {
                        label: "箱量",
                        prop: "quantity",
                        type: "number",
                        width: '120',
                        cell: true,
                        controls: false,
                        precision: 0,
                        rules: [{
                            required: true,
                            message: " ",
                            trigger: "blur"
                        }]
                    },
                    {
                        label: "件数",
                        prop: "number",
                        type: "number",
                        width: '120',
                        // cell:true,
                        controls: false,
                        precision: 0,
                    },
                    {
                        label: "毛重(KGS)",
                        prop: "grossWeight",
                        width: '120',
                        type: "number",
                        // cell:true,
                        controls: false,
                    },
                    {
                        label: "净重(KGS)",
                        prop: "netWeight",
                        width: '120',
                        type: "number",
                        cell: true,
                        controls: false,
                    },
                    {
                        label: "体积(CBM)",
                        prop: "measurement",
                        width: '120',
                        type: "number",
                        // cell:true,
                        controls: false,
                    },
                    {
                        label: "温度",
                        prop: "temperature",
                        cell: true,
                        controls: false,
                        type: "number",
                        width: "120"
                    },
                    {
                        label: "温度单位",
                        prop: "temperatureUnit",
                        type: 'select',
                        cell: true,
                        dicData: [{
                            label: '摄氏度',
                            value: 'C'
                        }, {
                            label: '华氏度',
                            value: 'F'
                        }]
                    },
                    {
                        label: "通风度",
                        prop: "ventilation",
                        cell: true,
                        controls: false,
                        type: "number",
                        width: "120"
                    },
                    {
                        label: "湿度",
                        prop: "humidity",
                        cell: true,
                        controls: false,
                        type: "number",
                        width: "120"
                    },
                    {
                        label: "SOC",
                        prop: "isSoc",
                        width: '120',
                        type: 'select',
                        cell: true,
                        dicData: [{
                            label: '否',
                            value: 0
                        }, {
                            label: '是',
                            value: 1
                        }]
                    },
                    {
                        label: "单程",
                        prop: "isOneway",
                        type: 'select',
                        cell: true,
                        dicData: [{
                            label: '否',
                            value: 0
                        }, {
                            label: '是',
                            value: 1
                        }]
                    },
                    {
                        label: "NOR",
                        prop: "nor",
                        width: '100',
                        type: 'select',
                        cell: true,
                        dicData: [{
                            label: '否',
                            value: 0
                        }, {
                            label: '是',
                            value: 1
                        }]
                    },
                    {
                        label: "OOG",
                        prop: "oog",
                        width: '120',
                        type: 'select',
                        cell: true,
                        dicData: [{
                            label: '否',
                            value: 0
                        }, {
                            label: '是',
                            value: 1
                        }]
                    },
                    {
                        label: "左超(CM)",
                        prop: "overLeft",
                        type: "number",
                        cell: true,
                        controls: false,
                    },
                    {
                        label: "右超(CM)",
                        prop: "overRight",
                        type: "number",
                        cell: true,
                        controls: false,
                    },
                    {
                        label: "前超(CM)",
                        prop: "overFront",
                        type: "number",
                        cell: true,
                        controls: false,
                    },
                    {
                        label: "后超(CM)",
                        prop: "overBack",
                        type: "number",
                        cell: true,
                        controls: false,
                    },
                    {
                        label: "超高(CM)",
                        prop: "overHeight",
                        type: "number",
                        cell: true,
                        controls: false,
                    },
                    {
                        label: "备注",
                        prop: "remarks",
                        span: 24,
                        type: 'textarea',
                        width: "180",
                        slot: true,
                        minRows: 3,
                    },
                ]
            },
            data: []
        };
    },
    computed: {
        ...mapGetters(["permission"]),
        permissionList() {
            return {
                addBtn: this.vaildData(this.permission.precontainers_add, false),
                viewBtn: this.vaildData(this.permission.precontainers_view, false),
                delBtn: this.vaildData(this.permission.precontainers_delete, false),
                editBtn: this.vaildData(this.permission.precontainers_edit, false)
            };
        },
        ids() {
            let ids = [];
            this.selectionList.forEach(ele => {
                ids.push(ele.id);
            });
            return ids.join(",");
        }
    },
    async created() {
        this.option = await this.getColumnData(this.getColumnName(309.15), this.optionBack);
    },
    methods: {
        onclickEdit() {
            for (let item of this.assemblyForm.preContainersList) {
                this.$delete(item, '$cellEdit')
                this.$set(item, '$cellEdit', true)
            }
        },
        // 件数失焦事件
        numberBlur(row) {
            let quantityNum = 0
            for (let item of this.assemblyForm.preContainersList) {
                if (item.number) {
                    quantityNum += Number(item.number)
                }
            }
            if (quantityNum != 0) {
                this.assemblyForm.quantity = quantityNum
            }
        },
        // 毛重失焦事件
        grossWeightBlur(row) {
            let grossWeightNum = 0
            for (let item of this.assemblyForm.preContainersList) {
                if (item.grossWeight) {
                    grossWeightNum += Number(item.grossWeight)
                }
            }
            if (grossWeightNum != 0) {
                this.assemblyForm.grossWeight = grossWeightNum
            }
        },
        // 尺码失焦事件
        measurementBlur(row) {
            let measurementNum = 0
            for (let item of this.assemblyForm.preContainersList) {
                if (item.measurement) {
                    measurementNum += Number(item.measurement)
                }
            }
            if (measurementNum != 0) {
                this.assemblyForm.measurement = measurementNum
            }
        },
        // 批量保存
        batchSavefun() {
            if (!this.assemblyForm.id) {
                this.$message({
                    message: '请先保存数据之后才能添加',
                    type: 'warning'
                });
                return
            }
            // for (let item of this.assemblyForm.preContainersList) {
            //     if (!item.cntrTypeCode) {
            //         this.$message.warning('请选择尺码箱型')
            //         return;
            //     }
            //     if (!item.quantity) {
            //         this.$message.warning('请输入箱量')
            //         return;
            //     }
            //     item.pid = this.assemblyForm.id
            // }
            // precontainersSubmitList(this.assemblyForm.preContainersList).then(res => {
            //     this.$message({
            //         type: "success",
            //         message: "操作成功!"
            //     });
            //     this.$emit('billsDetailfun')
            // })
            for (let item of this.assemblyForm.preContainersList) {
                if (this.assemblyForm.containersList.filter(e => item.cntrTypeCode == e.cntrTypeCode).length != item.quantity) {
                    this.$confirm("箱型箱量改变，请检查预录费用信息?", {
                        confirmButtonText: "确定",
                        cancelButtonText: "取消",
                        showCancelButton: false,
                        type: "error"
                    }).then(() => {
                        precontainersSubmitList(this.assemblyForm.preContainersList).then(res => {
                            this.$message({
                                type: "success",
                                message: "操作成功!"
                            });
                            this.$emit('billsDetailfun')
                        })
                    })
                    return
                }
            }
            precontainersSubmitList(this.assemblyForm.preContainersList).then(res => {
                this.$message({
                    type: "success",
                    message: "操作成功!"
                });
                this.$emit('billsDetailfun')
            })
        },
        // 平均箱量
        equalDistribution() {
            if (!this.assemblyForm.id) {
                this.$message({
                    message: '请先保存数据之后才能添加',
                    type: 'warning'
                });
                return
            }
            if (this.assemblyForm.waitingBoxList.length <= 0) {
                this.$message({
                    type: "warning",
                    message: "请先添加集装箱数据!"
                });
                return
            }
            if (this.assemblyForm.preContainersList <= 0) {
                this.$message({
                    type: "warning",
                    message: "请先添加箱型数据!"
                });
                return
            }
            this.$confirm("确定平均分配?", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(() => {
                this.containersEqualDistributionfun()
            })
        },
        // 平均分配接口
        containersEqualDistributionfun() {
            containersEqualDistribution({
                pid: this.assemblyForm.id,
                waitingBox: this.assemblyForm.waitingBoxList[0]
            }).then(res => {
                if (res.data.data instanceof Array) {
                    this.$message({
                        type: "success",
                        message: "操作成功!"
                    })
                    this.$emit('billsDetailfun')
                } else {
                    // 没有除开
                    this.$message({
                        type: 'warning',
                        dangerouslyUseHTMLString: true,
                        message: '<table border="1">\n' +
                            '  <thead>\n' +
                            '    <tr>\n' +
                            '      <th></th>\n' +
                            '      <th>件数</th>\n' +
                            '      <th>毛重</th>\n' +
                            '      <th>尺码</th>\n' +
                            '    </tr>\n' +
                            '  </thead>\n' +
                            '  <tbody>\n' +
                            '    <tr>\n' +
                            '      <td>总数</td>\n' +
                            '      <td>' + res.data.data.total.quantity + '</td>\n' +
                            '      <td>' + res.data.data.total.grossWeight + '</td>\n' +
                            '      <td>' + res.data.data.total.grossWeight + '</td>\n' +
                            '    </tr>\n' +
                            '    <tr>\n' +
                            '      <td>入箱</td>\n' +
                            '      <td>' + res.data.data.average.quantity + '</td>\n' +
                            '      <td>' + res.data.data.average.grossWeight + '</td>\n' +
                            '      <td>' + res.data.data.average.grossWeight + '</td>\n' +
                            '    </tr>\n' +
                            '    <tr>\n' +
                            '      <td>差额</td>\n' +
                            '      <td>' + res.data.data.subtract.quantity + '</td>\n' +
                            '      <td>' + res.data.data.subtract.grossWeight + '</td>\n' +
                            '      <td>' + res.data.data.subtract.grossWeight + '</td>\n' +
                            '    </tr>\n' +
                            '  </tbody>\n' +
                            '</table>',
                        duration: 5000
                    });

                }

            })
        },
        corpClear(value, row) {
            this.$set(row, 'cntrTypeCode', null)
            this.$set(row, 'cntrTypeCodeId', null)
            this.$set(row, 'teu', null)
        },
        // 选择框的回调
        corpChange(value, row) {
            if (this.assemblyForm.preContainersList.filter(e => value == e.cntrTypeCode).length) {
                this.$set(row, 'cntrTypeCode', null)
                this.$set(row, 'cntrTypeCodeId', null)
                this.$set(row, 'teu', null)
                return this.$message.error('箱型不能重复')
            }
            for (let item of this.cntrTypeCodeData) {
                if (item.cnName == value) {
                    this.$set(row, 'cntrTypeCode', item.cnName)
                    this.$set(row, 'cntrTypeCodeId', item.id)
                    this.$set(row, 'teu', item.teu)
                }
            }
        },
        // 筛选数据模糊查找
        remoteMethod(value, name) {
            this.bcntrtypesListfun(value)
        },

        // 获取箱型字典数据
        bcntrtypesListfun(cnName) {
            bcntrtypesList(1, 10, { cnName }).then(res => {
                this.cntrTypeCodeData = res.data.data.records
            })
        },
        // 添加按钮确认
        rowSave(row, done, loading) {
            row.pid = this.pid
            // 如果是冻柜，则需要输入相应的通度和温度、温度，如果不是冻柜，不需要输入相应的温度等内容；
            if (this.assemblyForm.cargoType == 'reefer') {
                // 要判断的必填
                const arr = [
                    {
                        name: "温度",
                        value: "temperature",
                    },
                    {
                        name: "温度单位",
                        value: "temperatureUnit",
                    },
                    {
                        name: "通风度",
                        value: "ventilation",
                    },
                    {
                        name: "湿度",
                        value: "humidity",
                    },
                ]
                if (!requiredMessage(row, arr)) {
                    loading(); // 按钮的禁用关闭
                    return;
                }
            }
            precontainersSubmit(row).then(() => {
                this.$message({
                    type: "success",
                    message: "操作成功!"
                });
                this.$emit('billsDetailfun')
                done();
            }, error => {
                loading();
                window.console.log(error);
            });
        },
        // 编辑确认按钮
        rowUpdate(row, index) {
            let rulesRow = [
                {
                    name: "尺码箱型",
                    value: "cntrTypeCode",
                },
                {
                    name: "箱量",
                    value: "quantity",
                },

            ]
            if (!requiredMessage(row, rulesRow)) {
                return;
            }
            // 如果是冻柜，则需要输入相应的通度和温度、温度，如果不是冻柜，不需要输入相应的温度等内容；
            if (this.assemblyForm.cargoType == 'reefer') {
                // 要判断的必填
                const arr = [
                    {
                        name: "温度",
                        value: "temperature",
                    },
                    {
                        name: "温度单位",
                        value: "temperatureUnit",
                    },
                    {
                        name: "通风度",
                        value: "ventilation",
                    },
                    {
                        name: "湿度",
                        value: "humidity",
                    },
                ]
                if (!requiredMessage(row, arr)) {
                    return;
                }
            }
            if (!this.pid) {
                this.$message({
                    message: '请先保存数据之后才能添加',
                    type: 'warning'
                });
                return
            }
            if (row.id) {
                this.$confirm("已经存在配箱信息,如果修改预配箱数据 要清除全部配箱信息?", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                }).then(() => {
                    precontainersSubmit(row).then(() => {
                        this.$message({
                            type: "success",
                            message: "操作成功!"
                        });
                        this.$set(row, '$cellEdit', false)
                        this.$emit('billsDetailfun')
                    })
                })
            } else {
                row.pid = this.pid
                precontainersSubmit(row).then(() => {
                    this.$message({
                        type: "success",
                        message: "操作成功!"
                    });
                    this.$set(row, '$cellEdit', false)
                    this.$emit('billsDetailfun')
                }, error => {
                    console.log(error);
                });
            }
        },
        rowDel(row) {
            this.$confirm("确定将选择数据删除?", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            })
                .then(() => {
                    if (!row.id) {
                        this.$message({
                            type: "success",
                            message: "操作成功!"
                        });
                        this.assemblyForm.preContainersList.splice(row.$index, 1)
                    } else {
                        precontainersRemove(row.id).then(() => {
                            this.$message({
                                type: "success",
                                message: "操作成功!"
                            });
                            this.$emit('billsDetailfun')
                        });
                    }
                })
        },
        // 新增
        addfun() {
            this.$refs.crud.rowCellAdd({ pid: this.assemblyForm.id })
            // this.$refs.crud.rowAdd()
        },
        // 编辑
        editfun(row, index) {
            if (row.$cellEdit) {
                // 保存
                this.rowUpdate(row, index)
                // this.$set(row,'$cellEdit',false)
            } else {
                this.$set(row, '$cellEdit', true)
            }
            // this.$refs.crud.rowEdit(row,index)
        },
        // 多选删除
        handleDelete() {
            if (this.selectionList.length === 0) {
                this.$message.warning("请选择至少一条数据");
                return;
            }
            this.$confirm("确定将选择数据删除?", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            })
                .then(() => {
                    this.precontainersRemovefun()
                })
        },
        // 删除接口
        precontainersRemovefun() {
            let multiList = this.selectionList
            let arr = this.assemblyForm.preContainersList
            // 获取有id 的数据
            const itemsWithId = multiList.filter(item => item.id != null);
            let arrIds = itemsWithId.map(item => item.id) // 获取id 数据
            // 把选中的删除掉
            multiList.forEach((item) => {
                for (let index in arr) {
                    if (JSON.stringify(item) == JSON.stringify(arr[index])) {
                        arr.splice(Number(index), 1)
                    }
                }
            })
            // 有id 的处理
            if (itemsWithId.length != 0) {
                precontainersRemove(arrIds.join(',')).then(() => {
                    this.$message({
                        type: "success",
                        message: "操作成功!"
                    });
                    // this.$emit('billsDetailfun')
                    this.$refs.crud.toggleSelection();
                })
            };
        },
        beforeOpen(done, type) {
            if (["edit", "view"].includes(type)) {
                precontainersDetail(this.form.id).then(res => {
                    this.form = res.data.data;
                });
            }
            done();
        },
        selectionChange(list) {
            this.selectionList = list;
        },
        selectionClear() {
            this.selectionList = [];
            this.$refs.crud.toggleSelection();
        },
        refreshChange() {
            console.log('刷新')
        },

        //自定义列保存
        async saveColumnTwo(ref, option, optionBack, code) {
            /**
             * 已定义全局方法，直接使用，saveColumnData保存列数据方法,参数传值(表格名称，当前表格的option数据)
             * 已定义全局方法，直接使用，getColumnName方法用来获取枚举值，参数根据自己定义的code值获取中文名
             * 一定要执行异步操作，要等接口成功返回，才能执行下一行代码
             */
            const inSave = await this.saveColumnData(this.getColumnName(code), this[option]);
            if (inSave) {
                this.$message.success("保存成功");
                //关闭窗口
                this.$refs[ref].$refs.dialogColumn.columnBox = false;
            }
        },
        //自定义列重置
        async resetColumnTwo(ref, option, optionBack, code) {
            this[option] = this[optionBack];
            const inSave = await this.delColumnData(this.getColumnName(code), this[optionBack]);
            if (inSave) {
                this.$message.success("重置成功");
                this.$refs[ref].$refs.dialogColumn.columnBox = false;
            }
        },

    }
};
</script>

<style></style>
