<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <th:block th:include="include :: header('新增借用单')" />
    <th:block th:include="include :: datetimepicker-css" />
    <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-borrow-add">
            <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 is-required">借用部门：</label>
                        <div class="col-sm-8">
                            <select name="borrowDeptId" class="form-control" required onchange="changeBorrowDept(this.value)">
                                <option value="">请选择借用部门</option>
                                <option th:each="dept : ${deptList}" th:value="${dept.deptId}"
                                        th:text="${dept.deptName}"
                                        th:selected="${dept.deptId == defaultBorrowDeptId}"></option>
                            </select>
                        </div>
                    </div>
                </div>
                <div class="col-sm-4">
                    <div class="form-group">
                        <label class="col-sm-4 control-label is-required">借用人：</label>
                        <div class="col-sm-8">
                            <select name="borrowUserId" id="borrowUserId" class="form-control select-user" required></select>
                        </div>
                    </div>
                </div>
                <div class="col-sm-4">
                    <div class="form-group">
                        <label class="col-sm-4 control-label is-required">预计归还：</label>
                        <div class="col-sm-8">
                            <input name="expectedReturnDate" class="form-control time-input" type="text"
                                   placeholder="yyyy-MM-dd" required>
                        </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"></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 :: datetimepicker-js" />
    <th:block th:include="include :: select2-js" />
    <script th:inline="javascript">
        var prefix = ctx + "asset/borrow";
        var userList = [[${userList}]];
        var defaultBorrowUserId = [[${defaultBorrowUserId}]];

        $("#form-borrow-add").validate({ focusCleanup: true });

        $(function() {
            refreshBorrowUsers(defaultBorrowUserId);
            initDetailTable([]);
            if ($.fn.select2) {
                $(".select-user").select2({ width: "100%" });
            }
        });

        function submitHandler() {
            if ($("#bootstrap-table").bootstrapTable("getData").length === 0) {
                $.modal.alertWarning("请至少添加一条借用明细");
                return;
            }
            if ($.validate.form()) {
                syncDetailRows();
                $.operate.save(prefix + "/add", $("#form-borrow-add").serialize());
            }
        }

        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: "categoryName", title: "资产类别" },
                    { field: "beforeWarehouseName", title: "当前仓位", formatter: function(value, row) {
                        return $("<span>").text((row.beforeWarehouseName || "-") + " / " + (row.beforeLocationName || "-")).prop("outerHTML");
                    }},
                    { field: "tagCode", title: "RFID标签", formatter: function(value) { return value || "-"; } },
                    { field: "remark", title: "明细备注", formatter: function(value, row, index) {
                        return buildInput("amsBorrowOrderItemList[" + 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() {
            syncDetailRows();
            $.modal.openOptions({
                title: "选择可借用资产",
                url: prefix + "/selectAsset",
                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: buildBorrowItem(asset)
                    });
                    existing[String(asset.assetId)] = true;
                }
            });
            $.modal.close(index);
        }

        function buildBorrowItem(asset) {
            return {
                assetId: asset.assetId,
                assetCode: asset.assetCode,
                assetName: asset.assetName,
                categoryName: asset.categoryName,
                beforeWarehouseName: asset.warehouseName,
                beforeLocationName: asset.locationName,
                tagCode: asset.tagCode,
                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 syncDetailRows() {
            var rows = $("#bootstrap-table").bootstrapTable("getData");
            $.each(rows, function(index, row) {
                var tr = $("#bootstrap-table tbody tr[data-index='" + index + "']");
                row.remark = tr.find("[name$='.remark']").val() || "";
            });
        }

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

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

        function changeBorrowDept() {
            refreshBorrowUsers("");
        }

        function refreshBorrowUsers(selectedUserId) {
            var deptId = $("[name='borrowDeptId']").val();
            var userSelect = $("#borrowUserId");
            userSelect.empty().append($("<option>").val("").text("请选择借用人"));
            $.each(userList, function(i, user) {
                if (String(user.deptId) === String(deptId)) {
                    var option = $("<option>").val(user.userId).text(user.userName + "（" + user.loginName + "）");
                    if (String(user.userId) === String(selectedUserId)) {
                        option.attr("selected", "selected");
                    }
                    userSelect.append(option);
                }
            });
            userSelect.trigger("change");
        }
    </script>
</body>
</html>
