<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <th:block th:include="include :: header('修改领用申请')" />
    <th:block th:include="include :: select2-css" />
    <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-receive-edit" th:object="${amsReceiveOrder}">
            <input name="orderId" th:field="*{orderId}" type="hidden">
            <h4 class="form-header h4">基本信息</h4>
            <div class="row">
                <div class="col-sm-4">
                    <div class="form-group">
                        <label class="col-sm-4 control-label">领用单号：</label>
                        <div class="col-sm-8"><input th:value="*{receiveNo}" class="form-control" readonly></div>
                    </div>
                </div>
                <div class="col-sm-4">
                    <div class="form-group">
                        <label class="col-sm-4 control-label">申请人：</label>
                        <div class="col-sm-8"><input th:value="*{applicantName}" class="form-control" readonly></div>
                    </div>
                </div>
                <div class="col-sm-4">
                    <div class="form-group">
                        <label class="col-sm-4 control-label">申请部门：</label>
                        <div class="col-sm-8"><input th:value="*{applyDeptName}" class="form-control" 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="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" />
    <th:block th:include="include :: select2-js" />
    <script th:inline="javascript">
        var prefix = ctx + "asset/receive";
        var orderId = [[${amsReceiveOrder.orderId}]];
        var detailData = [[${amsReceiveOrder.amsReceiveOrderItemList}]];
        var deptList = [[${deptList}]];
        var userList = [[${userList}]];
        var defaultReceiveDeptId = [[${defaultReceiveDeptId}]];
        var defaultReceiveUserId = [[${defaultReceiveUserId}]];

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

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

        $(function() {
            initDetailTable(detailData || []);
        });

        function initDetailTable(data) {
            $.table.init({
                data: data,
                pagination: false,
                showSearch: false,
                showRefresh: false,
                showToggle: false,
                showColumns: false,
                sidePagination: "client",
                onPostBody: function() {
                    // 表格数据渲染完成后，将领用人下拉框初始化为 select2 模糊搜索框
                    if ($.fn.select2) {
                        $(".select-user").select2({
                            width: "100%"
                        });
                    }
                },
                columns: [{
                    checkbox: true
                },
                {
                    field: "assetId",
                    title: "资产",
                    formatter: function(value, row, index) {
                        return buildAssetCell(row, index);
                    }
                },
                {
                    field: "beforeWarehouseName",
                    title: "当前仓位",
                    formatter: function(value, row) {
                        return $("<span>").text((row.beforeWarehouseName || "-") + " / "
                            + (row.beforeLocationName || "-")).prop("outerHTML");
                    }
                },
                {
                    field: "receiveDeptId",
                    title: "领用部门",
                    formatter: function(value, row, index) {
                        return buildDeptSelect(value, index);
                    }
                },
                {
                    field: "receiveUserId",
                    title: "领用人",
                    formatter: function(value, row, index) {
                        return buildUserSelect(value, row, index);
                    }
                },
                {
                    field: "remark",
                    title: "明细备注",
                    formatter: function(value, row, index) {
                        return buildInput("amsReceiveOrderItemList[" + 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>';
                    }
                }]
            });
        }

        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: buildReceiveItem(asset)
                    });
                    existing[String(asset.assetId)] = true;
                }
            });
            $.modal.close(index);
        }

        function buildReceiveItem(asset) {
            return {
                assetId: asset.assetId,
                assetCode: asset.assetCode,
                assetName: asset.assetName,
                categoryName: asset.categoryName,
                beforeWarehouseId: asset.warehouseId,
                beforeWarehouseCode: asset.warehouseCode,
                beforeWarehouseName: asset.warehouseName,
                beforeLocationId: asset.locationId,
                beforeLocationCode: asset.locationCode,
                beforeLocationName: asset.locationName,
                receiveDeptId: defaultReceiveDeptId,
                receiveUserId: defaultReceiveUserId,
                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 changeDept(index, value) {
            syncDetailRows();
            var row = $("#bootstrap-table").bootstrapTable("getData")[index];
            row.receiveDeptId = value;
            row.receiveUserId = "";
            $("#bootstrap-table").bootstrapTable("updateRow", { index: index, row: row });
        }

        function syncDetailRows() {
            var rows = $("#bootstrap-table").bootstrapTable("getData");
            $.each(rows, function(index, row) {
                var tr = $("#bootstrap-table tbody tr[data-index='" + index + "']");
                row.receiveDeptId = tr.find("[name$='.receiveDeptId']").val() || "";
                row.receiveUserId = tr.find("[name$='.receiveUserId']").val() || "";
                row.remark = tr.find("[name$='.remark']").val() || "";
            });
        }

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

        function buildDeptSelect(value, index) {
            var select = $("<select>").addClass("form-control").attr({
                name: "amsReceiveOrderItemList[" + index + "].receiveDeptId",
                required: true,
                onchange: "changeDept(" + index + ", this.value)"
            });
            select.append($("<option>").val("").text("请选择领用部门"));
            $.each(deptList, function(i, dept) {
                var option = $("<option>").val(dept.deptId).text(dept.deptName);
                if (String(dept.deptId) === String(value)) {
                    option.attr("selected", "selected");
                }
                select.append(option);
            });
            return select.prop("outerHTML");
        }

        function buildUserSelect(value, row, index) {
            // 加上 select-user 样式类，以便在 onPostBody 回调中初始化为 select2 模糊搜索框
            var select = $("<select>").addClass("form-control select-user").attr({
                name: "amsReceiveOrderItemList[" + index + "].receiveUserId",
                required: true
            });
            select.append($("<option>").val("").text("请选择领用人"));
            $.each(userList, function(i, user) {
                if (String(user.deptId) === String(row.receiveDeptId)) {
                    var option = $("<option>").val(user.userId).text(user.userName + "（" + user.loginName + "）");
                    if (String(user.userId) === 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>
