Загрузка данных


<script type="text/javascript">
    $(function () {
        var dia_register_id;
        let isForming = false;
        let currentStage = "";

        const $formBtn = $("#formBtn");
        const originalButtonText = $formBtn.text().trim();

        let reportTable = new QueryTable(
            "xxeQqUgZ",
            {
                initComplete: function (settings, json) {
                },
                onRowSelect: function (data, index) {
                },
                onRowDeselect: function (data, index) {
                },
                drawCallback: function (settings) {
                }
            },
            () => {
                return {
                    report_date_from: $("#dateFrom").val(),
                    report_date_to: $("#dateTo").val(),
                    dia_register_id: dia_register_id,
                    isShow: ($("#isShow").val() == 1)
                };
            }
        );

        // Выполняем запрос асинхронно и записываем время в консоль.
        async function executeRequest(stage, options) {
            currentStage = stage;
            $formBtn.text(stage + "…");

            const startedAt = Date.now();
            console.log("Начало этапа:", stage);

            try {
                const result = await $.ajax({
                    ...options,
                    async: true
                });

                console.log("Ответ этапа:", stage, result);
                return result;
            } finally {
                console.log(
                    "Время этапа:",
                    stage,
                    ((Date.now() - startedAt) / 1000).toFixed(2) + " сек."
                );
            }
        }

        async function get_dia_register_id(reportDate) {
            const data = await executeRequest(
                "Поиск реестра",
                {
                    url: "queryModel.json",
                    type: "POST",
                    data: {
                        queryModelCode: "GH878pfc",
                        date: reportDate,
                        register_type_code: "ROPS"
                    },
                    dataType: "json"
                }
            );

            if (!data || typeof data !== "object" || Array.isArray(data)) {
                throw new Error("Получен некорректный ответ при поиске реестра.");
            }

            return data.id ?? 0;
        }

        $formBtn.on("click", async function () {
            if (isForming) {
                return;
            }

            isForming = true;
            $formBtn.prop("disabled", true);

            const reportDate = getCurDateStr();

            try {
                showProcessing();

                dia_register_id = await get_dia_register_id(reportDate);

                if (dia_register_id == 0) {
                    await executeRequest(
                        "Сохранение параметров",
                        {
                            url: "queryAction/action",
                            type: "POST",
                            data: {
                                viewCode: "6VVoYx6a",
                                queryActionCode: "y2le9Whk",
                                unloadPerconalData: 1,
                                reportDate: reportDate
                            },
                            dataType: "json"
                        }
                    );

                    await executeRequest(
                        "Формирование отчёта",
                        {
                            url: "queryAction/action",
                            type: "POST",
                            data: {
                                viewCode: "6VVoYx6a",
                                queryActionCode: "ZHfR5S0T"
                            },
                            dataType: "json"
                        }
                    );

                    dia_register_id = await get_dia_register_id(reportDate);

                    if (dia_register_id == 0) {
                        throw new Error(
                            "После выполнения операций реестр не найден. " +
                            "Необходимо проверить результат формирования."
                        );
                    }
                }

                currentStage = "Обновление таблицы";
                $("#isShow").val(1);
                reportTable.reload();

            } catch (error) {
                console.error(
                    "Ошибка на этапе:",
                    currentStage,
                    error
                );

                let message = error.message;

                if (!message && error.status) {
                    message = "Ошибка HTTP " + error.status +
                        (error.statusText ? ": " + error.statusText : "");
                }

                if (!message) {
                    message = "Не удалось получить корректный ответ сервера.";
                }

                alert(
                    "Этап: " + currentStage + "\n" +
                    message
                );

            } finally {
                hideProcessing();
                $formBtn
                    .prop("disabled", false)
                    .text(originalButtonText);

                isForming = false;
            }
        });

        function getCurDateStr() {
            const date = new Date();
            const day = String(date.getDate()).padStart(2, "0");
            const month = String(date.getMonth() + 1).padStart(2, "0");
            const year = date.getFullYear();

            return day + "." + month + "." + year;
        }
    });
</script>