<!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" />
</head>
<body class="white-bg">
    <div class="wrapper wrapper-content animated fadeInRight ibox-content">
        <form class="form-horizontal m" id="form-asset-add">
            <div class="col-xs-6">
                <div class="form-group">
                    <label class="col-sm-4 control-label is-required">资产编码：</label>
                    <div class="col-sm-8">
                        <input name="assetCode" class="form-control" type="text" required>
                    </div>
                </div>
            </div>
            <div class="col-xs-6">
                <div class="form-group">
                    <label class="col-sm-4 control-label is-required">资产名称：</label>
                    <div class="col-sm-8">
                        <input name="assetName" class="form-control" type="text" required>
                    </div>
                </div>
            </div>
            <div class="col-xs-6">
                <div class="form-group">
                    <label class="col-sm-4 control-label is-required">资产类别：</label>
                    <div class="col-sm-8">
                        <select id="categoryId" name="categoryId" class="form-control select2-control" required>
                            <option value="">请选择</option>
                            <option th:each="category : ${categoryList}" th:text="${category.categoryName}" th:value="${category.categoryId}" th:data-use-life="${category.defaultUseLife}" th:data-maintenance-cycle="${category.defaultMaintenanceCycle}"></option>
                        </select>
                    </div>
                </div>
            </div>
            <div class="col-xs-6">
                <div class="form-group">
                    <label class="col-sm-4 control-label">规格型号：</label>
                    <div class="col-sm-8">
                        <input name="specModel" class="form-control" type="text">
                    </div>
                </div>
            </div>
            <div class="col-xs-6">
                <div class="form-group">
                    <label class="col-sm-4 control-label">品牌：</label>
                    <div class="col-sm-8">
                        <input name="brand" class="form-control" type="text">
                    </div>
                </div>
            </div>
            <div class="col-xs-6">
                <div class="form-group">
                    <label class="col-sm-4 control-label is-required">所属仓库：</label>
                    <div class="col-sm-8">
                        <select id="warehouseId" name="warehouseId" class="form-control select2-control" required>
                            <option value="">请选择</option>
                            <option th:each="warehouse : ${warehouseList}" th:text="${warehouse.warehouseName}" th:value="${warehouse.warehouseId}"></option>
                        </select>
                    </div>
                </div>
            </div>
            <div class="col-xs-6">
                <div class="form-group">
                    <label class="col-sm-4 control-label is-required">存放位置：</label>
                    <div class="col-sm-8">
                        <select id="locationId" name="locationId" class="form-control select2-control" required>
                            <option value="">请选择</option>
                            <option th:each="location : ${locationList}" th:text="${location.locationName}" th:value="${location.locationId}" th:data-warehouse-id="${location.warehouseId}"></option>
                        </select>
                    </div>
                </div>
            </div>
            <div class="col-xs-6">
                <div class="form-group">
                    <label class="col-sm-4 control-label">使用部门：</label>
                    <div class="col-sm-8">
                        <select name="useDeptId" class="form-control select2-control">
                            <option value="">请选择</option>
                            <option th:each="dept : ${deptList}" th:text="${dept.deptName}" th:value="${dept.deptId}"></option>
                        </select>
                    </div>
                </div>
            </div>
            <div class="col-xs-6">
                <div class="form-group">
                    <label class="col-sm-4 control-label">使用人：</label>
                    <div class="col-sm-8">
                        <select name="useUserId" class="form-control select2-control">
                            <option value="">请选择</option>
                            <option th:each="user : ${userList}" th:text="${user.userName + '（' + user.loginName + '）'}" th:value="${user.userId}"></option>
                        </select>
                    </div>
                </div>
            </div>
            <div class="col-xs-6">
                <div class="form-group">
                    <label class="col-sm-4 control-label">保管人：</label>
                    <div class="col-sm-8">
                        <select name="custodianId" class="form-control select2-control">
                            <option value="">请选择</option>
                            <option th:each="user : ${userList}" th:text="${user.userName + '（' + user.loginName + '）'}" th:value="${user.userId}"></option>
                        </select>
                    </div>
                </div>
            </div>
            <div class="col-xs-6">
                <div class="form-group">
                    <label class="col-sm-4 control-label">购置日期：</label>
                    <div class="col-sm-8">
                        <div class="input-group date">
                            <input name="purchaseDate" class="form-control" placeholder="yyyy-MM-dd" type="text">
                            <span class="input-group-addon"><i class="fa fa-calendar"></i></span>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-xs-6">
                <div class="form-group">
                    <label class="col-sm-4 control-label">资产原值：</label>
                    <div class="col-sm-8">
                        <input name="originalValue" class="form-control" type="number" min="0" step="0.01">
                    </div>
                </div>
            </div>
            <div class="col-xs-6">
                <div class="form-group">
                    <label class="col-sm-4 control-label">使用寿命（月）：</label>
                    <div class="col-sm-8">
                        <input name="useLife" class="form-control" type="number" min="0" step="1">
                    </div>
                </div>
            </div>
            <div class="col-xs-6">
                <div class="form-group">
                    <label class="col-sm-4 control-label">维保周期（月）：</label>
                    <div class="col-sm-8">
                        <input name="maintenanceCycle" class="form-control" type="number" min="0" step="1">
                    </div>
                </div>
            </div>
            <div class="col-xs-6">
                <div class="form-group">
                    <label class="col-sm-4 control-label">上次维保日期：</label>
                    <div class="col-sm-8">
                        <div class="input-group date">
                            <input name="lastMaintenanceDate" class="form-control" placeholder="yyyy-MM-dd" type="text">
                            <span class="input-group-addon"><i class="fa fa-calendar"></i></span>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-xs-6">
                <div class="form-group">
                    <label class="col-sm-4 control-label">下次维保日期：</label>
                    <div class="col-sm-8">
                        <div class="input-group date">
                            <input name="nextMaintenanceDate" class="form-control" placeholder="yyyy-MM-dd" type="text">
                            <span class="input-group-addon"><i class="fa fa-calendar"></i></span>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-xs-12">
                <div class="form-group">
                    <label class="col-sm-2 control-label">备注：</label>
                    <div class="col-sm-10">
                        <textarea name="remark" class="form-control"></textarea>
                    </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/asset"
        var allLocationOptions = [];
        var syncingWarehouseAndLocation = false;

        initLocationOptions();
        $(".select2-control").select2({
            placeholder: "请选择",
            allowClear: true
        });
        $("#warehouseId").on("change", function() {
            if (!syncingWarehouseAndLocation) {
                refreshLocationOptions();
            }
        });
        $("#locationId").on("change", fillWarehouseByLocation);
        $("#categoryId").on("change", fillCategoryDefaults);
        $("input[name='maintenanceCycle']").on("input change", calculateNextMaintenanceDate);
        $("input[name='lastMaintenanceDate']").on("change changeDate", calculateNextMaintenanceDate);
        refreshLocationOptions();

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

        function submitHandler() {
            if ($.validate.form()) {
                $.operate.save(prefix + "/add", $('#form-asset-add').serialize());
            }
        }

        function refreshLocationOptions() {
            var warehouseId = $("#warehouseId").val();
            var $location = $("#locationId");
            var selectedLocationId = $location.val();
            $location.empty().append('<option value="">请选择</option>');
            $.each(allLocationOptions, function(index, location) {
                if (!warehouseId || String(location.warehouseId) === String(warehouseId)) {
                    var option = new Option(location.text, location.value, false, false);
                    $(option).attr("data-warehouse-id", location.warehouseId);
                    $location.append(option);
                }
            });
            if (selectedLocationId && $location.find("option[value='" + selectedLocationId + "']").length > 0) {
                $location.val(selectedLocationId);
            } else {
                $location.val("");
            }
            $location.trigger("change.select2");
        }

        function fillCategoryDefaults() {
            var $option = $("#categoryId").find("option:selected");
            if (!$option.val()) {
                $("input[name='useLife']").val("");
                $("input[name='maintenanceCycle']").val("");
                calculateNextMaintenanceDate();
                return;
            }
            $("input[name='useLife']").val($option.attr("data-use-life") || "");
            $("input[name='maintenanceCycle']").val($option.attr("data-maintenance-cycle") || "");
            calculateNextMaintenanceDate();
        }

        function initLocationOptions() {
            $("#locationId").find("option[data-warehouse-id]").each(function() {
                allLocationOptions.push({
                    value: $(this).val(),
                    text: $(this).text(),
                    warehouseId: $(this).attr("data-warehouse-id")
                });
            });
        }

        function fillWarehouseByLocation() {
            if (syncingWarehouseAndLocation) {
                return;
            }
            var selectedLocationId = $("#locationId").val();
            if (!selectedLocationId) {
                return;
            }
            var location = findLocationOption(selectedLocationId);
            if (!location || !location.warehouseId) {
                return;
            }
            syncingWarehouseAndLocation = true;
            $("#warehouseId").val(location.warehouseId).trigger("change.select2");
            refreshLocationOptions();
            $("#locationId").val(selectedLocationId).trigger("change.select2");
            syncingWarehouseAndLocation = false;
        }

        function findLocationOption(locationId) {
            for (var i = 0; i < allLocationOptions.length; i++) {
                if (String(allLocationOptions[i].value) === String(locationId)) {
                    return allLocationOptions[i];
                }
            }
            return null;
        }

        function calculateNextMaintenanceDate() {
            var lastDate = parseDateValue($("input[name='lastMaintenanceDate']").val());
            var cycle = parseInt($("input[name='maintenanceCycle']").val(), 10);
            if (!lastDate || isNaN(cycle) || cycle < 0) {
                return;
            }
            $("input[name='nextMaintenanceDate']").val(formatDate(addMonths(lastDate, cycle)));
        }

        function parseDateValue(value) {
            var match = /^(\d{4})-(\d{1,2})-(\d{1,2})$/.exec(value || "");
            if (!match) {
                return null;
            }
            return new Date(parseInt(match[1], 10), parseInt(match[2], 10) - 1, parseInt(match[3], 10));
        }

        function addMonths(date, months) {
            var day = date.getDate();
            var result = new Date(date.getFullYear(), date.getMonth() + months, 1);
            var maxDay = new Date(result.getFullYear(), result.getMonth() + 1, 0).getDate();
            result.setDate(Math.min(day, maxDay));
            return result;
        }

        function formatDate(date) {
            var month = date.getMonth() + 1;
            var day = date.getDate();
            return date.getFullYear() + "-" + (month < 10 ? "0" + month : month) + "-" + (day < 10 ? "0" + day : day);
        }

        $("input[name='purchaseDate'], input[name='lastMaintenanceDate'], input[name='nextMaintenanceDate']").datetimepicker({
            format: "yyyy-mm-dd",
            minView: "month",
            autoclose: true
        });
    </script>
</body>
</html>
