<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
    <th:block th:include="include :: header('借用单详情')" />
</head>
<body>
    <div class="main-content">
        <form class="form-horizontal" th:object="${amsBorrowOrder}">
            <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"><p class="form-control-plaintext" th:text="*{borrowNo}"></p></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"><p class="form-control-plaintext" th:text="*{borrowUserName}"></p></div>
                    </div>
                </div>
            </div>
            <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"><p class="form-control-plaintext" th:text="*{borrowDeptName}"></p></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">
                            <p class="form-control-plaintext" th:text="*{expectedReturnDate == null ? '' : #dates.format(expectedReturnDate, 'yyyy-MM-dd')}"></p>
                        </div>
                    </div>
                </div>
            </div>
            <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"><p class="form-control-plaintext" th:text="*{@dict.getLabel('ams_borrow_status', orderStatus)}"></p></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"><p class="form-control-plaintext" th:text="*{confirmUserName}"></p></div>
                    </div>
                </div>
            </div>
            <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">
                            <p class="form-control-plaintext" th:text="*{confirmTime == null ? '' : #dates.format(confirmTime, 'yyyy-MM-dd HH:mm:ss')}"></p>
                        </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"><p class="form-control-plaintext" th:text="*{rejectReason}"></p></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"><p class="form-control-plaintext" th:text="*{remark}"></p></div>
                    </div>
                </div>
            </div>
            <h4 class="form-header h4">借用明细</h4>
            <div class="row">
                <div class="col-sm-12 select-table table-striped">
                    <table class="table table-bordered">
                        <thead>
                            <tr>
                                <th>序号</th>
                                <th>资产</th>
                                <th>资产类别</th>
                                <th>借用前仓位</th>
                                <th>归还仓位</th>
                                <th>归还状态</th>
                                <th>实际归还</th>
                                <th>备注</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr th:each="item, stat : *{amsBorrowOrderItemList}">
                                <td th:text="${stat.count}"></td>
                                <td th:text="${item.assetCode + ' - ' + item.assetName}"></td>
                                <td th:text="${item.categoryName}"></td>
                                <td th:text="${(item.beforeWarehouseName ?: '-') + ' / ' + (item.beforeLocationName ?: '-')}"></td>
                                <td>
                                    <div th:if="${item.returnStatus == 'BORROWING'}">
                                        <select class="form-control return-warehouse" th:id="${'returnWarehouseId_' + item.itemId}"
                                                th:data-item-id="${item.itemId}" onchange="refreshReturnLocations(this.getAttribute('data-item-id'))">
                                            <option value="">请选择归还仓库</option>
                                            <option th:each="warehouse : ${warehouseList}" th:value="${warehouse.warehouseId}"
                                                    th:text="${warehouse.warehouseCode + ' - ' + warehouse.warehouseName}"
                                                    th:selected="${warehouse.warehouseId == item.beforeWarehouseId}"></option>
                                        </select>
                                        <select class="form-control return-location" th:id="${'returnLocationId_' + item.itemId}"
                                                th:data-default-location-id="${item.beforeLocationId}">
                                            <option value="">请选择归还位置</option>
                                        </select>
                                    </div>
                                    <span th:if="${item.returnStatus != 'BORROWING'}"
                                          th:text="${(item.returnWarehouseName ?: '-') + ' / ' + (item.returnLocationName ?: '-')}"></span>
                                </td>
                                <td th:text="${@dict.getLabel('ams_borrow_status', item.returnStatus)}"></td>
                                <td th:text="${item.actualReturnDate == null ? '' : #dates.format(item.actualReturnDate, 'yyyy-MM-dd')}"></td>
                                <td th:text="${item.remark}"></td>
                                <td>
                                    <a th:if="${item.returnStatus == 'BORROWING'}"
                                       class="btn btn-primary btn-xs" shiro:hasPermission="asset:borrow:applyReturn"
                                       href="javascript:void(0)" th:onclick="'applyReturn(' + ${item.itemId} + ')'">
                                        <i class="fa fa-sign-in"></i>申请归还
                                    </a>
                                    <a th:if="${item.returnStatus == 'PENDING_RETURN_CONFIRM'}"
                                       class="btn btn-primary btn-xs" shiro:hasPermission="asset:borrow:confirmReturn"
                                       href="javascript:void(0)" th:onclick="'confirmReturn(' + ${item.itemId} + ')'">
                                        <i class="fa fa-check"></i>确认归还
                                    </a>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </form>
    </div>
    <th:block th:include="include :: footer" />
    <script th:inline="javascript">
        var prefix = ctx + "asset/borrow";
        var orderId = [[${amsBorrowOrder.orderId}]];
        var locationList = [[${locationList}]];

        $(function() {
            $(".return-location").each(function() {
                var itemId = this.id.replace("returnLocationId_", "");
                refreshReturnLocations(itemId);
            });
        });

        function refreshReturnLocations(itemId) {
            var warehouseId = $("#returnWarehouseId_" + itemId).val();
            var locationSelect = $("#returnLocationId_" + itemId);
            var defaultLocationId = locationSelect.attr("data-default-location-id");
            locationSelect.empty().append($("<option>").val("").text("请选择归还位置"));
            $.each(locationList, function(i, location) {
                if (String(location.warehouseId) === String(warehouseId)) {
                    var option = $("<option>").val(location.locationId).text(location.locationCode + " - " + location.locationName);
                    if (String(location.locationId) === String(defaultLocationId)) {
                        option.attr("selected", "selected");
                    }
                    locationSelect.append(option);
                }
            });
        }

        function applyReturn(itemId) {
            var warehouseId = $("#returnWarehouseId_" + itemId).val();
            var locationId = $("#returnLocationId_" + itemId).val();
            if (!warehouseId || !locationId) {
                $.modal.alertWarning("请选择归还仓库和归还位置");
                return;
            }
            $.modal.confirm("提交后该明细将进入待归还确认状态，是否继续？", function() {
                postJson(prefix + "/applyReturn/" + orderId, [{
                    itemId: itemId,
                    returnWarehouseId: warehouseId,
                    returnLocationId: locationId
                }]);
            });
        }

        function confirmReturn(itemId) {
            $.modal.confirm("确认后该资产将重新入库到申请归还时保存的仓位，是否继续？", function() {
                postJson(prefix + "/confirmReturn/" + orderId, [{ itemId: itemId }]);
            });
        }

        function postJson(url, payload) {
            $.ajax({
                url: url,
                type: "post",
                contentType: "application/json",
                dataType: "json",
                data: JSON.stringify(payload),
                beforeSend: function(xhr) {
                    var token = $("meta[name='csrf-token']").attr("content");
                    if (token) {
                        xhr.setRequestHeader("X-CSRF-Token", token);
                    }
                    $.modal.loading("正在处理中，请稍候...");
                },
                complete: function() {
                    $.modal.closeLoading();
                },
                success: function(result) {
                    $.modal.closeLoading();
                    if (result.code == web_status.SUCCESS) {
                        $.modal.msgSuccess(result.msg);
                        refreshBorrowListQuietly();
                        setTimeout(function() {
                            window.location.reload();
                        }, 200);
                    } else if (result.code == web_status.WARNING) {
                        $.modal.alertWarning(result.msg);
                    } else {
                        $.modal.alertError(result.msg);
                    }
                },
                error: function(xhr) {
                    $.modal.closeLoading();
                    $.modal.alertError(xhr.responseJSON && xhr.responseJSON.msg
                        ? xhr.responseJSON.msg : "操作请求失败，请刷新页面后重试");
                }
            });
        }

        function refreshBorrowListQuietly() {
            try {
                if (typeof activeWindow !== "function") {
                    return;
                }
                var listWindow = activeWindow();
                if (listWindow && listWindow.$ && listWindow.table
                    && listWindow.table.options && listWindow.table.options.type !== undefined) {
                    listWindow.$.table.refresh();
                }
            } catch (e) {
                if (window.console) {
                    console.warn("刷新借用列表失败", e);
                }
            }
        }
    </script>
</body>
</html>
