<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <th:block th:include="include :: header('修改入库单')" />
    <style type="text/css">
        table label.error { position: inherit; }
        select + label.error { z-index: 1; right: 40px; }
    </style>
</head>
<body class="white-bg">
    <div class="wrapper wrapper-content animated fadeInRight ibox-content">
        <form class="form-horizontal m" id="form-inbound-edit" th:object="${amsInboundOrder}">
            <input name="orderId" th:field="*{orderId}" type="hidden">
            <h4 class="form-header h4">基本信息</h4>
            <div class="row">
                <div class="col-sm-6">
                    <div class="form-group">
                        <label class="col-sm-4 control-label">入库单号：</label>
                        <div class="col-sm-8">
                            <input th:value="*{inboundNo}" class="form-control" type="text" readonly>
                        </div>
                    </div>
                </div>
                <div class="col-sm-6">
                    <div class="form-group">
                        <label class="col-sm-4 control-label is-required">入库仓库：</label>
                        <div class="col-sm-8">
                            <select id="warehouseId" name="warehouseId" class="form-control" required>
                                <option value="">请选择入库仓库</option>
                                <option th:each="warehouse : ${warehouseList}"
                                        th:value="${warehouse.warehouseId}"
                                        th:text="${warehouse.warehouseCode + ' - ' + warehouse.warehouseName}"
                                        th:selected="${warehouse.warehouseId == amsInboundOrder.warehouseId}"></option>
                            </select>
                        </div>
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col-sm-12">
                    <div class="form-group">
                        <label class="col-sm-2 control-label">备注：</label>
                        <div class="col-sm-10">
                            <textarea name="remark" maxlength="500" class="form-control" rows="3">[[*{remark}]]</textarea>
                        </div>
                    </div>
                </div>
            </div>

            <h4 class="form-header h4">入库明细</h4>
            <div class="row">
                <div class="col-sm-12">
                    <button type="button" class="btn btn-white btn-sm" onclick="selectAssets()">
                        <i class="fa fa-plus"> 选择资产</i>
                    </button>
                    <button type="button" class="btn btn-white btn-sm" onclick="sub.delRow()">
                        <i class="fa fa-minus"> 删除</i>
                    </button>
                    <div class="col-sm-12 select-table table-striped">
                        <table id="bootstrap-table"></table>
                    </div>
                </div>
            </div>
        </form>
    </div>
    <th:block th:include="include :: footer" />
    <script th:inline="javascript">
        var prefix = ctx + "asset/inbound";
        var locationList = [[${locationList}]];
        var detailList = [[${amsInboundOrder.amsInboundOrderItemList}]];
        // 编辑场景需传入orderId，使待入库资产选择器排除当前单据自身占用的资产
        var orderId = [[${amsInboundOrder.orderId}]];

        $("#form-inbound-edit").validate({
            focusCleanup: true
        });

        function submitHandler() {
            if ($("#bootstrap-table").bootstrapTable('getData').length === 0) {
                $.modal.alertWarning("请至少保留一条入库明细");
                return;
            }
            if ($.validate.form()) {
                $.operate.save(prefix + "/edit", $('#form-inbound-edit').serialize());
            }
        }

        $(function() {
            initDetailTable(detailList);
            $("#warehouseId").change(function() {
                if ($("#bootstrap-table").bootstrapTable('getData').length > 0) {
                    $("#bootstrap-table").bootstrapTable('removeAll');
                    $.modal.alertWarning("入库仓库已变更，请重新添加入库明细");
                }
            });
        });

        function initDetailTable(data) {
            $.each(data, function(index, row) {
                row.index = $.table.serialNumber(index);
            });
            var options = {
                data: data,
                pagination: false,
                showSearch: false,
                showRefresh: false,
                showToggle: false,
                showColumns: false,
                sidePagination: "client",
                columns: [{
                    checkbox: true
                },
                {
                    field: 'index',
                    align: 'center',
                    title: "序号",
                    formatter: function(value, row, index) {
                        return $.table.serialNumber(index);
                    }
                },
                {
                    field: 'assetId',
                    title: '资产',
                    formatter: function(value, row, index) {
                        return buildAssetCell(row, index);
                    }
                },
                {
                    field: 'categoryName',
                    title: '资产类别'
                },
                {
                    field: 'locationId',
                    title: '入库位置',
                    formatter: function(value, row, index) {
                        return buildLocationSelect(value, index);
                    }
                },
                {
                    field: 'inboundQuantity',
                    align: 'center',
                    title: '数量',
                    formatter: function(value, row, index) {
                        return '<input class="form-control" type="text" readonly name="amsInboundOrderItemList['
                            + index + '].inboundQuantity" value="1">';
                    }
                },
                {
                    field: 'remark',
                    title: '明细备注',
                    formatter: function(value, row, index) {
                        return buildInput("amsInboundOrderItemList[" + index + "].remark", value, 500);
                    }
                },
                {
                    title: '操作',
                    align: 'center',
                    formatter: function(value, row, index) {
                        var rowIndex = $.common.isNotEmpty(row.index) ? row.index : $.table.serialNumber(index);
                        return '<a class="btn btn-danger btn-xs" href="javascript:void(0)" onclick="sub.delRowByIndex(\''
                            + rowIndex + '\')"><i class="fa fa-remove"></i>删除</a>';
                    }
                }]
            };
            $.table.init(options);
        }

        /** 打开待入库资产弹窗选择器，编辑场景携带orderId排除自身占用 */
        function selectAssets() {
            if ($.common.isEmpty($("#warehouseId").val())) {
                $.modal.alertWarning("请先选择入库仓库");
                return;
            }
            $.modal.openOptions({
                title: "选择待入库资产",
                url: prefix + "/selectAsset?orderId=" + orderId,
                width: "1100",
                height: "650",
                callBack: addSelectedAssets
            });
        }

        /** 弹窗回调：将选中的资产行写入明细表，已存在的资产自动跳过去重 */
        function addSelectedAssets(index, layero) {
            var selectedAssets = layero.find("iframe")[0].contentWindow.getSelectedAssets();
            if (!selectedAssets || selectedAssets.length === 0) {
                $.modal.alertWarning("请至少选择一条资产记录");
                return;
            }
            var existing = {};
            $.each($("#bootstrap-table").bootstrapTable('getData'), function(i, asset) {
                existing[String(asset.assetId)] = true;
            });
            $.each(selectedAssets, function(i, asset) {
                if (!existing[String(asset.assetId)]) {
                    asset.index = nextDetailIndex();
                    asset.locationId = "";
                    asset.inboundQuantity = 1;
                    asset.remark = "";
                    sub.addRow(asset);
                    existing[String(asset.assetId)] = true;
                }
            });
            $.modal.close(index);
        }

        /** 计算下一条明细的序号，基于当前最大序号递增以保持表单name连续 */
        function nextDetailIndex() {
            var nextIndex = 1;
            $.each($("#bootstrap-table").bootstrapTable('getData'), function(i, row) {
                var currentIndex = parseInt(row.index, 10);
                if (!isNaN(currentIndex) && currentIndex >= nextIndex) {
                    nextIndex = currentIndex + 1;
                }
            });
            return nextIndex;
        }

        /** 资产列渲染：生成隐藏字段（提交assetId）+ 可读标签（展示编码-名称） */
        function buildAssetCell(row, index) {
            var hidden = $("<input>").attr({
                type: "hidden",
                name: "amsInboundOrderItemList[" + index + "].assetId",
                value: row.assetId
            }).prop("outerHTML");
            var label = $("<span>").text(row.assetCode + " - " + row.assetName).prop("outerHTML");
            return hidden + label;
        }

        function buildLocationSelect(value, index) {
            var warehouseId = $("#warehouseId").val();
            var select = $("<select>").addClass("form-control").attr({
                name: "amsInboundOrderItemList[" + index + "].locationId",
                required: true
            });
            select.append($("<option>").val("").text("请选择入库位置"));
            $.each(locationList, function(i, location) {
                if (String(location.warehouseId) === String(warehouseId)) {
                    var label = location.locationCode + " - " + location.locationName;
                    var option = $("<option>").val(location.locationId).text(label);
                    if (String(location.locationId) === String(value)) {
                        option.attr("selected", "selected");
                    }
                    select.append(option);
                }
            });
            return select.prop("outerHTML");
        }

        function buildInput(name, value, maxLength) {
            return $("<input>").addClass("form-control").attr({
                type: "text",
                name: name,
                maxlength: maxLength
            }).val(value || "").prop("outerHTML");
        }
    </script>
</body>
</html>
