<template>
    <div>
        <el-card class="el-card">
            <el-form
                :inline="true"
                :model="query"
                class="query-form"
                size="mini"

            >
                <el-row style="width: 100%">
                    <el-form-item class="query-form-item">
                        <el-input style="width: 300px" v-model="query.billNo" placeholder="单据号"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button-group>
                            <el-button type="primary" icon="el-icon-refresh" @click="onReset"></el-button>
                            <el-button type="primary" icon="search" @click="onSubmit">查询</el-button>
                        </el-button-group>
                    </el-form-item>
                </el-row>

            </el-form>

            <el-table
                v-loading="loading"
                :data="list"
                style="width: 100%"
                @row-click="getOrderDetailList"
                highlight-current-row
                @selection-change="handleSelectionChange"
                :row-class-name="tableRowClassName"
            >
                <el-table-column label="序号" type="index"></el-table-column>
                <el-table-column label="扫码单据类型" prop="action">
                    <template slot-scope="scope">
                        <span>{{ getActionName(scope.row.action) }}</span>
                    </template>
                </el-table-column>
                <el-table-column
                    label="扫码单据号"
                    prop="id"
                    show-overflow-tooltip="true"
                ></el-table-column>
                <el-table-column
                    label="业务单据号"
                    prop="erpFk"
                    show-overflow-tooltip="true"
                ></el-table-column>
                <el-table-column label="来源" prop="fromType">
                    <template slot-scope="scope">
                        <span>{{ fromTypeMap[scope.row.fromType] }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="往来单位" prop="fromCorp" width="250">
                </el-table-column>
                <el-table-column label="当前仓库" prop="locStorageCode" width="150">
                    <template slot-scope="scope">
                        <span>{{ getStorageName(scope.row.locStorageCode) }}</span>
                    </template>
                </el-table-column>

                <el-table-column label="所属科室" prop="deptName" width="120" v-if="enableDept">
                </el-table-column>

                <el-table-column
                    label="创建时间"
                    prop="actDate"
                    width="150"
                    show-overflow-tooltip="true"
                >
                    <template slot-scope="scope">
                        <i class="el-icon-time"></i>
                        <span>{{ scope.row.actDate }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="操作" fixed="right" width="150">
                    <template slot-scope="scope">
                        <el-button
                            type="text"
                            size="small"
                            @click.native.stop="intentDetail(scope.row)"
                        >详情
                        </el-button
                        >
                    </template>
                </el-table-column>
            </el-table>
        </el-card>

        <el-card class="el-card" v-if="true">
            <el-table
                v-loading="loading"
                :data="detailList"
                style="width: 100%"
            >
                <el-table-column label="序号" type="index"></el-table-column>
                <el-table-column
                    label="产品通用名"
                    prop="coName"
                    :show-overflow-tooltip="true"
                ></el-table-column>
                <el-table-column
                    label="包装规格"
                    prop="packSpec"
                    :show-overflow-tooltip="true"
                ></el-table-column>
                <el-table-column
                    label="批次号"
                    prop="batchNo"
                    :show-overflow-tooltip="true"
                ></el-table-column>
                <el-table-column
                    label="生产日期"
                    prop="productDate"
                    :show-overflow-tooltip="true"
                >
                    <template slot-scope="scope">
                        <span>{{ convertDateFun(scope.row.productDate) }}</span>
                    </template>
                </el-table-column>
                <el-table-column
                    label="失效日期"
                    prop="expireDate"
                    :show-overflow-tooltip="true"
                >
                    <template slot-scope="scope">
                        <span>{{ convertDateFun(scope.row.expireDate) }}</span>
                    </template>
                </el-table-column>
                <el-table-column
                    label="单据数量"
                    prop="erpCount"
                    :show-overflow-tooltip="true"
                ></el-table-column>
                <el-table-column
                    label="实际数量"
                    prop="reCount"
                    :show-overflow-tooltip="true"
                ></el-table-column>

                <el-table-column label="扫码数量" prop="count"></el-table-column>
                <el-table-column
                    label="供应商"
                    prop="supName"
                    :show-overflow-tooltip="true"
                ></el-table-column>
                <el-table-column
                    label="生产企业"
                    prop="productCompany"
                    :show-overflow-tooltip="true"
                ></el-table-column>
                <el-table-column
                    label="注册/备案凭证号"
                    prop="authCode"
                    :show-overflow-tooltip="true"
                ></el-table-column>
            </el-table>
        </el-card>

        <el-dialog
            title="详情"
            :visible.sync="codeDetailVisible"
            width="80%"
            v-if="codeDetailVisible"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
        >
            <codeReplace
                :idQuery="idQuery"
                :editType="editType"
                v-on:closeDetailDialog="closeDetailDialog"
            ></codeReplace>
        </el-dialog>

        <el-dialog title="校验信息" :visible.sync="errDialogVisible" width="30%">
            <span>{{ errorDetail }}</span>
            <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="errDialogVisible = false">关 闭</el-button>
            </span>
        </el-dialog>

        <el-dialog
            title="修改时间"
            :visible.sync="editOrderVisible"
            width="35%"
            v-if="editOrderVisible"
        >

            <el-row style="width: 100%">
                <el-lable>创建时间：</el-lable>
                <el-date-picker
                    v-model="actDate"
                    type="datetime"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    :picker-options="pickerOptions"
                    placeholder="选择日期时间">
                </el-date-picker>
            </el-row>

            <el-row style="width: 100%; margin-top: 20px;">
                <el-lable>审核时间：</el-lable>
                <el-date-picker
                    v-model="auditTime"
                    type="datetime"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    :picker-options="pickerOptions"
                    placeholder="选择日期">
                </el-date-picker>
            </el-row>

            <div style="text-align: right; margin-top: 10px;">
                <el-button type="primary" size="small" icon="search" @click="updateOrderInfo"
                >提交
                </el-button
                >
                <el-button type="primary" size="small" icon="search" @click="cancelEdit"
                >取消
                </el-button
                >
            </div>
        </el-dialog>

    </div>
</template>

<script>
import {filterOrderForDelete, orderDetail, deleteByOrderId, updateOrderInfo} from "../../api/inout/order";
import store from "../../store";
import {getBussinessType} from "../../api/basic/bussinessType";
import {filterAllByUser} from "@/api/basic/invWarehouse";
import codeReplace from "../business/codeReplace";
import {selectSysParamByKey} from "@/api/param/systemParamConfig";
import {convertDate} from  "@/utils/date"

export default {
    name: "stockOrderDelete",
    data() {
        return {
            convertDateFun:convertDate,
            query: {
                billNo: "",
                page: 1,
                limit: 10
            },
            detailQuery: {
                orderIdFk: "",
                page: 1,
                limit: 20
            },
            busTypes: [],
            list: [],
            detailList: [],
            currentCheckIndex: -1,
            multipId: [],
            formLabelWidth: '150px',
            total: 0,
            detailTotal: 0,
            storageList: [],
            loading: false,
            detailLoading: false,
            enableDept: false,
            idQuery: {
                id: "",
            },
            editType: 1,
            sourceMap: {
                "1": "web端新增单据",
                "2": "第三方系统",
                "3": "扫码单据转换",
                "4": "采购计划转换",
            },
            fromTypeMap: {
                "1": "UDIMS平台",
                "2": "网页新增",
                "3": "pda即时校验",
                "4": "pda未校验",
                "5": "pc端扫码精灵",
                "6": "缺量补录单据",
                "7": "UDI供应商平台",
                "8": "平衡补录单据",
                "10": "手动补单"
            },
            erpCheckStatus: {
                0: "未校验",
                1: "失败",
                2: "成功",
            },
            isSp: store.getters.customerId,
            detailFormData: {},
            detailFormLoading: false,
            actDateRange: [],
            curRow: null,
            codeDetailVisible: false,
            editOrderVisible: false,
            actDate: null, //创建时间
            auditTime: null, //审核时间
            orderIds: [],
            pickerOptions: {
                disabledDate: time => {
                    let endDate = new Date().getTime();
                    let nowDate = new Date(time).getTime();
                    return (nowDate > endDate);
                }
            }
        }
    },
    methods: {
        onReset() {
            this.$router.push({
                path: ""
            });
            this.query = {
                billNo: ""
            };
            this.list = [];
            this.detailList = [];
            this.actDateRange = [];
        },
        onSubmit() {
            this.query.page = 1;
            this.getList();
        },
        handleCurrentChange(val) {
            this.query.page = val;
            this.getList();
        },

        changeFun(row) {
            let _this = this;
            _this.multipId = []; //每次改动重置ID
            row.forEach((item) => {
                _this.multipId.push(item.id);
            })
        },
        detailHandleCurrentChange(val) {
            this.query.page = val;
            this.getOrderDetailList();
        },
        // 刷新表单
        resetForm() {
            if (this.$refs["dataForm"]) {
                // 清空验证信息表单
                this.$refs["dataForm"].clearValidate();
                // 刷新表单
                this.$refs["dataForm"].resetFields();
                this.getList();
            }
        },
        getList() {
            this.query.billNo = this.query.billNo.trim();
            if (this.query.billNo === null || this.query.billNo === "") {
                this.$message.warning("请输入需要查询的单号");
            } else {
                this.loading = true;
                filterOrderForDelete(this.query)
                    .then(response => {
                        this.loading = false;
                        this.list = response.data.list || [];
                        this.detailList = [];
                        this.total = response.data.total || 0;
                    })
                    .catch(() => {
                        this.loading = false;
                        this.list = [];
                        this.total = 0;
                        this.detailList = [];
                    });
            }
        },
        getOrderDetailList(row) {
            if (this.$isNotBlank(row)) {
                this.detailQuery.orderId = row.id;
                this.detailQuery.orderIdFk = row.id;
            }
            this.detailLoading = true;
            orderDetail(this.detailQuery)
                .then((response) => {
                    this.detailLoading = false;
                    this.detailList = response.data || [];
                })
                .catch(() => {
                    this.detailLoading = false;
                    this.detailList = [];
                });
        },
        tableRowClassName({row, rowIndex}) {
            if (rowIndex === 0) {
                return 'highlight-row';
            }
            return '';
        },
        getActionName(action) {
            for (let i = 0; i < this.busTypes.length; i++) {
                if (this.busTypes[i].action === action) {
                    return this.busTypes[i].name;
                }
            }
        },
        getBusType() {
            let query = {
                enabled: true,
            };
            getBussinessType(query)
                .then((response) => {
                    this.busTypes = response.data.list || [];
                })
                .catch(() => {
                });
        },
        getStorageName(code) {
            for (let i = 0; i < this.storageList.length; i++) {
                if (this.storageList[i].code === code) {
                    return this.storageList[i].name;
                }
            }
        },
        getStorage() {
            this.storageList = [];
            filterAllByUser()
                .then((response) => {
                    this.storageList = response.data || [];
                })
                .catch(() => {
                });
        },
        deleteOrder(row) {
            this.$confirm('是否确认删除单据及相关数据?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                let params = {
                    id: row.id
                };
                deleteByOrderId(params).then((res) => {
                    if (res.code === 20000) {
                        this.$message({
                            type: 'success',
                            message: '删除成功!'
                        });
                        this.getList();
                        this.detailList = [];
                    }
                }).catch((error) => {
                    this.$message.error("删除失败");
                });
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        deleteAllOrder() {
            if (this.query.billNo === null || this.query.billNo === "" || this.list.length === 0) {
                return;
            }
            this.$confirm("是否确认删除此单据及所有关联单据？", "提示", {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                let ids = [];
                this.list.forEach(item => {
                    ids.push(item.id);
                });
                let params = {
                    ids: ids
                };
                deleteByOrderId(params).then((res) => {
                    if (res.code === 20000) {
                        this.$message.success("删除成功");
                        this.list = [];
                        this.detailList = [];
                    }
                }).catch((error) => {
                    this.$message.error("删除失败");
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            })
        },
        editAllOrderTime() {
            if (this.query.billNo === null || this.query.billNo === "" || this.list.length === 0) {
                return;
            }
            this.actDate = null;
            this.auditTime = null;
            this.editOrderVisible = true;
        },
        intentDetail(row) {
            this.codeDetailVisible = true;
            this.idQuery.id = row.id;
        },
        handleEdit(row) {
            this.editOrderVisible = true;
            let actDateSplit = row.actDate.split(" ");
            this.actDate = actDateSplit[0];
            this.actDate2 = actDateSplit[1];

            let auditTimeSplit = row.auditTime.split(" ");
            this.auditTime = auditTimeSplit[0];
            this.auditTime2 = auditTimeSplit[1];

            this.orderIds = [];
        },
        updateOrderInfo() {
            if (this.actDate === null || this.actDate === '') {
                this.$message.warning("创建时间不能为空");
                return;
            }
            this.editOrderVisible = false;
            this.list.forEach(item => {
                this.orderIds.push(item.id);
            });
            let data = {
                actDate: this.actDate,
                auditTime: this.auditTime,
                orderIds: this.orderIds
            };
            updateOrderInfo(data).then((res) => {
                if (res.code === 20000) {
                    this.$message.success("修改成功");
                    this.getList();
                }
            }).catch((error) => {
                this.$message.error(error.message);
            });
        },
        cancelEdit() {
            this.editOrderVisible = false;
        }
    },
    components: {
        codeReplace
    },
    filters: {
        statusFilterType(status) {
            const statusMap = {
                0: "gray",
                1: "success"
            };
            return statusMap[status];
        },
        statusFilterName(status) {
            const statusMap = {
                "1": "草稿",
                "2": "未配货",
                "3": "待校验",
                "4": "已校验",
                "5": "已核对",
            };
            return statusMap[status];
        },
        typeFilterName(type) {
            const typeMap = {
                1: "预入库",
                2: "普通采购",
            };
            return typeMap[type];
        }
    },
    created() {
        this.getBusType();
        this.getStorage();
        selectSysParamByKey({paramKey: "muti_inv_mode"}).then((res) => {
            if (res.code === 20000) {
                if (res.data.paramValue === "0") {
                    this.enableDept = true;
                }
            }
        })
    }
}
</script>

<style scoped>

.el-dialog {
    display: flex;
    flex-direction: column;
    margin: 0 !important;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

.el-dialog .el-dialog__body {
    flex: 1;
    overflow: auto;
}


.el-table /deep/ .highlight-row {
    background: #cae3f9;
}

</style>

