import Big from "big.js";
import GlobalConfig, { addThousandSeparators } from "../global-config.js";

class BigData {
    async init() {
        try {
            this.totalTargetPAD = await this.getTargetPAD();
            this.resultDataTotal = await this.getDataTotalPotensi();
            this.dataVerification = await this.getDataVerfication();
            this.dataNonVerification = await this.getDataNonVerfication();
            this.dataBusiness = await this.getDataBusiness();
            this.dataNonBusiness = await this.getDataNonBusiness();
            this.dataTataRuang = await this.getDataTataRuang();

            // total potensi
            this.bigTargetPAD = new Big(this.totalTargetPAD ?? 0);
            this.bigTotalPotensi = new Big(this.resultDataTotal.totalData ?? 0);

            this.resultPercentage = 0;
            if (this.bigTotalPotensi > 0 && this.bigTargetPAD > 0) {
                this.resultPercentage = this.bigTotalPotensi
                    .div(this.bigTargetPAD)
                    .times(100)
                    .toFixed(2);
                if (this.resultPercentage > 100) {
                    this.resultPercentage = 100;
                }
            }

            // tata ruang
            this.bigTotalTataRuang = new Big(this.dataTataRuang);
            this.percentageResultTataRuang =
                this.bigTotalTataRuang <= 0 || this.bigTotalPotensi <= 0
                    ? 0
                    : this.bigTotalTataRuang
                          .div(this.bigTotalPotensi)
                          .times(100)
                          .toFixed(2);

            // kekurangan potensi
            this.totalKekuranganPotensi = new Big(
                this.bigTargetPAD - this.bigTotalPotensi
            );

            this.percentageKekuranganPotensi =
                this.totalKekuranganPotensi <= 0 || this.bigTargetPAD <= 0
                    ? 0
                    : this.totalKekuranganPotensi
                          .div(this.bigTargetPAD)
                          .times(100)
                          .toFixed(2);

            // non-verification documents
            this.bigTotalNonVerification = new Big(
                this.dataNonVerification.total
            );
            this.percentageResultNonVerification = this.bigTotalNonVerification
                .div(this.bigTotalPotensi)
                .times(100)
                .toFixed(2);

            // verification documents
            this.bigTotalVerification = new Big(this.dataVerification.total);
            this.percetageResultVerification =
                this.bigTotalVerification <= 0 || this.bigTotalPotensi <= 0
                    ? 0
                    : this.bigTotalVerification
                          .div(this.bigTargetPAD)
                          .times(100)
                          .toFixed(2);

            // business documents
            this.bigTotalBusiness = new Big(this.dataBusiness.total);
            this.percentageResultBusiness =
                this.bigTotalNonVerification <= 0
                    ? 0
                    : this.bigTotalBusiness
                          .div(this.bigTotalNonVerification)
                          .times(100)
                          .toFixed(2);

            // non-business documents
            this.bigTotalNonBusiness = new Big(this.dataNonBusiness.total);
            this.percentageResultNonBusiness =
                this.bigTotalNonBusiness <= 0
                    ? 0
                    : this.bigTotalNonBusiness
                          .div(this.bigTotalNonVerification)
                          .times(100)
                          .toFixed(2);

            if (!this.bigTargetPAD) {
                console.error("Failed to load chart data");
                return;
            }

            this.initChartTargetPAD();
            this.initChartUsaha();
            this.initChartNonUsaha();
            this.initChartTotalPotensi();
            this.initChartVerificationDocuments();
            this.initChartNonVerificationDocuments();
            this.initChartKekuranganPotensi();
            this.initChartRealisasiTerbitPBG();
            this.initChartMenungguKlikDPMPTSP();
            this.initChartProsesDinasTeknis();
            this.initChartPotensiTataRuang();
        } catch (e) {
            console.error(e);
        }
    }

    async getDataTotalPotensi() {
        try {
            const response = await fetch(
                `${GlobalConfig.apiHost}/api/all-task-documents`,
                {
                    credentials: "include",
                    headers: {
                        Authorization: `Bearer ${
                            document.querySelector("meta[name='api-token']")
                                .content
                        }`,
                        "Content-Type": "application/json",
                    },
                }
            );

            if (!response.ok) {
                console.error("Network response was not ok", response);
            }

            const data = await response.json();
            return {
                seriesData: data.data.series,
                countData: data.data.count,
                totalData: data.data.total,
            };
        } catch (error) {
            console.error("Error fetching chart data:", error);
            return null;
        }
    }

    async getTargetPAD() {
        try {
            const response = await fetch(
                `${GlobalConfig.apiHost}/api/api-data-settings?search=target_pad`,
                {
                    credentials: "include",
                    headers: {
                        Authorization: `Bearer ${
                            document.querySelector("meta[name='api-token']")
                                .content
                        }`,
                        "Content-Type": "application/json",
                    },
                }
            );

            if (!response.ok) {
                console.error("Network response was not ok", response);
            }

            const data = await response.json();
            return data.data[0].value;
        } catch (error) {
            console.error("Error fetching chart data:", error);
            return 0;
        }
    }

    async getDataVerfication() {
        try {
            const response = await fetch(
                `${GlobalConfig.apiHost}/api/verification-documents`,
                {
                    credentials: "include",
                    headers: {
                        Authorization: `Bearer ${
                            document.querySelector("meta[name='api-token']")
                                .content
                        }`,
                        "Content-Type": "application/json",
                    },
                }
            );

            if (!response.ok) {
                console.error("Network response was not ok", response);
            }

            const data = await response.json();
            return {
                count: data.data.count,
                total: data.data.total,
            };
        } catch (error) {
            console.error("Error fetching chart data:", error);
            return 0;
        }
    }

    async getDataNonVerfication() {
        try {
            const response = await fetch(
                `${GlobalConfig.apiHost}/api/non-verification-documents`,
                {
                    credentials: "include",
                    headers: {
                        Authorization: `Bearer ${
                            document.querySelector("meta[name='api-token']")
                                .content
                        }`,
                        "Content-Type": "application/json",
                    },
                }
            );

            if (!response.ok) {
                console.error("Network response was not ok", response);
            }

            const data = await response.json();
            return {
                count: data.data.count,
                total: data.data.total,
            };
        } catch (error) {
            console.error("Error fetching chart data:", error);
            return 0;
        }
    }

    async getDataBusiness() {
        try {
            const response = await fetch(
                `${GlobalConfig.apiHost}/api/business-documents`,
                {
                    credentials: "include",
                    headers: {
                        Authorization: `Bearer ${
                            document.querySelector("meta[name='api-token']")
                                .content
                        }`,
                        "Content-Type": "application/json",
                    },
                }
            );

            if (!response.ok) {
                console.error("Network response was not ok", response);
            }

            const data = await response.json();
            return {
                count: data.data.count,
                total: data.data.total,
            };
        } catch (error) {
            console.error("Error fetching chart data:", error);
            return 0;
        }
    }

    async getDataNonBusiness() {
        try {
            const response = await fetch(
                `${GlobalConfig.apiHost}/api/non-business-documents`,
                {
                    credentials: "include",
                    headers: {
                        Authorization: `Bearer ${
                            document.querySelector("meta[name='api-token']")
                                .content
                        }`,
                        "Content-Type": "application/json",
                    },
                }
            );

            if (!response.ok) {
                console.error("Network response was not ok", response);
            }

            const data = await response.json();
            return {
                count: data.data.count,
                total: data.data.total,
            };
        } catch (error) {
            console.error("Error fetching chart data:", error);
            return 0;
        }
    }

    async getDataTataRuang() {
        try {
            const response = await fetch(
                `${GlobalConfig.apiHost}/api/api-data-settings?search=tata_ruang`,
                {
                    credentials: "include",
                    headers: {
                        Authorization: `Bearer ${
                            document.querySelector("meta[name='api-token']")
                                .content
                        }`,
                        "Content-Type": "application/json",
                    },
                }
            );

            if (!response.ok) {
                console.error("Network response was not ok", response);
            }

            const data = await response.json();
            return data.data[0].value;
        } catch (error) {
            console.error("Error fetching chart data:", error);
            return 0;
        }
    }

    initChartTargetPAD() {
        document
            .querySelectorAll(".document-count.chart-target-pad")
            .forEach((element) => {
                element.innerText = ``;
            });
        document
            .querySelectorAll(".document-total.chart-target-pad")
            .forEach((element) => {
                element.innerText = `Rp.${addThousandSeparators(
                    this.bigTargetPAD.toString()
                )}`;
            });
        document
            .querySelectorAll(".small-percentage.chart-target-pad")
            .forEach((element) => {
                element.innerText = `${100}%`;
            });
    }
    initChartTotalPotensi() {
        const countAll = this.resultDataTotal.countData ?? 0;

        document
            .querySelectorAll(".document-count.chart-total-potensi")
            .forEach((element) => {
                element.innerText = `${countAll}`;
            });
        document
            .querySelectorAll(".document-total.chart-total-potensi")
            .forEach((element) => {
                element.innerText = `Rp.${addThousandSeparators(
                    this.bigTotalPotensi.toString()
                )}`;
            });
        document
            .querySelectorAll(".small-percentage.chart-total-potensi")
            .forEach((element) => {
                element.innerText = `${this.resultPercentage}%`;
            });
    }
    initChartVerificationDocuments() {
        document
            .querySelectorAll(".document-count.chart-berkas-terverifikasi")
            .forEach((element) => {
                element.innerText = `${this.dataVerification.count}`;
            });
        document
            .querySelectorAll(".document-total.chart-berkas-terverifikasi")
            .forEach((element) => {
                element.innerText = `Rp.${addThousandSeparators(
                    this.bigTotalVerification.toString()
                )}`;
            });
        document
            .querySelectorAll(".small-percentage.chart-berkas-terverifikasi")
            .forEach((element) => {
                element.innerText = `${this.percetageResultVerification}%`;
            });
    }
    initChartNonVerificationDocuments() {
        document
            .querySelectorAll(
                ".document-count.chart-berkas-belum-terverifikasi"
            )
            .forEach((element) => {
                element.innerText = `${this.dataNonVerification.count}`;
            });
        document
            .querySelectorAll(
                ".document-total.chart-berkas-belum-terverifikasi"
            )
            .forEach((element) => {
                element.innerText = `Rp.${addThousandSeparators(
                    this.bigTotalNonVerification.toString()
                )}`;
            });
        document
            .querySelectorAll(
                ".small-percentage.chart-berkas-belum-terverifikasi"
            )
            .forEach((element) => {
                element.innerText = `${this.percentageResultNonVerification}%`;
            });
    }
    initChartUsaha() {
        document
            .querySelectorAll(".document-count.chart-business")
            .forEach((element) => {
                element.innerText = `${this.dataBusiness.count}`;
            });
        document
            .querySelectorAll(".document-total.chart-business")
            .forEach((element) => {
                element.innerText = `Rp.${addThousandSeparators(
                    this.bigTotalBusiness.toString()
                )}`;
            });
        document
            .querySelectorAll(".small-percentage.chart-business")
            .forEach((element) => {
                element.innerText = `${this.percentageResultBusiness}%`;
            });
    }
    initChartNonUsaha() {
        document
            .querySelectorAll(".document-count.chart-non-business")
            .forEach((element) => {
                element.innerText = `${this.dataNonBusiness.count}`;
            });
        document
            .querySelectorAll(".document-total.chart-non-business")
            .forEach((element) => {
                element.innerText = `Rp.${addThousandSeparators(
                    this.bigTotalNonBusiness.toString()
                )}`;
            });
        document
            .querySelectorAll(".small-percentage.chart-non-business")
            .forEach((element) => {
                element.innerText = `${this.percentageResultNonBusiness}%`;
            });
    }
    initChartKekuranganPotensi() {
        document
            .querySelectorAll(".document-count.chart-kekurangan-potensi")
            .forEach((element) => {
                element.innerText = ``;
            });
        document
            .querySelectorAll(".document-total.chart-kekurangan-potensi")
            .forEach((element) => {
                element.innerText = `Rp.${addThousandSeparators(
                    this.totalKekuranganPotensi.toString()
                )}`;
            });
        document
            .querySelectorAll(".small-percentage.chart-kekurangan-potensi")
            .forEach((element) => {
                element.innerText = `${this.percentageKekuranganPotensi}%`;
            });
    }
    initChartRealisasiTerbitPBG() {
        document
            .querySelectorAll(".document-count.chart-realisasi-tebit-pbg")
            .forEach((element) => {
                element.innerText = `0`;
            });
        document
            .querySelectorAll(".document-total.chart-realisasi-tebit-pbg")
            .forEach((element) => {
                element.innerText = `Rp.${addThousandSeparators("0.00")}`;
            });
        document
            .querySelectorAll(".small-percentage.chart-realisasi-tebit-pbg")
            .forEach((element) => {
                element.innerText = `0.00%`;
            });
    }
    initChartMenungguKlikDPMPTSP() {
        document
            .querySelectorAll(".document-count.chart-menunggu-klik-dpmptsp")
            .forEach((element) => {
                element.innerText = `${0}`;
            });
        document
            .querySelectorAll(".document-total.chart-menunggu-klik-dpmptsp")
            .forEach((element) => {
                element.innerText = `Rp.${addThousandSeparators("0.00")}`;
            });
        document
            .querySelectorAll(".small-percentage.chart-menunggu-klik-dpmptsp")
            .forEach((element) => {
                element.innerText = `0.00%`;
            });
    }
    initChartProsesDinasTeknis() {
        document
            .querySelectorAll(".document-count.chart-proses-dinas-teknis")
            .forEach((element) => {
                element.innerText = `${0}`;
            });
        document
            .querySelectorAll(".document-total.chart-proses-dinas-teknis")
            .forEach((element) => {
                element.innerText = `Rp.${addThousandSeparators("0.00")}`;
            });
        document
            .querySelectorAll(".small-percentage.chart-proses-dinas-teknis")
            .forEach((element) => {
                element.innerText = `0.00%`;
            });
    }
    initChartPotensiTataRuang() {
        document
            .querySelectorAll(".document-count.chart-potensi-tata-ruang")
            .forEach((element) => {
                element.innerText = "";
            });
        document
            .querySelectorAll(".document-total.chart-potensi-tata-ruang")
            .forEach((element) => {
                element.innerText = `Rp.${addThousandSeparators(
                    this.bigTotalTataRuang.toString()
                )}`;
            });
        document
            .querySelectorAll(".small-percentage.chart-potensi-tata-ruang")
            .forEach((element) => {
                element.innerText = `${this.percentageResultTataRuang}%`;
            });
    }
}

document.addEventListener("DOMContentLoaded", async function (e) {
    await new BigData().init();
});

function resizeDashboard() {
    //Target Width
    let targetElement = document.getElementById("dashboard-fixed-wrapper");
    let targetWidth = targetElement.offsetWidth;
    //console.log("TARGET ",targetWidth);

    //Real Object Width
    let dashboardElement = document.getElementById("dashboard-fixed-container");
    let dashboardWidth = 1110; //dashboardElement.offsetWidth;
    //console.log("CURRENT ",dashboardWidth);

    if (targetWidth > dashboardWidth) {
        targetWidth = dashboardWidth;
    }

    dashboardElement.style.transformOrigin = "left top";
    dashboardElement.style.transition = "transform 0.2s ease-in-out";
    dashboardElement.style.transform =
        "scale(" + (targetWidth / dashboardWidth).toFixed(2) + ")";
    //console.log("SCALE ", (targetWidth/dashboardWidth).toFixed(2));
}

window.addEventListener("load", function () {
    resizeDashboard();
});

window.addEventListener("resize", function () {
    resizeDashboard();
});
