<!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-transfer-edit" th:object="${amsTransferOrder}">
            <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="*{transferNo}" 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">申请人：</label>
                        <div class="col-sm-8">
                            <input th:value="*{applicantName}" class="form-control" type="text" readonly>
                        </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="transferReason" maxlength="500" class="form-control"
                                      rows="3">[[*{transferReason}]]</textarea>
                        </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="removeSelectedAssets()">
                        <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/transfer";
        var orderId = [[${amsTransferOrder.orderId}]];
        var detailList = [[${amsTransferOrder.amsTransferOrderItemList}]];
        var warehouseList = [[${warehouseList}]];
        var locationList = [[${locationList}]];
        var assetStatusDatas = [[${@dict.getType('ams_asset_status')}]];

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

        /* 提交前校验明细不能为空 */
        function submitHandler() {
            if ($("#bootstrap-table").bootstrapTable("getData").length === 0) {
                $.modal.alertWarning("请至少保留一条调拨明细");
                return;
            }
            if ($.validate.form()) {
                $.operate.save(prefix + "/edit", $("#form-transfer-edit").serialize());
            }
        }

        $(function() {
            initDetailTable(detailList);
        });

        function initDetailTable(data) {
            $.table.init({
                data: data,
                pagination: false,
                showSearch: false,
                showRefresh: false,
                showToggle: false,
                showColumns: false,
                sidePagination: "client",
                columns: [{
                    checkbox: true
                },
                {
                    field: "assetId",
                    title: "资产",
                    formatter: function(value, row, index) {
                        return buildAssetCell(row, index);
                    }
                },
                {
                    field: "assetStatus",
                    title: "状态",
                    formatter: function(value) {
                        return $.table.selectDictLabel(assetStatusDatas, value);
                    }
                },
                {
                    field: "oldWarehouseName",
                    title: "当前归属",
                    formatter: function(value, row) {
                        return buildCurrentOwnership(row);
                    }
                },
                {
                    field: "newWarehouseId",
                    title: "新仓库",
                    formatter: function(value, row, index) {
                        return buildWarehouseSelect(value, index);
                    }
                },
                {
                    field: "newLocationId",
                    title: "新位置",
                    formatter: function(value, row, index) {
                        return buildLocationSelect(value, row, index);
                    }
                },
                {
                    field: "remark",
                    title: "明细备注",
                    formatter: function(value, row, index) {
                        return buildInput("amsTransferOrderItemList[" + index + "].remark", value, 500);
                    }
                },
                {
                    title: "操作",
                    align: "center",
                    formatter: function(value, row) {
                        return '<a class="btn btn-danger btn-xs" href="javascript:void(0)" onclick="removeAsset(\''
                            + row.assetId + '\')"><i class="fa fa-remove"></i>删除</a>';
                    }
                }]
            });
        }

        /* 编辑模式传入 orderId，让选择器排除当前调拨单已占用的资产 */
        function selectAssets() {
            $.modal.openOptions({
                title: "选择可调拨资产",
                url: prefix + "/selectAsset?orderId=" + orderId,
                width: "1200",
                height: "680",
                callBack: addSelectedAssets
            });
        }

        /* 弹窗回调：从选择器取回勾选行，去重后追加到明细表 */
        function addSelectedAssets(index, layero) {
            var selectedAssets = layero.find("iframe")[0].contentWindow.getSelectedAssets();
            if (!selectedAssets || selectedAssets.length === 0) {
                $.modal.alertWarning("请至少选择一条资产记录");
                return;
            }
            syncDetailRows();
            var existing = {};
            $.each($("#bootstrap-table").bootstrapTable("getData"), function(i, row) {
                existing[String(row.assetId)] = true;
            });
            $.each(selectedAssets, function(i, asset) {
                if (!existing[String(asset.assetId)]) {
                    $("#bootstrap-table").bootstrapTable("insertRow", {
                        index: $("#bootstrap-table").bootstrapTable("getData").length,
                        row: buildTransferItem(asset)
                    });
                    existing[String(asset.assetId)] = true;
                }
            });
            $.modal.close(index);
        }

        /**
         * 将资产台账字段映射为调拨明细行的初始值。
         * 注意台账字段名（warehouseId）→ 调拨明细「原」前缀字段（oldWarehouseId）。
         */
        function buildTransferItem(asset) {
            return {
                assetId: asset.assetId,
                assetCode: asset.assetCode,
                assetName: asset.assetName,
                categoryName: asset.categoryName,
                assetStatus: asset.assetStatus,
                oldWarehouseId: asset.warehouseId,
                oldWarehouseCode: asset.warehouseCode,
                oldWarehouseName: asset.warehouseName,
                oldLocationId: asset.locationId,
                oldLocationCode: asset.locationCode,
                oldLocationName: asset.locationName,
                newWarehouseId: "",
                newLocationId: "",
                remark: ""
            };
        }

        function removeSelectedAssets() {
            var rows = $("#bootstrap-table").bootstrapTable("getSelections");
            if (rows.length === 0) {
                $.modal.alertWarning("请至少选择一条记录");
                return;
            }
            syncDetailRows();
            $("#bootstrap-table").bootstrapTable("remove", {
                field: "assetId",
                values: $.map(rows, function(row) { return row.assetId; })
            });
        }

        function removeAsset(assetId) {
            syncDetailRows();
            $("#bootstrap-table").bootstrapTable("remove", { field: "assetId", values: [assetId] });
        }

        /* 仓库下拉变更时清空位置并重新渲染级联 */
        function changeWarehouse(index, value) {
            syncDetailRows();
            var row = $("#bootstrap-table").bootstrapTable("getData")[index];
            row.newWarehouseId = value;
            row.newLocationId = "";
            $("#bootstrap-table").bootstrapTable("updateRow", { index: index, row: row });
        }

        /**
         * 关键技巧：在任何行操作前，从 DOM 同步表单元素的用户编辑值
         * 回 bootstrapTable 的数据模型，避免增删行后丢失已填写数据。
         */
        function syncDetailRows() {
            var rows = $("#bootstrap-table").bootstrapTable("getData");
            $.each(rows, function(index, row) {
                var tr = $("#bootstrap-table tbody tr[data-index='" + index + "']");
                row.newWarehouseId = tr.find("[name$='.newWarehouseId']").val() || "";
                row.newLocationId = tr.find("[name$='.newLocationId']").val() || "";
                row.remark = tr.find("[name$='.remark']").val() || "";
            });
        }

        function buildAssetCell(row, index) {
            var hidden = $("<input>").attr({
                type: "hidden",
                name: "amsTransferOrderItemList[" + index + "].assetId",
                value: row.assetId
            }).prop("outerHTML");
            return hidden + $("<span>").text(row.assetCode + " - " + row.assetName).prop("outerHTML");
        }

        function buildCurrentOwnership(row) {
            return $("<span>").text((row.oldWarehouseName || "-") + " / "
                + (row.oldLocationName || "-")).prop("outerHTML");
        }

        function buildWarehouseSelect(value, index) {
            var select = $("<select>").addClass("form-control").attr({
                name: "amsTransferOrderItemList[" + index + "].newWarehouseId",
                required: true,
                onchange: "changeWarehouse(" + index + ", this.value)"
            });
            select.append($("<option>").val("").text("请选择新仓库"));
            $.each(warehouseList, function(i, warehouse) {
                var option = $("<option>").val(warehouse.warehouseId)
                    .text(warehouse.warehouseCode + " - " + warehouse.warehouseName);
                if (String(warehouse.warehouseId) === String(value)) {
                    option.attr("selected", "selected");
                }
                select.append(option);
            });
            return select.prop("outerHTML");
        }

        function buildLocationSelect(value, row, index) {
            var select = $("<select>").addClass("form-control").attr({
                name: "amsTransferOrderItemList[" + index + "].newLocationId",
                required: true
            });
            select.append($("<option>").val("").text("请选择新位置"));
            $.each(locationList, function(i, location) {
                if (String(location.warehouseId) === String(row.newWarehouseId)) {
                    var option = $("<option>").val(location.locationId)
                        .text(location.locationCode + " - " + location.locationName);
                    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>
