<!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-return-add">
            <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 is-required">接收仓库：</label>
                        <div class="col-sm-8">
                            <select name="receiveWarehouseId" class="form-control" required
                                    onchange="changeReceiveWarehouse()">
                                <option value="">请选择接收仓库</option>
                                <option th:each="warehouse : ${warehouseList}" th:value="${warehouse.warehouseId}"
                                        th:text="${warehouse.warehouseCode + ' - ' + warehouse.warehouseName}"></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"></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/return";
        var locationList = [[${locationList}]];
        $("#form-return-add").validate({ focusCleanup: true });

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

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

        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: "originWarehouseName", title: "领用前仓位", formatter: function(value, row) { return buildOriginText(row); } },
                    { field: "beforeDeptName", title: "退库前部门" },
                    { field: "beforeUserName", title: "退库前使用人" },
                    { field: "afterLocationId", title: "退库位置", formatter: function(value, row, index) { return buildLocationSelect(value, index); } },
                    { field: "remark", title: "明细备注", formatter: function(value, row, index) { return buildInput("amsReturnOrderItemList[" + 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: buildSelectorUrl(), 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 currentRows = $("#bootstrap-table").bootstrapTable("getData");
            if (!isCompatibleOriginGroup(currentRows.concat(selectedAssets))) {
                $.modal.alertWarning("一张退库单只能选择同一原领用仓库的资产，缺少领用来源的资产不能与可追溯资产混选");
                return;
            }
            if (currentRows.length === 0 && isOriginEnabled(selectedAssets[0])) {
                $("[name='receiveWarehouseId']").val(selectedAssets[0].originWarehouseId);
            }
            var existing = {};
            $.each(currentRows, 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: buildReturnItem(asset) });
                    existing[String(asset.assetId)] = true;
                }
            });
            $.modal.close(index);
        }

        function buildReturnItem(asset) {
            return {
                assetId: asset.assetId, assetCode: asset.assetCode, assetName: asset.assetName,
                categoryName: asset.categoryName, beforeDeptId: asset.useDeptId,
                beforeDeptName: asset.useDeptName, beforeUserId: asset.useUserId,
                beforeUserName: asset.useUserName, originWarehouseId: asset.originWarehouseId,
                originWarehouseCode: asset.originWarehouseCode, originWarehouseName: asset.originWarehouseName,
                originWarehouseEnabled: asset.originWarehouseEnabled, originLocationId: asset.originLocationId,
                originLocationCode: asset.originLocationCode, originLocationName: asset.originLocationName,
                originLocationEnabled: asset.originLocationEnabled,
                afterLocationId: isOriginEnabled(asset)
                    && String(asset.originWarehouseId) === String($("[name='receiveWarehouseId']").val())
                    ? asset.originLocationId : "", remark: ""
            };
        }

        function buildSelectorUrl() {
            var url = prefix + "/selectAsset";
            var rows = $("#bootstrap-table").bootstrapTable("getData");
            if (rows.length === 0) { return url; }
            if (isTraceable(rows[0])) {
                return url + "?originWarehouseId=" + rows[0].originWarehouseId;
            }
            return url + "?missingOriginOnly=true";
        }

        function isCompatibleOriginGroup(rows) {
            if (!rows || rows.length === 0) { return true; }
            var traceable = isTraceable(rows[0]);
            var warehouseId = traceable ? String(rows[0].originWarehouseId) : "";
            for (var i = 1; i < rows.length; i++) {
                if (isTraceable(rows[i]) !== traceable) { return false; }
                if (traceable && String(rows[i].originWarehouseId) !== warehouseId) { return false; }
            }
            return true;
        }

        function isTraceable(row) {
            return row.originWarehouseId != null && row.originLocationId != null;
        }

        function isOriginEnabled(row) {
            return isTraceable(row) && row.originWarehouseEnabled === "Y" && row.originLocationEnabled === "Y";
        }

        function buildOriginText(row) {
            if (!isTraceable(row)) { return "无可追溯领用前仓位"; }
            var text = (row.originWarehouseName || "-") + " / " + (row.originLocationName || "-");
            return text + (isOriginEnabled(row) ? "" : "（原仓位已停用）");
        }

        function changeReceiveWarehouse() {
            syncDetailRows();
            var rows = $("#bootstrap-table").bootstrapTable("getData");
            $.each(rows, function(index, row) { row.afterLocationId = ""; });
            $("#bootstrap-table").bootstrapTable("load", rows);
        }

        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.afterLocationId = tr.find("[name$='.afterLocationId']").val() || "";
                row.remark = tr.find("[name$='.remark']").val() || "";
            });
        }

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

        function buildLocationSelect(value, index) {
            var warehouseId = $("[name='receiveWarehouseId']").val();
            var select = $("<select>").addClass("form-control").attr({ name: "amsReturnOrderItemList[" + index + "].afterLocationId", required: true });
            select.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(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>
