<!DOCTYPE HTML>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<meta charset="utf-8">
<head>
    <th:block th:include="include :: header"/>
    <th:block th:include="include :: select2-css"/>
    <script src="/wms/js/jquery.min.js"></script>
</head>
<body class="white-bg">
<div class="wrapper wrapper-content animated fadeInRight ibox-content">
    <form class="form-horizontal m" id="form-semiReceipt-semiReceipt">
        <div class="form-group">
            <label class="col-sm-2 control-label">单据类型:</label>
            <div class="col-sm-2">
                <select id="receiptType" name="receiptType" class="form-control"
                        th:with="receiptTypeList=${@receiptTypeService.getType()}">
                    <option th:selected="${receiptType['code']} == 'SEMI'" th:each="receiptType : ${receiptTypeList}" th:text="${receiptType['name']}"
                            th:value="${receiptType['code']}"></option>
                </select>
            </div>
            <label class="col-sm-2 control-label">工单号:</label>
            <div class="col-sm-4">
                <div class="input-group">
                    <input class="form-control" type="text" placeholder="请扫描工单号" value="" id="orderCode"/>
                    <span class="input-group-btn">
                        <button type="button" onclick="chooseOrder()" id="chooseOrderBtn"
                                class="btn btn-primary">选取工单
                        </button>
                    </span>
                </div>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-2 control-label">生产令号:</label>
            <div class="col-sm-2">
                <input class="form-control" type="text" readonly placeholder="请扫描生产令号" value="" id="orderNumber"/>
            </div>
            <label class="col-sm-2 control-label">生产批号:</label>
            <div class="col-sm-2">
                <input class="form-control" type="text" readonly placeholder="请扫描生产批号" value="" id="batchNumber"/>
            </div>
        </div>
        <div class="col-sm-12 select-info">
            <ul id="myTab" class="nav nav-tabs">
                <li id="l1" class="active"><a href="#tab1" data-toggle="tab">序号追溯入库</a></li>
                <li id="l2"><a href="#tab1" data-toggle="tab">批次追溯入库</a></li>
            </ul>
            <div id="myTabContent" class="tab-content">
                <div class="tab-pane fade in active" id="tab1">
                    <div class="form-group" style="margin-top: 10px">
                        <label class="col-sm-2 control-label">盛具编码:</label>
                        <div class="col-sm-2" style="padding-left: 0">
                            <input class="form-control" type="text" placeholder="请扫描盛具编码" value="" id="vehicleCode"/>
                        </div>
                        <label class="col-sm-2 control-label">追溯码:</label>
                        <div class="col-sm-6">
                            <input class="form-control" id="tracingNo" name="tracingNo" type="text" placeholder="请扫描物料追溯码">
                        </div>
                    </div>
                    <div class="form-group" style="margin-top: 10px">
                        <div class="col-sm-4" id="qtyDiv" style="visibility: hidden">
                            <label class="col-sm-6 control-label">数量:</label>
                            <div class="col-sm-6 input-group" style="float: inline-start;">
                                <input class="form-control" min="0" placeholder="请输入数量" id="qty">
                                <span class="input-group-btn">
                                    <button class="btn btn-default" type="button" onclick="qtySure()" id="qtySureButton">确定</button>
                                </span>
                            </div>
                        </div>
                        <div class="col-sm-6" style="display: flex; justify-content: flex-end">
                            <span style="line-height: 34px" id="scanCount"></span>
                        </div>
                        <div class="col-sm-2" style="display: flex; justify-content: flex-end">
                            <a class="btn btn-primary" onclick="semiReceipt()" type="button">提交</a>&nbsp;&nbsp;
                            <a class="btn btn-danger" onclick="$.modal.close()" type="button">关闭</a>
                        </div>
                    </div>
                </div>
                <table id="bootstrap-table" data-mobile-responsive="true"
                       class="table table-bordered table-hover text-nowrap">
                </table>
            </div>
        </div>
    </form>
</div>
<th:block th:include="include :: footer"/>
<!--<th:block th:include="include :: select2-js"/>-->
<script>
    let vehicleData = null;  // 当前扫描的盛具
    let material = null; // 扫描的物料

    let currentX = 1;
    let currentY = 1;
    let tableDataList = [];

    $(function () {
        // 追溯码入库列表初始化
        $("#bootstrap-table").bootstrapTable({
            showToggle: false,
            showRefresh: false,
            showColumns: false,
            showSearch: false,
            columns: [
                {
                    field: 'vehicleCode',
                    title: '盛具编码'
                },
                {
                    field: 'materialCode',
                    title: '物料编码'
                },
                {
                    field: 'materialName',
                    title: '物料名称'
                },
                {
                    field: 'materialSpec',
                    title: '物料规格'
                },
                {
                    field: 'flowCode',
                    title: '工序号'
                },
                {
                    field: 'materialUnit',
                    title: '物料单位'
                },
                {
                    field: 'description',
                    title: '物料描述'
                },
                {
                    field: 'weight',
                    title: '药量(g)'
                },
                {
                    field: 'high',
                    title: '高度(cm)'
                },
                {
                    field: 'x',
                    title: 'x坐标'
                },
                {
                    field: 'y',
                    title: 'y坐标'
                },
                {
                    field: 'scTracingNo',
                    title: '生产追溯码'
                },
                {
                    field: 'bqTracingNo',
                    title: '标签追溯码'
                },
                {
                    field: 'supplierCode',
                    title: '供应商编码'
                },
                {
                    field: 'supplierBatch',
                    title: '供应商批次码'
                },
                {
                    field: 'supplierTracingNo',
                    title: '供应商SN码'
                },
                {
                    title: '操作',
                    align: 'center',
                    formatter: function (value, row, index) {
                        if (index !== 0) {
                            return
                        }
                        // JSON.stringify()将对象转化成JSON字符串;.replace(/""/g,"’")将JSON字符串中的双引号转化成单引号
                        let rowStr = JSON.stringify(row)
                        let actions = [];
                        actions.unshift(`<a class='btn btn-danger btn-xs' href='#' onclick='remove(${rowStr})'><i class='fa fa-trash-o'></i>删除</a>`);
                        return actions.join('');
                    }
                }]
        });

        // 工单号绑定事件
        $('#orderCode').on('input', debounce(function () {
            let orderCode = this.value;
            if ($.common.isEmpty(orderCode)) {
                return;
            }
            $.ajax({
                cache: true,
                type: "get",
                dataType: "json",
                url: "/wms/workOrder/getOrderByCode",
                async: false,
                data: {
                    orderCode: orderCode
                },
                contentType: "application/json",
                success: function (result) {
                    if (result.code === web_status.SUCCESS) {
                        if (result) {
                            $("#orderCode").val(result.orderCode);
                            $("#orderNumber").val(result.orderNumber);
                            $("#batchNumber").val(result.batchNumber);
                        }
                        $("#vehicleCode").focus();
                    } else {
                        $("#orderCode").val("").focus();
                        $("#orderNumber").val("");
                        $("#batchNumber").val("");
                        $.modal.msgWarning(result.msg);
                    }
                }
            });
        }, 1000));

        // 追溯码输入框输入事件
        $('#tracingNo').on('input', debounce(function () {
            let value = this.value;
            if ($.common.isEmpty(value)) {
                return;
            }
            if (value.substring(0, 2) !== "ZS") {
                $.modal.msgWarning("入库条码规则错误,不为ZS开头");
                clearTracingNo();
                return;
            }
            handleZS(value);
            loadTable();
        }, 600));

        // 盛具编码绑定输入事件
        $('#vehicleCode').on('input', debounce(function () {
            let vehicleCode = this.value;
            if ($.common.isEmpty(vehicleCode) || (vehicleData != null && vehicleCode === vehicleData.code)) {
                return
            }
            if (vehicleCode.substring(0, 7) === "CJ10000") {
                if ($.common.isEmpty(vehicleCode)) {
                    $.modal.msgWarning("通用盛具不可采用此方式入库");
                    return
                }
            }
            $.ajax({
                cache: true,
                type: "get",
                dataType: "json",
                url: "/wms/config/vehicle/getVehicleData",
                async: false,
                data: {
                    vehicleCode: vehicleCode,
                },
                contentType: "application/json",
                success: function (result) {
                    if (result.code === web_status.SUCCESS) {
                        vehicleData = result.data;
                        $("#tracingNo").focus();
                        material = null;
                        loadTable();
                        clearTracingNoAndFocus();
                    } else {
                        $.modal.msgWarning(result.msg);
                        clearTracingNo();
                    }
                    resetXY();
                    //resetQtySure();
                    $("#qty").val();
                }
            });
        }, 600))

        // 切换标签之后触发
        $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
            let id = $('#myTab li[class="active"]').attr("id")
            $("#vehicleCode").focus();
            if (id === "l2") {
                $("#qtyDiv").css("visibility", "visible")
            } else {
                $("#qtyDiv").css("visibility", "hidden")
            }
        })
    });

    function handleZS(value) {
        // 请求MES获取物料信息
        $.ajax({
            cache: true,
            type: "GET",
            url: "/wms/API/WMS/v2/getMesTracingCode",
            async: false,
            data: {zs: value},
            contentType: "application/json",
            error: function (res) {
                $.modal.msgError(res);
            },
            success: function (result) {
                if (result.code === web_status.SUCCESS) {
                    let tracingCode = result.data;
                    $("#tracingNo").val(tracingCode);
                    let splitArray = tracingCode.split("|");
                    let scTracingNo = splitArray[0];
                    let materialCode = splitArray[1];
                    let qty = parseInt(splitArray[2]);
                    let supplierCode = splitArray[3];
                    let supplierBatch = splitArray[4];
                    let supplierTracingNo = splitArray[5];
                    let flowCode = splitArray[6];
                    if (!checkMaterial(materialCode)) {
                        return
                    }
                    getMaterialInfo(materialCode);
                    let id = $('#myTab li[class="active"]').attr("id")
                    if (id === "l1") {
                        addSerial(null, scTracingNo, supplierCode, supplierBatch, supplierTracingNo, flowCode);
                        clearTracingNoAndFocus();
                    }
                    if (id === "l2") {
                        if (qty === 1) {
                            addSerial(null, scTracingNo, supplierCode, supplierBatch, supplierTracingNo, flowCode);
                            clearTracingNoAndFocus();
                        } else if (qty > 1) {
                            $("#qty").focus();
                        } else {
                            $.modal.msgWarning("数量错误");
                        }
                    }
                } else {
                    $.modal.msgWarning(result.msg);
                }
            }
        });
    }

    // 添加序号
    function addSerial(bqTracingNo, scTracingNo, supplierCode, supplierBatch, supplierTracingNo, flowCode) {
        let sameTracingNoData = null;
        if (bqTracingNo !== null && $.common.isNotEmpty(bqTracingNo)) {
            sameTracingNoData = tableDataList.find(data => data.bqTracingNo === bqTracingNo)
        }
        if (scTracingNo !== null && $.common.isNotEmpty(scTracingNo)) {
            sameTracingNoData = tableDataList.find(data => data.scTracingNo === scTracingNo)
        }
        if (sameTracingNoData !== null && sameTracingNoData !== undefined) {
            $.modal.msgWarning("追溯码已经扫描过,在坐标" + sameTracingNoData.x + "," + sameTracingNoData.y + "上")
            clearTracingNo();
            return;
        }
        let obj = {
            vehicleCode: vehicleData.code,
            materialCode: material.code,
            materialName: material.name,
            materialSpec: material.spec,
            materialUnit: material.unit,
            description: material.description,
            weight: material.weight,
            high: material.high,
            qty: 1,
            x: currentX,
            y: currentY,
            flowCode: flowCode,
            bqTracingNo: bqTracingNo,
            scTracingNo: scTracingNo,
            supplierCode: supplierCode,
            supplierTracingNo: supplierTracingNo,
            supplierBatch: supplierBatch
        }
        if (currentX > vehicleData.maxY || currentY > vehicleData.maxX) {
            $.modal.msgWarning("当前盛具已放满");
            return;
        }
        tableDataList.unshift(obj);
        if (currentX === vehicleData.maxY) {
            currentX = 1;
            currentY++;
        } else {
            currentX++;
        }
    }

    // 添加批次
    function addBatch(bqTracingNo, scTracingNo, qty, supplierCode, supplierBatch, supplierTracingNo, flowCode) {
        // 校验数量
        if ($.common.isEmpty(qty)) {
            return;
        }
        if (qty <= 0) {
            $.modal.msgWarning("入库数量有误");
            return;
        }
        clearTableData()
        resetXY();
        clearTracingNo()
        clearVehicleCodeAndFocus();
        if (qty > vehicleData.maxX * vehicleData.maxY) {
            $.modal.msgWarning(`盛具最大可盛放 ${vehicleData.maxX * vehicleData.maxY} 个物料`);
            return
        }
        for (let i = 0; i < qty; i++) {
            let obj = {
                vehicleCode: vehicleData.code,
                materialCode: material.code,
                materialName: material.name,
                materialSpec: material.spec,
                materialUnit: material.unit,
                weight: material.weight,
                high: material.high,
                qty: 1,
                x: currentX++,
                y: currentY,
                bqTracingNo: bqTracingNo,
                scTracingNo: scTracingNo,
                flowCode: flowCode,
                supplierCode: supplierCode,
                supplierBatch: supplierBatch,
                supplierTracingNo: supplierTracingNo
            }
            tableDataList.unshift(obj);
            if (currentX > vehicleData.maxY) {
                currentX = 1;
                currentY++;
            }
        }
    }

    // 提交方法
    function semiReceipt() {
        let orderCode = $("#orderCode").val();
        let orderNumber = $("#orderNumber").val();
        let batchNumber = $("#batchNumber").val();
        let materialDataList = []
        // let vehicleCode = $("#vehicleCode").val()
        /*if ($.common.isEmpty(vehicleCode)) {
            $.modal.msgWarning("请扫描盛具编码");
            return;
        }*/
        if ($.common.isEmpty(orderCode)) {
            $.modal.msgWarning("请选择或输入工单号");
            return;
        }
        if ($.common.isEmpty(orderNumber)) {
            $.modal.msgWarning("请选择或输入生产令号");
            return;
        }
        if ($.common.isEmpty(batchNumber)) {
            $.modal.msgWarning("请选择或输入生产批号");
            return;
        }
        if (tableDataList === null || tableDataList.length === 0) {
            $.modal.msgWarning("入库物料为空");
            return;
        }
        tableDataList.forEach(data => {
            materialDataList.unshift({
                "vehicleCode": data.vehicleCode,
                "materialCode": data.materialCode,
                "locationNoX": data.x,
                "locationNoY": data.y,
                "qty": data.qty,
                "tracingNo": data.bqTracingNo || data.scTracingNo,
                "qualityStatus": true,
                "supplierCode": data.supplierCode,
                "supplierBatch": data.supplierBatch,
                "supplierTracingNo": data.supplierTracingNo,
                "flowCode": data.flowCode
            })
        });
        let timestamp = Date.now();
        let json = {
            "taskNo": timestamp,
            "orderCode": orderCode,
            "orderNumber": orderNumber,
            "batchNumber": batchNumber,
            // "vehicleCode": vehicleCode,
            "materialDataList": materialDataList
        }
        $.ajax({
            cache: true,
            type: "POST",
            dataType: "json",
            url: "/wms/API/WMS/v2/wmsReceipt",
            async: false,
            data: JSON.stringify(json),
            contentType: "application/json",
            success: function (result) {
                if (result.code === web_status.SUCCESS) {
                    layer.msg("保存成功,正在刷新数据请稍后……", {
                            icon: $.modal.icon(modal_status.SUCCESS),
                            time: 500,
                            shade: [0.1, '#8F8F8F']
                        }
                    )
                    // $.modal.msgReload("保存成功,正在刷新数据请稍后……", modal_status.SUCCESS);
                    // 请求成功,不关闭页面。清空页面所有数据方便再次组盘
                    vehicleData = null;
                    tableDataList = [];
                    loadTable();
                    resetXY();
                    clearVehicleCodeAndFocus();
                } else {
                    $.modal.alertError(result.msg);
                }
            }
        });
    }

    // 选取工单按钮点击事件
    function chooseOrder() {
        $.modal.open("选取工单", ctx + "workOrder/getUsableOrder", 800, 570)
    }

    // 清空追溯码文本框
    function clearTracingNo() {
        $("#tracingNo").val("");
    }

    function clearTracingNoAndFocus() {
        $("#tracingNo").val("").focus();
    }

    function clearVehicleCodeAndFocus() {
        $("#vehicleCode").val("").focus();
    }

    // 删除生成的记录
    function remove(row) {
        tableDataList = tableDataList.filter(data => data.x !== row.x || data.y !== row.y);
        currentX = row.x;
        currentY = row.y;
        loadTable();
    }

    // 重新加载表格
    function loadTable() {
        tableDataList.sort((a, b) => {
            if (a.vehicleCode === b.vehicleCode) {
                return -(a.y - b.y) || -(a.x - b.x)
            }
            return a.vehicleCode - b.vehicleCode
        })
        $("#bootstrap-table").bootstrapTable('load', tableDataList);
        if (tableDataList.length !== 0) {
            const res = new Map()
            let vehicleCount = tableDataList.filter((item) => !res.has(item.vehicleCode) && res.set(item.vehicleCode, 1)).length
            let currentQty = tableDataList.filter(x => x.vehicleCode === vehicleData.code).length;
            $("#scanCount").text(`盛具数量:${vehicleCount},扫码总数量:${tableDataList.length},当前扫码数量:${currentQty}`).show()
        } else {
            $("#scanCount").hide();
        }
    }

    // 清除表格信息
    function clearTableData() {
        tableDataList = tableDataList.filter(data => data.vehicleCode !== vehicleData.code)
        loadTable();
    }

    /**
     * 重置坐标
     */
    function resetXY() {
        currentY = 1;
        currentX = 1;
    }

    /**
     * 根据物料编码搜索物料信息
     */
    function getMaterialInfo(materialCode) {
        $.ajax({
            cache: true,
            type: "get",
            dataType: "json",
            url: "/wms/config/material/getByCode",
            async: false,
            data: {
                materialCode: materialCode
            },
            contentType: "application/json",
            error: function (res) {
                $.modal.msgError(res.msg);
            },
            success: function (res) {
                if (res.code === web_status.SUCCESS) {
                    material = res.data;
                } else {
                    $.modal.msgWarning(res.msg);
                    clearTracingNo();
                }
            }
        });
    }

    // 数量确认按钮点击事件
    function qtySure() {
        let qty = $("#qty").val();
        if ($.common.isEmpty(qty)) {
            return;
        }
        if (qty <= 0) {
            $.modal.msgWarning("输入数量有误");
            return
        }
        if ($.common.isEmpty(vehicleData)) {
            $.modal.msgWarning("请先扫码盛具编码");
            $("#vehicleCode").focus();
            return
        }
        let value = $("#tracingNo").val();

        let splitArray = value.split("|");
        let scTracingNo = splitArray[0];
        let supplierCode = splitArray[3];
        let supplierBatch = splitArray[4];
        let supplierTracingNo = splitArray[5];
        let flowCode = splitArray[6];
        addBatch(null, scTracingNo, qty, supplierCode, supplierBatch, supplierTracingNo, flowCode)
        loadTable();
    }

    /**
     * 回传事件
     */
    $("#qty").keyup(function (event) {
        if (event.keyCode === 13) {
            $("#qtySureButton").trigger("click");
        }
    })

    function checkMaterial(materialCode) {
        if ($.common.isNotEmpty(tableDataList)) {
            let sameMaterial = tableDataList.find(x => x.materialCode === materialCode);
            if ($.common.isEmpty(sameMaterial)) {
                $.modal.msgWarning("物料不一致错误,盛具上的物料必须一致才能入库");
                clearTracingNo();
                return false;
            }
        }
        return true
    }

    /**
     * 防抖
     * @param fn 业务方法
     * @param delay 延迟时间
     * @returns {(function(): void)|*}
     */
    function debounce(fn, delay) {
        let timeout = null;
        return function () {
            if (timeout !== null) {
                clearTimeout(timeout);
            }
            timeout = setTimeout(() => {
                //利用call(),让this的指针从指向window 转成指向input
                fn.call(this);
            }, delay);
        }
    }
</script>
</body>
</html>