<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <th:block th:include="include :: header('出库任务单列表')"/>
    <link th:href="@{/ruoyi/css/ry-ui-custom.css?v=4.7.3}" rel="stylesheet"/>
</head>
<body class="gray-bg">
<div class="container-div">
    <div class="row pl0 pr0">
        <div class="col-sm-8 pr0 pl0">
            <div class="box-shadow">
                <div class="ibox float-e-margins" style="margin-bottom: 10px;">
                    <div class="ibox-title">
                        <h5>身份信息</h5>
                    </div>
                    <div class="ibox-content ibox-content-1" style="margin: 0;height: 45px">
                        <form th:object="${sysUser}">
                            <input type="hidden" id="outStand" th:value="*{outStand}"/>
                            <div class="col-sm-4 form-horizontal">
                                <label class="control-label">当前操作员：</label>
                                <label class="control-label" style="font-weight: bold" id="currentUser"
                                       th:text="*{userName}"></label>
                            </div>
                            <div class="col-sm-3 form-horizontal">
                                <label class="control-label">角色：</label>
                                <label class="control-label" style="font-weight: bold" id="userRoles"
                                       th:text="*{roleNames}"></label>
                            </div>
                            <div class=" form-horizontal">
                                <label class="control-label">上次登录时间：</label>
                                <label class="control-label" style="font-weight: bold" id="lastLoginTime"
                                       th:text="*{loginDateStr}"></label>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
            <div style="margin-top: 10px;" class="box-shadow">
                <div class="ibox float-e-margins">
                    <div class="ibox-title">
                        <h5>出库信息</h5>
                    </div>
                    <div class="ibox-content ibox-content-1">
                        <div class="select-table table-striped">
                            <table id="bootstrap-table"></table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-sm-4 pl5 pr0">
            <div class="ibox float-e-margins box-shadow">
                <div class="ibox-title">
                    <h5>出库操作</h5>
                </div>
                <ul class="nav nav-tabs">
                    <li class="active"><a href="#goodsOutConfirm" class="nav-right-tabs-a" data-toggle="tab">工单出库</a></li>
                </ul>
                <div class="tab-content">
                    <div class="tab-pane active" id="goodsOutConfirm">
                        <form class="m" id="form-goods-out-confirm">
                            <div class="row">
                                <div class="col-sm-6 form-group">
                                    <label class="control-label">物料编码：</label>
                                    <div>
                                        <input type="text" id="goodsId" name="goodsId" placeholder="点击选择物料"
                                               class="form-control input-border-bottom" onclick="openGoodsList()">
                                    </div>
                                </div>
                                <div class="col-sm-6 form-group">
                                    <label class="control-label">待发数量：</label>
                                    <div>
                                        <input type="number" id="waitNum" name="waitNum"
                                               class="form-control input-border-bottom" readonly>
                                    </div>
                                </div>
                            </div>
                            <!--                                 <div class="row">-->
                            <!--                                     <div class="col-sm-6 form-group">-->
                            <!--                                         <label class="control-label">批次号：</label>-->
                            <!--                                         <div>-->
                            <!--                                             <input type="text" id="putinId" name="putinId"  autocomplete="off" placeholder="批次号" class="form-control input-border-bottom" >-->
                            <!--                                         </div>-->
                            <!--                                     </div>-->
                            <!--                                 </div>-->
                            <div class="row">
                                <div class="col-sm-6 form-group">
                                    <label class="control-label">当前待发工单：</label>
                                    <div>
                                        <input type="text" id="orderIdConfirm" name="orderIdConfirm"
                                               class="form-control input-border-bottom" readonly>
                                    </div>
                                </div>
                                <div class="col-sm-6 form-group">
                                    <label class="control-label">当前工单待发数量：</label>
                                    <div>
                                        <input type="number" id="waitNumConfirm" name="waitNumConfirm"
                                               class="form-control input-border-bottom" readonly>
                                    </div>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-sm-6 form-group">
                                    <label class="control-label">扫码校验用：</label>
                                    <div>
                                        <input type="text" id="scanConfirm" name="scanConfirm" class="form-control input-border-bottom">
                                    </div>
                                </div>
                                <div class="col-sm-6 form-group">
                                    <label class="control-label">此次拣货数量：</label>
                                    <div>
                                        <input type="number" id="pickNum" name="pickNum" class="form-control input-border-bottom">
                                    </div>
                                </div>
                            </div>
<!--                            <div class="row">-->
<!--                                <div class="col-sm-6 form-group">-->
<!--                                    <div class="checkbox">-->
<!--                                        <label><input type="checkbox" id="checkRemain" value="1">是否结束发料</label>-->
<!--                                    </div>-->
<!--                                </div>-->
<!--                            </div>-->
                            <div class="row">
                                <div class="col-sm-6 form-group">
                                    <label class="control-label">已拣货数量：</label>
                                    <div>
                                        <input type="number" id="realPickNum" name="realPickNum" class="form-control input-border-bottom" readonly>
                                    </div>
                                </div>
                                <div class="col-sm-6" style="padding-right: 10px;padding-left: 20px;">
                                    <button type="button" class="btn btn-lg btn-ctl-clear" onclick="endGoodsOut();">
                                        <span class="btn-ctl-color">结束本次发料</span></button>
                                </div>
                            </div>
                        </form>
                        <div class="row">
                            <div class="col-sm-6" style="padding-right: 20px;padding-left: 20px;">
                                <button type="button" class="btn btn-lg btn-ctl-print" onclick="goodsOutTaskConfirm();">
                                    <span class="btn-ctl-color">确认出库</span></button>
                            </div>
                            <div class="col-sm-6" style="padding-right: 20px;padding-left: 20px;">
                                <button type="button" class="btn btn-lg btn-ctl-print-red" onclick="backStock()"><span
                                        class="btn-ctl-color">返库</span></button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<th:block th:include="include :: footer"/>
<style>
    .fixed-table-toolbar {
        display: none !important;
    }
</style>
<!--    <script th:src="@{/js/scan.js}"></script>-->
<script th:inline="javascript">
    var prefix = ctx + "business/mesManage";
    var statusDatas = [[${@dict.getType('out_status')}]];
    var realPickNum = 0;

    /**
     * 表格初始化
     */
    $(function () {
        var options = {
            url: prefix + "/orderTaskOut/main",
            modalName: "出库信息",
            showSearch: false,
            showToggle: false,
            showRefresh: false,
            showColumns: false,
            queryParams: queryParams,
            // onClickRow:function(row, $element) {
            //     // 物料编码
            //     $("#goodsId").val(row.goodsId);
            //     return false;
            // },
            // TODO
            columns: [
                {
                    field: 'goodId',
                    title: '物料编码',
                    sortable: true
                },
                {
                    field: 'goodsName',
                    title: '物料描述',
                    sortable: true,
                    formatter: function (value, row, index) {
                        return $.table.tooltip(value);
                    }
                },
                {
                    field: 'produclotid',
                    title: '批次号',
                    sortable: true
                },
                {
                    field: 'productionDate',
                    title: '生产日期',
                    sortable: true
                },
                {
                    field: 'expiryDate',
                    title: '有效日期',
                    sortable: true
                },
                {
                    field: 'mistockNum',
                    title: '数量',
                    sortable: true
                },
                {
                    field: 'pickingNum',
                    title: '出库数量',
                    sortable: true
                },
                {
                    field: 'ctl',
                    title: '托盘号',
                    sortable: true
                },
                {
                    field: 'locId',
                    title: '库位',
                    sortable: true,
                    align: 'center'
                },
                {
                    field: 'outstand',
                    title: '出库站台',
                    sortable: true
                },
                {
                    field: 'outstatus',
                    title: '状态',
                    sortable: true,
                    formatter: function (value, row, index) {
                        return $.table.selectDictLabel(statusDatas, value);
                    }
                },
                {
                    title: '扫描',
                    formatter: function (value, row, index) {
                        var actions = [];
                        if (row.outstatus == "3") {
                            actions.push('<button id="scan" class="btn btn-warning btn-xs" onclick="checkGoodsOut(' + row.goodId + ', \'' + row.produclotid + '\')">校验</button>');
                        } else if (row.outstatus == "4") {
                            actions.push('<a id="scan" class="btn btn-success btn-xs">已校验</a>');
                        } else {
                            actions.push('<a id="scan" class="btn btn-default btn-xs">校验</a>');
                        }
                        return actions.join('');
                    },
                    align: 'center'
                }
            ]
        };
        $.table.init(options);
    });

    function queryParams(params) {
        var search = $.table.queryParams(params);
        search.ckType = "4";
        search.username = "MES";
        search.outStand = $("#outStand").val();
        return search;
    }

    // 出库任务列表，每间隔5秒刷新
    setInterval(function () {
        console.log('刷新出库任务');
        $.table.refresh();
    }, 1000)

    // 校验
    function checkGoodsOut(goodsId, produclotid) {
        console.log("校验开始");
        // 初始化参数
        let codeString = "";
        let scanMode = true;
        let pickingNumConfirm = 0;
        let numBefore = 0;
        console.log("扫码模式：" + scanMode);
        console.log("待校验物料编码：" + goodsId);
        console.log("待校验批次号：" + produclotid);
        $("#scanConfirm").val("");
        $("#scanConfirm").focus();
        $(this).keydown(function (e) {
            if (scanMode) {
                let code = e.which;
                if (code !== 13) {
                    // codeString += String.fromCharCode(code);
                } else if (code === 13) {
                    scanMode = false;
                    codeString = $("#scanConfirm").val();
                    console.log("扫码所得字符串：" + codeString);
                    let scanInfo = codeString.replace(/(\[GS\])|(\[RS\])|(\[EOT\])/g, " ");
                    console.log("扫码所得字符串格式化：" + scanInfo);
                    let goodsInfoConfirm = scanInfo.trim().split(" ");
                    let goodsIdConfirm = goodsInfoConfirm[0];
                    console.log("扫码所得物料编码：" + goodsIdConfirm);
                    let productLotIdConfirm = goodsInfoConfirm[2];
                    console.log("扫码所得批次号：" + productLotIdConfirm);
                    $("#scanConfirm").val("");
                    console.log("扫码所得数量：" + pickingNumConfirm);
                    if (goodsIdConfirm == goodsId && productLotIdConfirm == produclotid) {
                        $.ajax({
                            type: "post",
                            url: prefix + "/orderTaskOut/checkOut",
                            data: {
                                "goodId": goodsId,
                                "pickingNum": $("#pickNum").val(),
                                "outStand": $("#outStand").val(),
                                "putinId": produclotid,
                                "outId": $("#orderIdConfirm").val(),
                            },
                            success: function (res) {
                                console.log(res)
                                if (res.code == 0) {
                                    if (res.data != null) {
                                        var nextOrder = res.data;
                                        $("#orderIdConfirm").val(nextOrder.orderId);
                                        $("#waitNumConfirm").val(nextOrder.waitNum);
                                        // 增加实际拣货数量
                                        realPickNum = realPickNum + $("#pickNum").val()
                                        $("#realPickNum").val(realPickNum);
                                    } else {
                                        $.modal.msgSuccess('该物料已无工单发料任务或者该托盘上已无所需物料，请点击返库按钮返库')
                                    }
                                } else {
                                    $.modal.msgError('错误')
                                }
                            },
                            error: function () {
                                $.modal.msgError('错误')
                            }
                        });
                    } else {
                        $.modal.msgError('物料编码或批次号不对');
                    }
                    console.log("扫码模式：" + scanMode);
                }
            }
        })
    }

    // 结束此次发料
    function endGoodsOut() {
        // 结束本次发料时，更新状态为可回库
        $.ajax({
            type: "post",
            url: prefix + "/orderTaskOut/endGoodsOut",
            data: {
                "outstand": $("#outStand").val()
            },
            success: function (data) {
                console.log(data)
                if (data.code == 0) {
                    if (data.msg == "0") {
                        $.modal.msgError('当前站台无可返库任务')
                    } else if (data.msg == "-1") {
                        $.modal.msgError('更新状态失败')
                    } else {
                        $.modal.msgSuccess("已结束此次发料，请点击返库按钮返库")
                    }
                } else {
                    $.modal.msgError('错误')
                }
            },
            error: function () {
                $.modal.msgError('错误')
            }
        });
    }

    /**
     * 回库
     */
    function backStock() {
        // 返库时需要更新实际拣货数量
        $.ajax({
            type: "post",
            url: ctx + "business/mesManage/backStock",
            data: {
                "pickingNum": realPickNum,
                "outstand": $("#outStand").val()
            },
            success: function (data) {
                console.log(data)
                if (data.code == 0) {
                    if (data.msg == "0") {
                        $.modal.msgError('当前站台无可返库任务')
                    } else {
                        $.modal.msgSuccess('已提交返库请求')
                    }
                } else {
                    $.modal.msgError('错误')
                }
            },
            error: function () {
                $.modal.msgError('错误')
            }
        });
    }

    /**
     * 工单出库（更新任务号和站台号）
     */
    function goodsOutTaskConfirm() {
        if ($("#goodsIdConfirm").val() == null || $("#goodsIdConfirm").val() == "") {
            $.modal.msgWarning('未选择出库任务，默认出第一条');
        }

        $.ajax({
            type: "post",
            url: prefix + "/orderTaskOut/updateTask",
            data: {
                "goodId": $("#goodsId").val(),
                "pickNum": $("#waitNum").val(),
                "outStand": $("#outStand").val(),
                "ckType": "4"
            },
            success: function (data) {
                console.log(data)
                if (data.code == 0) {
                    if (data.msg == "0") {
                        $.modal.msgError('库存不足')
                    } else if (data.msg == "-1") {
                        $.modal.msgError('执行任务失败')
                    } else if (data.msg == "-2") {
                        $.modal.msgError('当前站台有出库任务未完成')
                    } else if (data.msg == "-3"){
                        $.modal.msgError('无可出库工单任务')
                    } else {
                        $.modal.msgSuccess('已提交出库任务请求')
                        $("#goodsId").val("")
                        $("#waitNum").val("")
                    }
                } else {
                    $.modal.msgError('错误')
                }
            },
            error: function () {
                $.modal.msgError('错误')
            }
        });
    }

    function openGoodsList() {
        var options = {
            title: '选择出库任务',
            url: prefix + "/orderTaskOut/pickingTask",
            // width: 800,
            // height: 1000,
            callBack: doSubmit
        };
        $.modal.openOptions(options);
    }

    function doSubmit(index, layero) {
        var rows = layero.find("iframe")[0].contentWindow.getSelections();
        if (rows.length == 0) {
            $.modal.alertWarning("请至少选择一条记录");
            return;
        }
        console.log(rows);
        $('#waitNum').val(rows.pop());
        $('#goodsId').val(rows.pop());
        $.modal.close(index);
    }

    // $("#checkRemain").click(function () {
    //     var isRemain = $("input[id='checkRemain']:checked").val();
    //     if (isRemain) {
    //         $("#remainNum").attr("disabled", false);
    //     } else {
    //         $("#remainNum").attr("disabled", true);
    //     }
    // })
</script>
</body>
</html>