<template>
    <div>
        <el-card class="el-card">

            <el-form
                :inline="true"
                :model="filterQuery"
                class="query-form"
                size="mini"
                @submit.native.prevent
            >
                <el-row>
                    <el-form-item class="query-form-item" label-width="100px">
                        <el-input
                            id="inputer"
                            v-model="filterQuery.code"
                            placeholder="UDI码"
                            ref='inputRef'
                            style="width: 500px"
                            @keypress.enter.native="enterKey($event)"
                        ></el-input>
                        <el-checkbox v-model="sitcomScan" style="margin-left: 15px">分段扫码</el-checkbox>
                    </el-form-item>
                    <el-form-item class="query-form-item">
                        <el-button-group>
                            <el-button
                                type="primary"
                                icon="el-icon-refresh"
                                @click="onReset"
                            ></el-button>
                            <el-button type="primary" icon="search" @click="search">查询</el-button>
                        </el-button-group>
                    </el-form-item>
                </el-row>

            </el-form>

            <el-table
                v-loading="loading"
                :data="list"
                style="width: 100%"
                @row-click="getOrderDetail"
                highlight-current-row
                @selection-change="handleSelectionChange"
            >
                <el-table-column type="selection" width="55"></el-table-column>
                <el-table-column label="序号" type="index"></el-table-column>
                <el-table-column label="业务类型" prop="action">
                    <template slot-scope="scope">
                        <span>{{ geActionName(scope.row.action) }}</span>
                    </template>
                </el-table-column>
                <el-table-column
                    label="订单号"
                    prop="orderId"
                    show-overflow-tooltip="true"
                ></el-table-column>
                <el-table-column label="来源" prop="fromType"></el-table-column>
                <el-table-column label="往来单位" prop="fromCorp">
                </el-table-column>
                <el-table-column
                    label="创建时间"
                    prop="actDate"
                    width="200"
                    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="上传状态" prop="exportStatus"></el-table-column> -->
                <el-table-column label="操作" fixed="right" width="230">
                    <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-pagination
                :current-page="query.page"
                :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="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="lotno"
                    :show-overflow-tooltip="true"
                ></el-table-column>
                <el-table-column
                    label="生产日期"
                    prop="produceDate"
                    :show-overflow-tooltip="true"
                ></el-table-column>
                <el-table-column
                    label="失效日期"
                    prop="expireDate"
                    :show-overflow-tooltip="true"
                ></el-table-column>
                <el-table-column label="扫码数量" prop="count"></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"
        >
            <codeDetail
                :idQuery="idQuery"
                v-on:closeDetailDialog="closeDetailDialog"
            ></codeDetail>
        </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>
    </div>
</template>

<script>
import {
    filterCode,
    codeList,
    findAllByOrderId,
    updateUnit,
    deleteByOrderId,
    updateExportStatus,
    uploadOrder,
    mergeOrder,
    orderDetail
} from "../../api/warehouse/order";
import {getBusTypeByUser} from "../../api/warehouse/BusRole";
import {getUdiTrace} from "../../api/warehouse/udiTrace";
import {unitListBykey} from "../../api/warehouse/unit";
import draggable from "vuedraggable";
import {saveAs} from "file-saver";
import codeDetail from "./code";

const formJson = {
    site_id: "",
    site_name: "",
    describe: "",
    ads: []
};
export default {
    props: {
        isSelect: {
            type: Boolean,
            default: false
        }
    },

    data() {
        return {
            query: {
                page: 1,
                limit: 20
            },
            codeQuery: {code: null},
            sitcomScan: false,
            checkStatus: {
                error: "校验异常",
                null: "未校验",
                success: "正常"
            },
            //往来单位
            unitquery: {key: "", page: 1, limit: 20},
            unitlist: [],
            list: [],
            detailList: [],
            unitUpdateQuery: {
                id: null,
                fromCorpId: null,
                fromCorp: null,
                orderId: null
            },
            actDateRange: [],
            filterQuery: {
                id: "",
                code: "",
                page: 1,
                limit: 10
            },
            detailQuery: {
                orderId: ""
            },
            deleteData: {
                orderId: ""
            },
            idQuery: {
                id: ""
            },
            curIndex: null,
            curOrderId: null,
            adListNoDataText: "无数据",
            queryAdIdAsyncLoading: false,
            codeDetailVisible: false,
            total: 0,
            loading: false,
            busTypes: [],
            index: null,
            formName: null,
            orderId: "",
            formMap: {
                add: "新增",
                edit: "编辑"
            },
            exportQuery: {
                orderId: "",
                exportStatus: ""
            },

            uploadQuery: {
                orderId: ""
            },

            multipleSelection: [],
            dialogTableVisible: false,
            formLoading: false,
            formVisible: false,
            formData: formJson,
            deleteLoading: false,
            addDialogVisible: false,
            errDialogVisible: false,
            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]);
                        }
                    }
                ]
            }
        };
    },
    components: {
        draggable,
        codeDetail
    },
    methods: {
        onReset() {
            this.$router.push({
                path: ""
            });
            this.filterQuery = {
                page: 1,
                limit: 10,
                code: ""
            };
            this.actDateRange = [];
            this.getList();
        },
        enterKey(event) {
            if (this.sitcomScan) {
                return;
            } else {
                this.$refs.inputRef.select();
                this.onSubmit();
            }
        },
        onSubmit() {
            if (this.actDateRange != null) {
                this.filterQuery.startTime = this.actDateRange[0];
                this.filterQuery.endTime = this.actDateRange[1];
            } else {
                this.filterQuery.startTime = null;
                this.filterQuery.endTime = null;
            }
            this.getList();
        },
        handleSizeChange(val) {
            this.filterQuery.limit = val;
            this.getList();
        },
        handleCurrentChange(val) {
            this.filterQuery.page = val;
            this.getList();
        },
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },

        handleErrorDetail(poistion) {
            var mOrder = this.list[poistion];
            this.errorDetail = mOrder.remark;
            this.errDialogVisible = true;
        },

        mergesOrders() {
            var repeatData = this.multipleSelection;
            if (repeatData.length <= 1) {
                this.$message.warning("选择的订单需大于1");
                return;
            }
            var orderid = repeatData[0].orderId;
            var unit = repeatData[0].fromCorp;
            var action = repeatData[0].action;
            var orderList = [];
            repeatData.forEach((obj, index) => {
                if (unit != obj.fromCorp) {
                    this.$message.warning("往来单位不一致！");
                    return;
                }
                if (action != obj.action) {
                    this.$message.warning("业务类型不一致！");
                    return;
                }
                orderList.push(obj.orderId);
            });
            var tquery = {
                orderList: orderList
            };

            this.$confirm(
                "所选择的订单将会合并到订单号为" + orderid + "的订单下",
                "提示",
                {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                }
            )
                .then(() => {
                    mergeOrder(tquery).then((response) => {
                        if (response.code == 20000) {
                            this.getList();
                            this.$message({
                                type: "success",
                                message: "合并成功"
                            });
                        } else {
                            this.$message.error(response.message);
                        }
                    });
                })
                .catch(() => {
                });
        },
        search() {
            this.filterQuery.page = 1;
            this.getList();
        },
        //获取订单列表
        getList() {
            this.loading = true;
            getUdiTrace(this.filterQuery)
                .then((response) => {
                    this.loading = false;
                    if (response.code != 20000) {
                        this.$message.error(response.message);
                    }
                    this.list = response.data.list || [];
                    this.detailList = [];
                    this.total = response.data.total || 0;

                })
                .catch((error) => {
                    this.loading = false;
                    this.$message.error(error.message);
                    this.list = [];
                    this.detailList = [];
                    this.total = 0;
                });
        },
        //业务明细表
        getOrderDetail(row) {
            this.loading = true;
            this.detailQuery = {
                orderId: row.orderId
            };
            this.refresgOrderDetail();
        },
        repeatCheckClick(row) {
            let tQuery = {
                orderId: row.orderId
            };
            this.loading = true;
            repeatCheck(tQuery)
                .then((response) => {
                    this.loading = false;
                    if (response.code == 20000) {
                        this.$message.success(response.data);
                        this.getList();
                        this.detailQuery = {
                            orderId: row.orderId
                        };
                        this.refresgOrderDetail();
                    } else {
                        this.$message.error(response.message);
                    }
                })
                .catch(() => {
                    this.loading = false;
                    this.getList();
                    this.$message.error(response.message);
                });
        },
        refresgOrderDetail() {
            orderDetail(this.detailQuery)
                .then((response) => {
                    this.loading = false;
                    this.detailList = response.data || [];
                })
                .catch(() => {
                    this.loading = false;
                    this.detailList = [];
                });
        },
        keyup_submit(event) {
            filterCode(this.codeQuery).then((response) => {
                this.loading = false;
                this.list = response.data.list || [];
                this.detailList = [];
                this.total = response.data.total || 0;
            })
                .catch(() => {
                    this.loading = false;
                });
            event.target.select();
        },
        handleUnitClick(row) {
            this.curIndex = row.id;
            this.curOrderId = row.orderId;
            this.dialogTableVisible = true;
        },
        getUnitList() {
            this.loading = true;
            unitListBykey(this.unitquery)
                .then((response) => {
                    this.loading = false;
                    this.unitlist = response.data.list || [];
                })
                .catch(() => {
                    this.loading = false;
                });
        },

        intentDetail(row) {
            // this.$router.push({
            //   path: "../inout/detail",
            //   query: { id: row.id },
            // });

            this.codeDetailVisible = true;
            this.idQuery.id = row.orderId;
        },

        selectUnit(row) {
            this.unitUpdateQuery.id = this.curIndex;
            this.unitUpdateQuery.fromCorp = row.name;
            this.unitUpdateQuery.fromCorpId = row.unitid;
            this.unitUpdateQuery.orderId = this.curOrderId;
            updateUnit(this.unitUpdateQuery)
                .then((response) => {
                    this.dialogTableVisible = false;
                    this.getList();
                })
                .catch(() => {
                    this.dialogTableVisible = false;
                });
        },
        deleteOrders(data) {
            this.loading = true;
            this.deleteData.orderId = data;
            deleteByOrderId(this.deleteData)
                .then((response) => {
                    this.getList();
                    this.refresgOrderDetail();
                    this.$message({
                        type: "success",
                        message: "删除成功！"
                    });
                })
                .catch(() => {
                });
        },
        exportDialog(value) {
            var mOrder = value;
            if (mOrder.exportStatus == "已上传") {
                this.$confirm("该订单已修改, 是否继续?", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                })
                    .then(() => {
                        this.uploadOrderDialog(mOrder);
                    })
                    .catch(() => {
                    });
            } else if (mOrder.contrastStatus == "error") {
                this.$confirm("该订单校验异常, 是否继续?", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                })
                    .then(() => {
                        this.uploadOrderDialog(mOrder);
                    })
                    .catch(() => {
                    });
            } else if (mOrder.contrastStatus == null) {
                this.$confirm("该订单未校验, 是否继续?", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                })
                    .then(() => {
                        this.uploadOrderDialog(mOrder);
                    })
                    .catch(() => {
                    });
            } else {
                this.$confirm("是否确定修改ERP订单?", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                })
                    .then(() => {
                        this.uploadOrderDialog(mOrder);
                    })
                    .catch(() => {
                    });
            }
        },

        exportXml(poistion) {
            this.loading = true;
            var mOrder = this.list[poistion];
            var corpOrderId = mOrder.id;
            var codeArry;
            this.query = {
                corpOrderId: corpOrderId,
                page: 1,
                limit: 20
            };
            findAllByOrderId(this.query) //查找该单号下的所有条码
                .then((response) => {
                    this.loading = false;
                    codeArry = response.data.list || [];
                    var document =
                        "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
                        "<Document xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"终端接口XML Schema-2.0.xsd\" SN=\"\" Version=\"3.0\" License=\"123456\">\n" +
                        "<Events>\n" +
                        "<Event Name=\"" +
                        mOrder.action +
                        "\" MainAction=\"" +
                        mOrder.mainAction +
                        "\">" +
                        "<ActionMaping>\n" +
                        "<Action Name=\"" +
                        mOrder.mainAction +
                        "\">\n" +
                        "<ActionData>Code</ActionData>\n" +
                        "<ActionData>CorpOrderID</ActionData>\n" +
                        "<ActionData>Actor</ActionData>\n" +
                        "<ActionData>ActDate</ActionData>\n" +
                        "<ActionData>ToCorpID</ActionData>\n" +
                        "</Action>\n" +
                        " </ActionMaping>\n" +
                        "<DataMaping>\n" +
                        "<MetaData Name=\"Code\" Type=\"string\" />\n" +
                        "<MetaData Name=\"CorpOrderID\" Type=\"string\" />\n" +
                        "<MetaData Name=\"Actor\" Type=\"string\" />\n" +
                        "<MetaData Name=\"ActDate\" Type=\"Date\" />\n" +
                        "<MetaData Name=\"ToCorpID\" Type=\"string\" />\n" +
                        "</DataMaping>\n" +
                        "<DataField>\n";
                    for (var value of codeArry) {
                        if (value.fromCorpId == null) {
                            value.fromCorpId = "";
                        }
                        var tempdata =
                            " <Data Code=\"" +
                            value.code +
                            "\" CorpOrderID=\"" +
                            value.corpOrderId +
                            "\" Actor=\"" +
                            value.actor +
                            "\" ActDate=\"" +
                            value.actDate +
                            "\" ToCorpID=\"" +
                            value.fromCorpId +
                            "\" />\n";

                        document = document + tempdata;
                    }
                    document =
                        document +
                        "</DataField>\n" +
                        "</Event>\n" +
                        "</Events>\n" +
                        "</Document>\n";

                    var blob = new Blob([document], {
                        type: "text/plain;charset=utf-8"
                    });
                    saveAs(blob, mOrder.action + mOrder.corpOrderId + ".xml");

                    this.exportQuery.orderId = corpOrderId;
                    this.exportQuery.exportStatus = "已上传";
                    updateExportStatus(this.exportQuery).then((response) => {
                        this.getList();
                    });
                })
                .catch(() => {
                    this.loading = false;
                    this.list = [];
                    this.total = 0;
                });
        },

        uploadOrderDialog(value) {
            this.uploadQuery = {
                orderId: value.id
            };
            uploadOrder(this.uploadQuery)
                .then((response) => {
                    if (response.code == 20000) {
                        this.$message.success(response.data);
                        this.getList();
                    } else {
                        this.$message.error(response.message);
                    }
                })
                .catch(() => {
                });
        },

        deleteDialog(rowId) {
            this.$confirm("此操作将永久删除该订单, 是否继续?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            })
                .then(() => {
                    this.deleteOrders(rowId);
                })
                .catch(() => {
                });
        },
        closeDetailDialog(val) {
            this.codeDetailVisible = false;
        },
        closeManuDialog(val) {
            this.addDialogVisible = false;
            if (val) {
                this.$message.success("选入成功");
                this.refresgOrderDetail();
                this.getList();
            } else {
                this.$message.error("选入失败");
            }
        },
        cancelDialog() {
            this.addDialogVisible = false;
        },
        importOrder(row) {
            this.orderId = row.id;
            this.addDialogVisible = true;
        },
        geActionName(action) {
            for (let i = 0; i < this.busTypes.length; i++) {
                if (this.busTypes[i].action === action) {
                    return this.busTypes[i].name;
                }
            }
        },
        getBusTypeByUser() {
            let query = {};
            getBusTypeByUser(query)
                .then((response) => {
                    this.busTypes = response.data.list || [];
                })
                .catch(() => {
                });
        }
    },
    filters: {
        statusFilterType(status) {
            const statusMap = {
                false: "success",
                true: "danger"
            };
            return statusMap[status];
        }
    },
    mounted() {
        document.body.ondrop = function (event) {
            event.preventDefault();
            event.stopPropagation();
        };
        var that = this;
        var inputer = document.getElementById("inputer");
        window.sc = new A.KeyScaner(inputer);//传入要监听的DOM节点
        sc.onInput = function (text) {
            //onInput事件在检测到回车键按下或在连续输入后超过500ms没有继续输入时触发
            if (text.includes("delete")) {
                that.formData.code = "";
                return;
            }
            if (that.sitcomScan) {
                that.filterQuery.code = that.filterQuery.code;
            } else {
                that.filterQuery.code = text;
            }
        };
        inputer.focus();//别忘了给要监听的节点放置焦点，如果是div一类默认不具备焦点的节点需要给它加上“tabindex”属性。不建议传入document、Body等全局节点，可能会影响其它输入控件的流畅性。

    },

    created() {
        this.getBusTypeByUser();
        let query = this.$route.query;
        this.query = Object.assign(this.query, query);
        this.query.limit = parseInt(this.query.limit);
        let end = new Date();
        let start = new Date();
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
        this.actDateRange = [start, end];
    }
};
</script>


<style>
.el-table .warning-row {
    background: #ffb5b5;
}

.el-table .success-row {
    background: #ffffff;
}
</style>
