<template>
    <el-dialog title="新增其他出库" append-to-body :modelValue="openShow" width="70%" @close="closeDialog" fullscreen>

        <el-form ref="form" :model="stOtherOutRecord" :rules="rules" label-width="100px" size="mini">
            <el-row>
                <!-- <el-col :span="8">
                    <el-form-item label="出库单号" prop="stAccBill.billCode">
                        <el-input v-model="stOtherOutRecord.stAccBill.billCode" :disabled="true" />
                    </el-form-item>
                </el-col> -->
                <el-col :span="6">
                    <el-form-item label="出库日期" prop="stAccBill.billDate">
                        <el-date-picker class="item-choose" v-model="stOtherOutRecord.stAccBill.billDate"
                            :picker-options="billDatePicker" type="date" value-format="yyyy-MM-dd" clearable
                            placeholder="请选择" style="width: 250px;" />
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="出库原因" prop="outType">
                        <el-select v-model="stOtherOutRecord.outType" @change="changeUseType" class="item-choose">
                            <el-option v-for="(item, index) in useTypeOptions" :key="index" :label="item.label"
                                :value="item.value" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="出库仓库" prop="stAccBill.coStorehouse.shId">
                        <!-- <co-store-house-sel ref="storeHouse" v-model="stOtherOutRecord.stAccBill.coStorehouse.shId"
                    :option="shOption" @itemValue="storeHouseChange" /> -->
                        <el-select v-model="stOtherOutRecord.stAccBill.coStorehouse.shId" @change="storeHouseChange"
                            class="item-choose">
                            <el-option v-for="(item, index) in shOption" :key="index" :label="item.label"
                                :value="item.value" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="领料人员" prop="stAccBill.pfUserInfo.userId">
                        <el-select v-model="stOtherOutRecord.stAccBill.pfUserInfo.userId" filterable
                            class="item-choose">
                            <el-option v-for="(item, index) in userData" :key="index"
                                :label="item.userCode + '/' + item.userName" :value="item.userId" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="工装编号" prop="pjMold.mid">
                        <el-select v-model="stOtherOutRecord.pjMold.mid" value-key="id" filterable class="item-choose">
                            <el-option v-for="item in treeData" :key="item.mid" :label="item.toolingCode"
                                :value="item.mid" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6" v-if="isShowInput">
                    <el-form-item label="出库工作订单" >
                        <el-input v-model="stOtherOutRecord.woCode" class="item-choose" />
                    </el-form-item>
                </el-col>
                 <el-col :span="12">
                    <el-form-item label="备注" prop="memo" class="auto-fit">
                        <el-input placeholder="请输入" :rows="2" v-model="stOtherOutRecord.memo" type="textarea"
                            minlength="0" maxlength="100" show-word-limit style="width: 100%;" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
               
            </el-row>
            <div slot="left" style="margin-bottom: 12px;">
                <el-button type="success" size="mini" @click="insertEvent()">插入一行</el-button>
                <el-button type="danger" size="mini" @click="$vxeTableUtil.deleteRow($refs.xTable)">删除一行</el-button>
                <!-- <el-button type="primary" size="mini" @click="submit()">保存</el-button> -->
            </div>
            <el-table ref="xTable" :loading="btnLoading" :data="outbankList" border show-overflow
                class="el-table-element" stripe keep-source highlight-current-row @edit-closed="editClosed"
                @edit-actived="editActived">
                <el-table-column type="checkbox" width="40" />
                <el-table-column label="仓库物料" prop="rlsId">
                    <template v-slot:edit="scope">
                        <!-- <st-store-goods-out v-model="scope.row.rlsId" :option="[]" :params="goodsParams"
                            @itemValue="goodsItemValue" /> -->
                    </template>
                    <template v-slot="{ row }">{{ row.goodsCodeAndGoodsName }}</template>
                </el-table-column>
                <el-table-column label="物料名称" prop="coGoods.goodsName" />
                <el-table-column label="型号/牌号" prop="coGoods.mtltmrk" />
                <el-table-column label="批号" prop="piNo" />
                <el-table-column label="炉批号" prop="stovePiNo" />
                <el-table-column label="库位号" prop="storageLocation.location" />
                <el-table-column label="库存数量" prop="quantity" />
                <el-table-column label="出库件数" :edit-render="{ type: 'default' }" prop="outQuantity">
                    <template v-slot:edit="scope">
                        <!-- <vd-input-number v-model="scope.row.outQuantity" :min="-1000000000" :max="1000000000"
                            :precision="4" /> -->
                    </template>
                    <template v-slot="{ row }">{{ row.outQuantity }}</template>
                </el-table-column>
                <el-table-column label="计量单位" prop="coGoods.unitName" />
                <el-table-column label="到期日期" prop="scrapCycle" />
                <el-table-column label="入库日期" prop="createTime" />
            </el-table>

        </el-form>

        <template #footer>
            <span class="dialog-footer">
                <el-button @click="closeDialog">取 消</el-button>
                <el-button type="primary" @click="submit">确 定</el-button>
            </span>
        </template>
    </el-dialog>
</template>
<script>
export default {
    props: {
        showDialog: {
            type: Boolean,
            default: false
        },
    },
    data() {
        const assQuantityValid = ({
            cellValue,
            rule,
            rules,
            row,
            rowIndex,
            column,
            columnIndex
        }) => {
            return new Promise((resolve, reject) => {
                if (row.coGoods) {
                    if (row.coGoods.numAcc) {
                        if (cellValue == null) {
                            reject(new Error(this.$t("store.goodsMustInputAssQuatity")));
                        }
                    }
                }
                resolve();
            });
        };
        return {
            openShow: false,

            userOption: [],
            shOption: [],
            moldOption: {},
            treeData: [],
            stOtherOutRecord: {
                stAccBill: {
                    billDate: new Date(),
                    pfUserInfo: { dept: {} },
                    coStorehouse: { shId: null }
                },
                pjMold: { mid: null },
                outType: 4,
                woCode: null,
                memo: null
            },
            btnLoading: false,
            outbankList: [],
            oldShId: null,
            disableTaskCode: true,
            billDatePicker: '',
            useTypeOptions: [
                {
                    value: 0,
                    label: "报废出库"
                },
                {
                    value: 1,
                    label: "料头出库"
                },
                {
                    value: 2,
                    label: "超额出库"
                },
                {
                    value: 3,
                    label: "复检出库"
                },
                {
                    value: 4,
                    label: "领用出库"
                },
                {
                    value: 5,
                    label: "库转移"
                },
                {
                    value: 6,
                    label: "退货出库"
                },
                {
                    value: 7,
                    label: "物料出库"
                },
                {
                    value: 8,
                    label: "班组提请"
                }
            ],
            goodsParams: {},
            piNoParams: {},
            rules: {
                stAccBill: {
                    coStorehouse: {
                        shId: [{ required: true }]
                    },
                    pfUserInfo: {
                        userId: [{ required: true }]
                    }
                },
                moId: [],

                outType: [{ required: true }],
                memo: [{ required: true }]
            },
            gridRules: {
                rlsId: [{ required: true }],
                shelfNo: [{ required: true }],
                assQuantity: [{ validator: assQuantityValid }]
            },
            isShowInput: false,
            userData: []
        }
    },
    mounted() {
        this.openShow = this.showDialog
    },
    methods: {
        closeDialog() {
            this.openShow = false
            this.$emit('closeDialog');
        },
        userDataFn() {
            // this.$ajax.post("sysComBox/user", { "filterValue": null, "paging": { "pageSize": 9999999, "pageNumber": 1 }, "baseParams": {} }).then(res => {
            //     if (this.$ifAjax(res)) {
            //         this.userData = res.data.list;

            //     }
            // });
        },
        opened() {
            this.stOtherOutRecord = {
                stAccBill: {
                    billDate: new Date(),
                    pfUserInfo: { dept: {} },
                    coStorehouse: { shId: null }
                },
                pjMold: { mid: null },
                outType: 4,
                memo: null
            };
            this.oldShId = null;
            this.outbankList = [];
            this.$refs.form.resetFields();
            if (this.abId == null) {
                this.queryDataForAdd();
            } else {
                this.queryData();
            }
            this.changeUseType(this.stOtherOutRecord.outType);
            this.moldList();
        },
        moldList() {
            // this.$ajax.post("stOtherReceiptRecord/queryMoldList").then(res => {
            //     if (this.$ifAjax(res)) {
            //         this.loading = false;
            //         this.treeData = res.data.list;
            //     }
            // });
            // this.$ajax.post("stOtherOutRecord/generateCode").then(res => {
            //     if (this.$ifAjax(res)) {
            //         this.stOtherOutRecord.stAccBill.billCode =
            //             res.data.stAccBill.billCode;

            //     }
            // });
        },
        queryDataForAdd() {
            this.$ajax.get("stOtherOutRecord/preparedForAdd").then(res => {
                this.stOtherOutRecord = res.data;
                this.userOption = [
                    {
                        userId: this.stOtherOutRecord.stAccBill.pfUserInfo.userId,
                        userName: this.stOtherOutRecord.stAccBill.pfUserInfo.userName
                    }
                ];

            });
        },
        queryData() {
            // 根据凭证单ID查询入库数据
            this.$ajax.get("stOtherOutRecord/queryForEdit/" + this.abId).then(res => {
                const { stOtherOutRecord, outbankList, prMoldOrder } = res.data;
                this.stOtherOutRecord = stOtherOutRecord;
                this.outbankList = outbankList;
                this.oldShId = this.stOtherOutRecord.stAccBill.coStorehouse.shId;
                this.userOption = [
                    {
                        userId: this.stOtherOutRecord.stAccBill.pfUserInfo.userId,
                        userName: this.stOtherOutRecord.stAccBill.pfUserInfo.userName
                    }
                ];
                this.shOption = [
                    {
                        shId: this.stOtherOutRecord.stAccBill.coStorehouse.shId,
                        shName: this.stOtherOutRecord.stAccBill.coStorehouse.shName
                    }
                ];
                this.stOtherOutRecord.moId = prMoldOrder.moId;
                this.moldOption[prMoldOrder.moId] = prMoldOrder;
            });
        },
        insertEvent(row = -1) {
            // 新增一行
            // this.$refs.xTable.insertAt({}, row);
            this.outbankList.push(row)
        },
        editActived({ row, rowIndex, column, columnIndex, $columnIndex, cell }) {

        },
        editClosed({ row, rowIndex, column, columnIndex, $columnIndex, cell }) {
            // 编辑完成后触发
            if (
                column.property === "quantity" ||
                column.property === "unitPrice" ||
                column.property === "abdMoney" ||
                column.property === "assQuantity"
            ) {
                this.changeData(row, column.property);
            }
        },
        activeCellMethod({ column, columnIndex }) {
            // 文本禁止编辑
            if (this.stOtherOutRecord.stAccBill.coStorehouse.shId == null) {
                this.$message.error(this.$t("store.pleaseChoseStore"));
                return false;
            }

            var row = this.$refs.xTable.getCurrentRecord();

            if (column.property === "assQuantity") {
                if (!row.coGoods.numAcc) {
                    this.$message.error(this.$t("store.pleaseChoseGoodsForNumAcc"));
                    return false;
                }
            }
            return true;
        },
        close(isRefresh) {
            this.$emit("cancel", isRefresh === true);
        },
        goodsItemValue(item) {
            // 选择完数据，对关联数据进行修改
            var row = this.$refs.xTable.getCurrentRecord();

            if (item.storageLocation != null) {
                this.$set(row, "storageLocation", item.storageLocation);
            }

            this.$set(row, "quantity", item.quantity);
            this.$set(row, "coGoods", item.coGoods);
            this.$set(row, "rlsId", item.rlsId);
            this.$set(row, "piNo", item.piNo);
            this.$set(row, "stovePiNo", item.stovePiNo);
            this.$set(row, "goodsCodeAndGoodsName", item.goodsCodeAndGoodsName);
            this.$set(row, "createTime", item.createTime);
            this.$set(row, "scrapCycle", item.scrapCycle);
        },
        storeHouseChange(item) {
            if (item.shName.indexOf("玻璃饼") !== -1) {
                this.isShowInput = true;
            } else {
                this.isShowInput = false;
            }
            this.goodsParams = { baseParams: { shId: item.shId } };
        },
        changeUseType(outType) {

        },

        changeData(row, fieldName) {
            // 数量
            let quantityVal = row.quantity;
            // 件数
            let assQuantityVal = row.assQuantity;
            // 单价
            let priceVal = row.unitPrice;
            // 金额
            let abdMoneyVal = row.abdMoney;
            // 件数核算
            const numAcc = row.coGoods.numAcc;

            if (quantityVal === undefined || quantityVal === null) {
                quantityVal = 0;
            }
            if (assQuantityVal === undefined || assQuantityVal === null) {
                assQuantityVal = 0;
            }
            if (priceVal === undefined || priceVal === null) {
                priceVal = 0;
            }

            const n = this.$number;
            if (
                fieldName === "quantity" ||
                fieldName === "unitPrice" ||
                fieldName === "assQuantity"
            ) {
                if (numAcc) {
                    abdMoneyVal = n.floatMul(priceVal, assQuantityVal, 2);
                } else {
                    abdMoneyVal = n.floatMul(priceVal, quantityVal, 2);
                }
                this.$set(row, "abdMoney", abdMoneyVal);
            } else {
                if (numAcc) {
                    priceVal = n.floatDiv(abdMoneyVal, assQuantityVal, 6);
                } else {
                    priceVal = n.floatDiv(abdMoneyVal, quantityVal, 6);
                }
                this.$set(row, "abdMoney", abdMoneyVal);
            }
        },
        getMinBillDate() {
            const self = this;

            return {
                disabledDate(time) {
                    if (self.stOtherOutRecord.stAccBill.billDate) {
                        return (
                            new Date(self.stOtherOutRecord.stAccBill.billDate).getTime() >
                            time.getTime()
                        );
                    }
                }
            };
        },
        submit() {
            // this.$refs.form.validate(formValid => {
            //     if (formValid) {
            //         if (this.isShowInput) {
            //             if (
            //                 this.stOtherOutRecord.woCode == null &&
            //                 this.stOtherOutRecord.woCode == undefined
            //             ) {
            //                 return this.$message.warning("请填写工作订单号");
            //             }
            //         }

            //         let submitList = [];
            //         const deleteIds = [];

            //         if (
            //             this.oldShId != null &&
            //             this.stOtherOutRecord.stAccBill.coStorehouse.shId !== this.oldShId
            //         ) {
            //             const { fullData } = this.$refs.xTable.getTableData();
            //             if (fullData.length > 0) {
            //                 submitList = submitList.concat(fullData);
            //             }
            //         } else {
            //             const {
            //                 insertRecords,
            //                 updateRecords
            //             } = this.$refs.xTable.getRecordset();
            //             if (insertRecords.length > 0) {
            //                 insertRecords.forEach(item => {
            //                     if (item.coGoods.goodsId != null) {
            //                         submitList.push(item);
            //                     }
            //                 });
            //             }
            //             if (updateRecords.length > 0) {
            //                 submitList = submitList.concat(updateRecords);
            //             }
            //         }

            //         const removeRecords = this.$refs.xTable.getRemoveRecords();
            //         if (removeRecords.length) {
            //             removeRecords.forEach(obj => {
            //                 if (obj.stAccBillDetail.abdId) {
            //                     deleteIds.push(obj.stAccBillDetail.abdId);
            //                 }
            //             });
            //         }

            //         if (
            //             (this.stOtherOutRecord.abId === undefined ||
            //                 this.stOtherOutRecord.abId === null) &&
            //             submitList.length === 0
            //         ) {
            //             this.$message.warning(
            //                 this.$t("videaVueLib.publics.message.noDataToSave")
            //             );
            //         } else {
            //             this.$refs.xTable.validate(submitList, errMap => {
            //                 if (errMap) {
            //                     return;
            //                 }
            //                 this.btnLoading = true;
            //                 this.$ajax
            //                     .post("stOtherOutRecord/addStOtherOutRecord", {
            //                         stOtherOutRecord: this.stOtherOutRecord,
            //                         list: submitList,
            //                         deleteIds: deleteIds
            //                     })
            //                     .then(res => {
            //                         if (this.$ifAjax(res)) {
            //                             this.$message.success(
            //                                 this.$t("videaVueLib.publics.message.success")
            //                             );
            //                             this.close(true);
            //                         }
            //                         this.btnLoading = false;
            //                     });
            //             });
            //         }
            //     }
            // });
        },
        piCodeChange(id, item) {
            this.stOtherOutRecord.taskCode = item.moCode;
        }
    }
}
</script>
<style lang="scss" scoped>
.item-choose {
    width: 250px;
}
</style>