<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 v-model="query.billNo" placeholder="单据号"></el-input>
                    </el-form-item>
                    <el-form-item class="query-form-item">
                        <el-select v-model="query.billType" placeholder="请选择业务类型" clearable="true" size="mini">
                            <el-option
                                v-for="item in busTypes"
                                :key="item.localName"
                                :label="item.localName"
                                :value="item.localAction">
                                <span style="float: left">{{ item.localName }}</span>
                            </el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item class="query-form-item">
                        <el-select v-model="query.orderStatus" placeholder="请选择单据状态" clearable="true" size="mini">
                            <el-option
                                v-for="item in orderStatusList"
                                :key="item.label"
                                :label="item.label"
                                :value="item.value">
                                <span style="float: left">{{ item.label }}</span>
                            </el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item class="query-form-item">
                        <el-select v-model="query.submitStatus" placeholder="请选择提交状态" clearable="true" size="mini">
                            <el-option
                                v-for="item in submitStatusList"
                                :key="item.label"
                                :label="item.label"
                                :value="item.value">
                                <span style="float: left">{{ item.label }}</span>
                            </el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item class="query-form-item">
                        <el-input v-model="query.corpName" placeholder="往来单位" clearable></el-input>
                    </el-form-item>
                    <el-form-item class="query-form-item">
                        <span style="color: #000; margin-left: 10px; margin-right: 6px">单据日期:</span>
                        <el-date-picker
                            :picker-options="pickerOptions"
                            v-model="actDateRange"
                            type="daterange"
                            format="yyyy 年 MM 月 dd 日"
                            value-format="yyyy-MM-dd"
                            range-separator="至"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期"
                        >
                        </el-date-picker>
                    </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%; " highlight-current-row
                      @row-click="getStockOrderDetailList" ref="multipleTable">
                <el-table-column type="index" label="序号" width="50"></el-table-column>
                <el-table-column label="单据号" prop="billNo" show-overflow-tooltip></el-table-column>
                <el-table-column label="往来单位" prop="corpName" show-overflow-tooltip></el-table-column>
                <el-table-column label="单据来源" prop="sourceType" width="150">
                    <template slot-scope="scope">
                        <span>{{ sourceMap[scope.row.sourceType] }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="单据日期" prop="billdate"></el-table-column>
                <!--                <el-table-column label="单据状态">-->
                <!--                    <template slot-scope="scope">-->
                <!--                        {{ scope.row.status | statusFilterName }}-->
                <!--                    </template>-->
                <!--                </el-table-column>-->


                <el-table-column label="业务类型" prop="billType">
                    <template slot-scope="scope">
                        <span>{{ getActionName(scope.row.billType) }}</span>
                    </template>
                </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="invWarehouseCode" width="150">
                    <template slot-scope="scope">
                        <span>{{ getSubStorageName(scope.row.invWarehouseCode) }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="提交状态">


                    <template slot-scope="scope">

                        <el-tag :type="(scope.row.exportStatus) | statusFilterType">
                            {{ exportStatusMap[scope.row.exportStatus] }}
                        </el-tag>

                    </template>
                </el-table-column>
                <el-table-column label="操作" fixed="right" width="200">
                    <template slot-scope="scope">
                        <el-button
                            v-if="scope.row.submitFlag"
                            type="text"
                            size="small"
                            @click.native="submitOrder(scope.row)">
                            提交
                        </el-button>

                    </template>
                </el-table-column>
            </el-table>

            <el-pagination
                :page-size="query.limit"
                @current-change="handleCurrentChange"
                layout="prev, pager, next"
                :total="total"
            >
            </el-pagination>
        </el-card>

        <el-card class="el-card">
            <el-table v-loading="detailLoading"
                      :data="detailList"
                      @selection-change="changeFun"
                      style="width: 100%">
                <el-table-column label="产品通用名" width="240" prop="productName"></el-table-column>
                <el-table-column label="包装规格" width="200" prop="spec"></el-table-column>
                <el-table-column label="批次号" width="140" prop="batchNo"></el-table-column>
                <el-table-column label="生产日期" width="100" prop="productDate"></el-table-column>
                <el-table-column label="失效日期" width="100" prop="expireDate"></el-table-column>
                <el-table-column label="单据数量" width="100" prop="count"></el-table-column>
                <el-table-column label="实际数量" width="100" prop="reCount"></el-table-column>
                <el-table-column label="价格" width="120" prop="price"></el-table-column>
                <el-table-column label="销售清单号（第二票）" width="180" prop="secSalesListNo"></el-table-column>
                <el-table-column label="销售发票号（第一票）" width="180" prop="firstSalesInvNo"></el-table-column>
                <el-table-column label="销售发票号（第二票）" width="180" prop="secSalesInvNo"></el-table-column>
                <el-table-column label="发票日期" width="150" prop="invoiceDate"></el-table-column>
            </el-table>

            <el-pagination
                :page-size="detailQuery.limit"
                @current-change="detailHandleCurrentChange"
                layout="prev, pager, next"
                :total="detailTotal"
            >
            </el-pagination>
        </el-card>

    </div>
</template>

<script>
import {
    stockOrderDetail,
    deleteStockOrderById, deleteStockOrderDetailById,
    copyStockOrderDetail, uploadStockOrderDetail,
    updateStockOrderDetail, submitStockOrderToThirdSys
} from "../../api/inout/stockOrder";
import {stockOrderUploadList} from "@/api/inout/stockOrderUpload";
import {getLocalJoinByUser} from "../../api/basic/busLocalType";
import {filterAllByUser} from "@/api/basic/invWarehouse";
import {filterSubByInv} from "@/api/basic/invSubWarehouse";

export default {
    name: "stockOrderDelSearch",
    data() {
        return {
            query: {
                billType: null,
                corpName: null,
                locStorageCode: null,
                startTime: "",
                endTime: "",
                billNo: "",
                orderStatus: null,
                submitStatus: null,
                page: 1,
                limit: 10
            },
            detailQuery: {
                orderIdFk: "",
                page: 1,
                limit: 20
            },
            busTypes: [],
            list: [],
            detailList: [],
            total: 0,
            detailTotal: 0,
            storageList: [],
            subInvList: [],
            loading: false,
            detailLoading: false,
            idQuery: {
                id: "",
            },
            exportStatusMap: {
                null: "未提交",
                "1": "已提交",
                "0": "未提交",
            },
            distributionVisible: false,
            detailFormRules: {
                batchNo: [
                    {required: true, message: "请输入批次号", trigger: "blur"}
                ],
                productDate: [
                    {required: true, message: "请输入生产日期", trigger: "blur"}
                ],
                expireDate: [
                    {required: true, message: "请输入失效日期", trigger: "blur"}
                ],
                sweepCount: [
                    {required: true, message: "请输入扫码数量", trigger: "blur"}
                ]
            },
            sourceMap: {
                "1": "web端新增单据",
                "2": "第三方系统",
                "3": "扫码单据转换",
                "4": "采购计划转换",
            },
            orderStatusList: [
                {
                    label: '未配货',
                    value: '2'
                },
                {
                    label: '待校验',
                    value: '3'
                },
                {
                    label: '已校验',
                    value: '4'
                },
                {
                    label: '已验收',
                    value: '5'
                }
            ],
            submitStatusList: [
                {
                    label: '未提交',
                    value: 0
                },
                {
                    label: '已提交',
                    value: 1
                },
                {
                    label: '提交失败',
                    value: 2
                },
            ],
            detailFormVisible: false,
            detailFormData: {},
            detailFormLoading: false,
            haveDistributionVisible: true,
            actDateRange: [],
            curRow: null,
            pickerOptions: {
                shortcuts: [
                    {
                        text: "最近一周",
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                            picker.$emit("pick", [start, end]);
                        },
                    },
                    {
                        text: "最近一个月",
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                            picker.$emit("pick", [start, end]);
                        },
                    },
                    {
                        text: "最近三个月",
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                            picker.$emit("pick", [start, end]);
                        },
                    },
                ],
            }
        }
    },
    methods: {
        onReset() {
            this.$router.push({
                path: ""
            });
            this.query = {
                billNo: "",
                billType: '',
                corpName: '',
                orderStatus: null,
                submitStatus: null,
                startTime: "",
                endTime: "",
                page: 1,
                limit: 10
            };
            this.getList();
            this.haveDistributionVisible = true;
            this.actDateRange = [];
        },
        onSubmit() {
            if (this.actDateRange !== null) {
                this.query.startTime = this.actDateRange[0];
                this.query.endTime = this.actDateRange[1];
            } else {
                this.query.startTime = null;
                this.query.endTime = null;
            }
            //手动点击查询按钮，每次都从第一页开始查询
            this.query.page = 1;
            this.getList();
            if (this.query.status === "202" || this.query.status === "502") {
                this.haveDistributionVisible = true;
            } else {
                this.haveDistributionVisible = false;
            }
        },
        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.getStockOrderDetailList();
        },
        // 刷新表单
        resetForm() {
            if (this.$refs["dataForm"]) {
                // 清空验证信息表单
                this.$refs["dataForm"].clearValidate();
                // 刷新表单
                this.$refs["dataForm"].resetFields();
                this.getList();
            }
        },
        getList() {
            this.loading = true;
            stockOrderUploadList(this.query).then((res) => {
                this.loading = false;
                if (res.code === 20000) {
                    this.list = res.data.list || [];
                    this.detailList = [];
                    this.total = res.data.total || 0;
                }
            }).catch((error) => {
                this.loading = false;
                this.list = [];
                this.total = 0;
                this.detailList = [];
            })
        },
        closeDialog(type) {
            this.distributionVisible = false;
            this.stockChangeVisible = false;

            this.getList();
            if (this.$isNotBlank(type)) {
                this.detailList = [];
            }
        },
        getStockOrderDetailList(row) {
            if (this.$isNotBlank(row)) {
                this.detailQuery.orderIdFk = row.id;
            }
            this.detailLoading = true;
            stockOrderDetail(this.detailQuery)
                .then((response) => {
                    this.detailLoading = false;
                    this.detailList = response.data.list || [];
                })
                .catch(() => {
                    this.detailLoading = false;
                    this.detailList = [];
                });
        },
        hideDetailForm() {
            // 更改值
            this.detailFormVisible = !this.detailFormVisible;
            return true;
        },
        getActionName(action) {
            for (let i = 0; i < this.busTypes.length; i++) {
                if (this.busTypes[i].localAction === action) {
                    return this.busTypes[i].localName;
                }
            }
        },
        getBusType() {
            let query = {
                enabled: true,
            };
            getLocalJoinByUser(query)
                .then((response) => {
                    this.busTypes = response.data.list || [];
                    this.filterQuery.billAction = this.busTypes[0].action;
                })
                .catch(() => {
                });
        },
        submitUploadDetail() {
            this.$refs["dataForm"].validate(valid => {
                if (valid) {
                    this.detailLoading = true;
                    let tQuery = this.detailFormData;
                    uploadStockOrderDetail(tQuery).then((response) => {
                        this.detailLoading = false;
                        if (response.code === 20000) {
                            this.$message.success("修改完成");
                            this.hideDetailForm();
                            this.getStockOrderDetailList();
                        } else {
                            this.$alert(response.message, '提示', {
                                confirmButtonText: '确定',
                                type: 'warning',
                                closeOnClickModal: true,
                                callback: action => {
                                    this.$refs.inputRef.focus();
                                }
                            });
                        }
                    });
                }
            });
        },
        getStorageName(code) {
            for (let i = 0; i < this.storageList.length; i++) {
                if (this.storageList[i].code === code) {
                    return this.storageList[i].name;
                }
            }
        },
        getSubStorageName(code) {
            for (let i = 0; i < this.subInvList.length; i++) {
                if (this.subInvList[i].code === code) {
                    return this.subInvList[i].name;
                }
            }
        },

        getSubInvList() {
            let query = {};
            filterSubByInv(query)
                .then((response) => {
                    this.subInvList = response.data || [];
                })
                .catch(() => {
                });
        },

        getStorage() {
            this.storageList = [];
            filterAllByUser()
                .then((response) => {
                    this.storageList = response.data || [];
                    if (this.storageList.length > 0) {
                        this.query.locStorageCode = this.storageList[0].code;
                        this.getSubInvList();
                        this.getList();
                    }
                })
                .catch(() => {
                });
        },
        myubmitOrder(row) {
            let params = {id: row.id};
            submitStockOrderToThirdSys(params).then((res) => {
                if (res.code == 20000) {
                    this.$message({
                        type: "success",
                        message: "提交成功！"
                    });
                    this.getList();
                } else {
                    this.$message.error(res.message);
                }
            }).catch((error) => {
                this.$message.error("提交失败");
            });
        },
        submitOrder(row) {
            if (row.exportStatus == 1) {
                this.$confirm("单据已经提交，是否重复提交？", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                    center: true
                }).then(() => {
                    this.myubmitOrder(row);
                }).catch(() => {

                })
            } else {
                this.$confirm("确定手动上传单据？", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                    center: true
                }).then(() => {
                    this.myubmitOrder(row);
                }).catch(() => {

                })

            }
        },

    },


    components: {},
    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.getStorage();
        this.getBusType();
        let end = new Date();
        let start = new Date();
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
        this.actDateRange = [start, end];

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

</style>

