const axios = require("axios");
const crypto = require("crypto");
const moment = require("moment");
const zulip = require("zulip-js");
const { exec } = require("child_process");
const fs = require("fs");
const { addLogFunction } = require("./addLogFunctionJS");

const config = {
  username: "networktool-bot@zulip.ipsupply.com.au",
  apiKey: "0jMAmOuhfLvBqKJikv5oAkyNM4RIEoAM",
  realm: "https://zulip.ipsupply.com.au",
};

const checkMultipleRequest = async () => {
  try {
    let report = [];
    let time = moment(Date.now()).format("HH:mm - DD/MM");
    const client = await zulip(config);

    const code = Math.random().toString(36).substring(2, 12);
    const secretString =
      code + "24feca0508b52d34b51db4b40964e7fff12edf71208a4607126f75cb5d504f7f";
    const accessToken = crypto
      .createHash("md5")
      .update(secretString)
      .digest("hex");
    const tokenInt =
      "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczovL2ludC5pcHN1cHBseS5jb20uYXUvYXBpL2xvZ2luIiwiaWF0IjoxNjg5ODYyNjAxLCJleHAiOjE3MjEzOTg2MDEsIm5iZiI6MTY4OTg2MjYwMSwianRpIjoiUElZVjNBM3ZPQVlMQ081SyIsInN1YiI6MSwicHJ2IjoiYzhlZTFmYzg5ZTc3NWVjNGM3Mzg2NjdlNWJlMTdhNTkwYjZkNDBmYyJ9.UcybIKMBjTAY9i0PfIDQMtqHyN72Ul0jC03ZDGLGpMI";
    let content = "||Server| System time| Status \n|---|:---|:---|:---:\n";
    // Tạo tiêu đề

    let allResponse = "";
    const requests = [
      //Ebay Systems
      {
        url: "https://disti.danielvu.com/api/eBayCustomerLog",
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Accept: "application/json",
          loginid: null,
          Code: code,
          AccessToken: accessToken,
        },
        data: {},
        name: "Ebay customer",
        group: "Ebay Systems",
      },
      {
        url: "https://disti.danielvu.com/api/eBayNewItemLog",
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Accept: "application/json",
          loginid: null,
          Code: code,
          AccessToken: accessToken,
        },
        data: {},
        name: "New item",
        group: "Ebay Systems",
      },
      {
        url: "https://disti.danielvu.com/api/eBayChatLog",
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Accept: "application/json",
          loginid: null,
          Code: code,
          AccessToken: accessToken,
        },
        data: {},
        name: "Ebay message",
        group: "Ebay Systems",
      },
      {
        url: "https://disti.danielvu.com/api/sendSellerOrderToERP",
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Accept: "application/json",
          loginid: null,
          Code: code,
          AccessToken: accessToken,
        },
        data: {},
        name: "Erp Sync Order Ebay",
        group: "Ebay Systems",
      },
      {
        url: "https://disti.danielvu.com/api/sendBuyerOrderToERP",
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Accept: "application/json",
          loginid: null,
          Code: code,
          AccessToken: accessToken,
        },
        data: {},
        name: "Erp Sync PO Ebay",
        group: "Ebay Systems",
      },
      //ERP Systems
      {
        url: "https://int.ipsupply.com.au/api/transferGetData",
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: "Bearer " + tokenInt,
        },
        data: {
          urlAPI: "/api/test-log-serial-number/sync-data",
          filter: {},
        },
        name: "Log SN to ERP",
        group: "ERP Systems",
      },
      {
        url: "https://int.ipsupply.com.au/api/transferGetData",
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: "Bearer " + tokenInt,
        },
        data: {
          urlAPI: "/api/stock-model-serial/check-sn-cisco",
          filter: {},
        },
        name: "SN Cisco to ERP",
        group: "ERP Systems",
      },
      {
        url: "https://int.ipsupply.com.au/api/transferPostData",
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: "Bearer " + tokenInt,
        },
        data: {
          urlAPI: "/api/logistics/check-shipping-rates",
          data: {
            courierName: "Fedex",
            packageInfo: {
              from: {
                streetLines: ["8/4A Bachell Ave"],
                city: "Lidcombe",
                stateOrProvinceCode: "",
                postalCode: "2141",
                countryCode: "AU",
              },
              to: {
                streetLines: ["600 Terminal Dr"],
                city: "Louisville",
                stateOrProvinceCode: "KY",
                postalCode: "40209",
                countryCode: "US",
              },
              requestedPackageLineItems: [
                {
                  weight: {
                    value: 10,
                    units: "KG",
                  },
                  dimensions: {
                    length: 2,
                    width: 3,
                    height: 4,
                    units: "CM",
                  },
                  groupPackageCount: 1,
                },
              ],
              commodities: [
                {
                  description: "G6",
                  quantity: 2,
                  quantityUnits: "PCS",
                  unitPrice: {
                    amount: 10000,
                    currency: "USD",
                  },
                  customsValue: {
                    amount: 10000,
                    currency: "USD",
                  },
                },
              ],
              inforCreateFedex: {
                pickupType: "CONTACT_FEDEX_TO_SCHEDULE",
              },
            },
          },
        },
        name: "Shipping rate Fedex",
        group: "Shipping System",
      },
      {
        url: "https://int.ipsupply.com.au/api/transferPostData",
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: "Bearer " + tokenInt,
        },
        data: {
          urlAPI: "/api/logistics/check-shipping-rates",
          data: {
            courierName: "DHL",
            packageInfo: {
              from: {
                streetLines: ["8/4A Bachell Ave"],
                city: "Lidcombe",
                stateOrProvinceCode: "",
                postalCode: "2141",
                countryCode: "AU",
              },
              to: {
                streetLines: ["600 Terminal Dr"],
                city: "Louisville",
                stateOrProvinceCode: "KY",
                postalCode: "40209",
                countryCode: "US",
              },
              requestedPackageLineItems: [
                {
                  weight: {
                    value: 10,
                    units: "KG",
                  },
                  dimensions: {
                    length: 2,
                    width: 3,
                    height: 4,
                    units: "CM",
                  },
                  groupPackageCount: 1,
                },
              ],
              commodities: [
                {
                  description: "G6",
                  quantity: 2,
                  quantityUnits: "PCS",
                  unitPrice: {
                    amount: 10000,
                    currency: "USD",
                  },
                  customsValue: {
                    amount: 10000,
                    currency: "USD",
                  },
                },
              ],
              inforCreateFedex: {
                pickupType: "CONTACT_FEDEX_TO_SCHEDULE",
              },
            },
          },
        },
        name: "Shipping rate DHL",
        group: "Shipping System",
      },
      {
        url: "https://int.ipsupply.com.au/api/transferPostData",
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: "Bearer " + tokenInt,
        },
        data: {
          urlAPI: "/api/logistics/check-shipping-rates",
          data: {
            courierName: "Transdirect",
            packageInfo: {
              from: {
                streetLines: ["8/4A Bachell Ave"],
                city: "Lidcombe",
                stateOrProvinceCode: "",
                postalCode: "2141",
                countryCode: "AU",
              },
              to: {
                streetLines: ["600 Terminal Dr"],
                city: "Louisville",
                stateOrProvinceCode: "KY",
                postalCode: "40209",
                countryCode: "US",
              },
              requestedPackageLineItems: [
                {
                  weight: {
                    value: 10,
                    units: "KG",
                  },
                  dimensions: {
                    length: 2,
                    width: 3,
                    height: 4,
                    units: "CM",
                  },
                  groupPackageCount: 1,
                },
              ],
              commodities: [
                {
                  description: "G6",
                  quantity: 2,
                  quantityUnits: "PCS",
                  unitPrice: {
                    amount: 10000,
                    currency: "USD",
                  },
                  customsValue: {
                    amount: 10000,
                    currency: "USD",
                  },
                },
              ],
              inforCreateFedex: {
                pickupType: "CONTACT_FEDEX_TO_SCHEDULE",
              },
            },
          },
        },
        name: "Shipping rate Transdirect",
        group: "Shipping System",
      },
      {
        url: "https://int.ipsupply.com.au/api/transferPostData",
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: "Bearer " + tokenInt,
        },
        data: {
          urlAPI: "/api/logistics/check-shipping-rates",
          data: {
            courierName: "CouriersPlease",
            packageInfo: {
              from: {
                streetLines: ["8/4A Bachell Ave"],
                city: "Lidcombe",
                stateOrProvinceCode: "",
                postalCode: "2141",
                countryCode: "AU",
              },
              to: {
                streetLines: ["600 Terminal Dr"],
                city: "Louisville",
                stateOrProvinceCode: "KY",
                postalCode: "40209",
                countryCode: "US",
              },
              requestedPackageLineItems: [
                {
                  weight: {
                    value: 10,
                    units: "KG",
                  },
                  dimensions: {
                    length: 2,
                    width: 3,
                    height: 4,
                    units: "CM",
                  },
                  groupPackageCount: 1,
                },
              ],
              commodities: [
                {
                  description: "G6",
                  quantity: 2,
                  quantityUnits: "PCS",
                  unitPrice: {
                    amount: 10000,
                    currency: "USD",
                  },
                  customsValue: {
                    amount: 10000,
                    currency: "USD",
                  },
                },
              ],
              inforCreateFedex: {
                pickupType: "CONTACT_FEDEX_TO_SCHEDULE",
              },
            },
          },
        },
        name: "Shipping rate Courier Please",
        group: "Shipping System",
      },
      {
        url: "https://int.ipsupply.com.au/api/transferPostData",
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: "Bearer " + tokenInt,
        },
        data: {
          urlAPI: "/api/logistics/check-shipping-rates",
          data: {
            courierName: "Auspost",
            packageInfo: {
              from: {
                streetLines: ["8/4A Bachell Ave"],
                city: "Lidcombe",
                stateOrProvinceCode: "",
                postalCode: "2141",
                countryCode: "AU",
              },
              to: {
                streetLines: ["600 Terminal Dr"],
                city: "Louisville",
                stateOrProvinceCode: "KY",
                postalCode: "40209",
                countryCode: "US",
              },
              requestedPackageLineItems: [
                {
                  weight: {
                    value: 10,
                    units: "KG",
                  },
                  dimensions: {
                    length: 2,
                    width: 3,
                    height: 4,
                    units: "CM",
                  },
                  groupPackageCount: 1,
                },
              ],
              commodities: [
                {
                  description: "G6",
                  quantity: 2,
                  quantityUnits: "PCS",
                  unitPrice: {
                    amount: 10000,
                    currency: "USD",
                  },
                  customsValue: {
                    amount: 10000,
                    currency: "USD",
                  },
                },
              ],
              inforCreateFedex: {
                pickupType: "CONTACT_FEDEX_TO_SCHEDULE",
              },
            },
          },
        },
        name: "Shipping rate Auspost",
        group: "Shipping System",
      },
      {
        url: "https://int.ipsupply.com.au/api/transferPostData",
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: "Bearer " + tokenInt,
        },
        data: {
          urlAPI: "/api/logistics/check-shipping-rates",
          data: {
            courierName: "FRF",
            packageInfo: {
              from: {
                streetLines: ["8/4A Bachell Ave"],
                city: "Lidcombe",
                stateOrProvinceCode: "",
                postalCode: "2141",
                countryCode: "AU",
              },
              to: {
                streetLines: ["112 Munro St"],
                city: "South Melbourne",
                postalCode: "3205",
                countryCode: "AU",
              },
              requestedPackageLineItems: [
                {
                  weight: {
                    value: 10,
                    units: "KG",
                  },
                  dimensions: {
                    length: 2,
                    width: 3,
                    height: 4,
                    units: "CM",
                  },
                  groupPackageCount: 1,
                },
              ],
              commodities: [
                {
                  description: "G6",
                  quantity: 2,
                  quantityUnits: "PCS",
                  unitPrice: {
                    amount: 10000,
                    currency: "USD",
                  },
                  customsValue: {
                    amount: 10000,
                    currency: "USD",
                  },
                },
              ],
              inforCreateFedex: {
                pickupType: "CONTACT_FEDEX_TO_SCHEDULE",
              },
            },
          },
        },
        name: "Shipping rate FRF",
        group: "Shipping System",
      },
      {
        url: "https://int.ipsupply.com.au/api/transferPostData",
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: "Bearer " + tokenInt,
        },
        data: {
          urlAPI: "/api/logistics/check-shipping-rates",
          data: {
            courierName: "Sendle",
            packageInfo: {
              from: {
                streetLines: ["8/4A Bachell Ave"],
                city: "Lidcombe",
                stateOrProvinceCode: "",
                postalCode: "2141",
                countryCode: "AU",
              },
              to: {
                streetLines: ["112 Munro St"],
                city: "South Melbourne",
                postalCode: "3205",
                countryCode: "AU",
              },
              requestedPackageLineItems: [
                {
                  weight: {
                    value: 10,
                    units: "KG",
                  },
                  dimensions: {
                    length: 2,
                    width: 3,
                    height: 4,
                    units: "CM",
                  },
                  groupPackageCount: 1,
                },
              ],
              commodities: [
                {
                  description: "G6",
                  quantity: 2,
                  quantityUnits: "PCS",
                  unitPrice: {
                    amount: 10000,
                    currency: "USD",
                  },
                  customsValue: {
                    amount: 10000,
                    currency: "USD",
                  },
                },
              ],
              inforCreateFedex: {
                pickupType: "CONTACT_FEDEX_TO_SCHEDULE",
              },
            },
          },
        },
        name: "Shipping rate Sendle",
        group: "Shipping System",
      },
      {
        url: "https://int.ipsupply.com.au/api/transferPostData",
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: "Bearer " + tokenInt,
        },
        data: {
          urlAPI: "/api/logistics/check-tracking",
          data: {
            trackingNumber: "782568904960",
            type: "Fedex",
          },
        },
        name: "Tracking Fedex",
        group: "Shipping System",
      },
      {
        url: "https://int.ipsupply.com.au/api/transferPostData",
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: "Bearer " + tokenInt,
        },
        data: {
          urlAPI: "/api/logistics/check-tracking",
          data: {
            trackingNumber: "210865775",
            type: "TNT",
          },
        },
        name: "Tracking TNT",
        group: "Shipping System",
      },
      {
        url: "https://int.ipsupply.com.au/api/transferPostData",
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: "Bearer " + tokenInt,
        },
        data: {
          urlAPI: "/api/logistics/check-tracking",
          data: {
            trackingNumber: "1Z94VTP30308384260",
            type: "UPS",
          },
        },
        name: "Tracking UPS",
        group: "Shipping System",
      },
      {
        url: "https://int.ipsupply.com.au/api/transferPostData",
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: "Bearer " + tokenInt,
        },
        data: {
          urlAPI: "/api/logistics/check-tracking",
          data: {
            trackingNumber: "33FJV771376901000930306",
            type: "Auspost",
          },
        },
        name: "Tracking Auspost",
        group: "Shipping System",
      },
      {
        url: "https://int.ipsupply.com.au/api/transferPostData",
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: "Bearer " + tokenInt,
        },
        data: {
          urlAPI: "/api/logistics/check-tracking",
          data: {
            trackingNumber: "9400111206203073428144",
            type: "USPS",
          },
        },
        name: "Tracking USPS",
        group: "Shipping System",
      },
      {
        url: "https://int.ipsupply.com.au/api/transferPostData",
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: "Bearer " + tokenInt,
        },
        data: {
          urlAPI: "/api/logistics/check-tracking",
          data: {
            trackingNumber: "CVAZ00633255",
            type: "StarTrack",
          },
        },
        name: "Tracking StarTrack",
        group: "Shipping System",
      },
      {
        url: "https://int.ipsupply.com.au/api/transferPostData",
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: "Bearer " + tokenInt,
        },
        data: {
          urlAPI: "/api/logistics/check-tracking",
          data: {
            trackingNumber: "S92C5DS",
            type: "Sendle",
          },
        },
        name: "Tracking Sendle",
        group: "Shipping System",
      },
      {
        url: "https://int.ipsupply.com.au/api/transferPostData",
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: "Bearer " + tokenInt,
        },
        data: {
          urlAPI: "/api/logistics/check-tracking",
          data: {
            trackingNumber: "2334909695 ",
            type: "DHL",
          },
        },
        name: "Tracking DHL",
        group: "Shipping System",
      },
      {
        url: "https://int.ipsupply.com.au/api/transferPostData",
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: "Bearer " + tokenInt,
        },
        data: {
          urlAPI: "/api/logistics/check-tracking",
          data: {
            trackingNumber: "60508912001",
            type: "CouriersPlease",
          },
        },
        name: "Tracking CouriersPlease",
        group: "Shipping System",
      },
      //Other system
      {
        url: "https://int.ipsupply.com.au/api/transferPostData",
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: "Bearer " + tokenInt,
        },
        data: {
          urlAPI: "/api/stock-model-serial/check-sn-list-cisco",
          data: {
            serialNumbers: ["FGL1716W349"],
          },
        },
        name: "Check SN Cisco",
        group: "Other Systems",
      },
      {
        url: "ssh danielvu-gold@172.16.6.2 cat /home/danielvu-gold/htdocs/gold.danielvu.com/check_file.json",
        method: "EXEC",
        headers: {},
        data: {},
        name: "Perthmint",
        group: "Other Systems",
      },
      {
        url: "https://disti.danielvu.com/api/fileAutoImportLog",
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Accept: "application/json",
          loginid: null,
          Code: code,
          AccessToken: accessToken,
        },
        data: {},
        name: "Auto import Disti",
        group: "Other Systems",
      },
      //Test Log System
      {
        url: "nc -zv 172.16.7.13 8002",
        method: "EXEC",
        headers: {},
        data: {},
        name: "ATC to ERP",
        group: "Test Log System",
      },
      {
        url: "nc -zv 172.16.7.13 5000",
        method: "EXEC",
        headers: {},
        data: {},
        name: "ATC worked",
        group: "Test Log System",
      },
      {
        url: "nc -zv 172.16.6.23 7777",
        method: "EXEC",
        headers: {},
        data: {},
        name: "Read Test Log",
        group: "Test Log System",
      },
    ];

    const logicCheck = async (req, response) => {
      try {
        if (Array.isArray(response.data) === false) {
          if (
            (response.data.data !== undefined &&
              response.data.data.length > 0) ||
            (response.data !== undefined && response.data?.success)
          ) {
            report.push({
              group: req.group,
              name: req.name,
              status: ":check:",
              code: response.status,
              lengthOrData: response.data?.data?.length | response.data,
            });
          } else {
            if (response.data?.data !== undefined) {
              if (Array.isArray(response.data.data) === false) {
                const data = JSON.stringify(
                  response.data?.data
                )?.toLocaleLowerCase();
                if (
                  data?.includes("error") ||
                  data?.includes("invalid") ||
                  response.data.data === undefined
                ) {
                  report.push({
                    group: req.group,
                    name: req.name,
                    status: ":red_circle:",
                    code: response.status,
                    lengthOrData: JSON.stringify(response.data?.data),
                  });
                } else {
                  report.push({
                    group: req.group,
                    name: req.name,
                    status: ":check:",
                    code: response.status,
                    lengthOrData: response.data?.data?.length,
                  });
                }
              } else {
                if (
                  response.data?.data !== undefined &&
                  response.data?.data?.length > 0
                ) {
                  report.push({
                    group: req.group,
                    name: req.name,
                    status: ":check:",
                    code: response.status,
                    lengthOrData: response.data?.data?.length,
                  });
                } else {
                  report.push({
                    group: req.group,
                    name: req.name,
                    status: ":red_circle:",
                    code: response.status,
                    lengthOrData: JSON.stringify(response.data?.data),
                  });
                }
              }
            } else {
              const data = JSON.stringify(response.data)?.toLocaleLowerCase();
              if (
                data?.includes("error") ||
                data?.includes("invalid") ||
                response.data === undefined
              ) {
                report.push({
                  group: req.group,
                  name: req.name,
                  status: ":red_circle:",
                  code: response.status,
                  lengthOrData: JSON.stringify(response.data?.data),
                });
              } else {
                report.push({
                  group: req.group,
                  name: req.name,
                  status: ":check:",
                  code: response.status,
                  lengthOrData: response.data?.data?.length,
                });
              }
            }
          }
        } else {
          if (response.data.length > 0) {
            report.push({
              group: req.group,
              name: req.name,
              status: ":check:",
              code: response.status,
              lengthOrData: response.data.length,
            });
          } else {
            report.push({
              group: req.group,
              name: req.name,
              status: ":red_circle:",
              code: response.status,
              lengthOrData: response.data,
            });
          }
        }
      } catch (error) {
        console.log("logic check: ", error);
      }
    };

    const runExec = (command, name) => {
      return new Promise((resolve, reject) => {
        exec(command, (error, stdout, stderr) => {
          if (error) {
            reject(error);
          } else {
            if (name === "Test Log System") {
              if (stdout !== "") {
                resolve(stdout);
              } else {
                resolve(stderr);
              }
            } else {
              resolve(stdout);
            }
          }
        });
      });
    };

    const sortArray = (data) => {
      data.sort((a, b) => {
        if (a.group === b.group) {
          return a.name.localeCompare(b.name);
        }
        return a.group.localeCompare(b.group);
      });

      // Đưa group "Other Systems" xuống cuối
      data.sort((a, b) => {
        if (a.group === "Other Systems") return 1;
        if (b.group === "Other Systems") return -1;
        return 0;
      });

      return data;
    };

    const promises = requests.map(async (req, index) => {
      try {
        if (req.method === "POST") {
          let response = await axios.post(req.url, req.data, {
            headers: req.headers,
          });

          let responseDataString = JSON.stringify(response.data, null, 2);
          allResponse += `${req.name}\n${responseDataString}\n\n`;
          console.log(response.data);
          // Xử lý response ở đây
          // console.log("Response:", response.data.length);
          // console.log("Status:", response.status);

          if (response.data !== "" && response.data !== undefined) {
            if (req.name !== "Auto import Disti") {
              logicCheck(req, response);
            } else {
              console.log(response.data?.data?.length);
              if (response.data?.data?.length > 0) {
                response.data?.data?.map((u) => {
                  let name = req.name + " from " + u.data_name;
                  if (u.status === true) {
                    report.push({
                      group: req.group,
                      name: name,
                      status: ":check:",
                      code: "good",
                      lengthOrData: response.data?.data,
                    });
                  } else {
                    report.push({
                      group: req.group,
                      name: name,
                      status: ":red_circle:",
                      code: "fail",
                      lengthOrData: response.data?.data,
                    });
                  }
                });
              } else {
                report.push({
                  group: req.group,
                  name: req.name,
                  status: ":red_circle:",
                  code: "fail",
                  lengthOrData: response.data?.data,
                });
              }
            }
          } else {
            console.log("Error:", response);
            report.push({
              group: req.group,
              name: req.name,
              status: ":red_circle:",
              code: response.status,
              lengthOrData: "Error: " + JSON.stringify(response, null, 2),
            });
          }
          // .then((response) => {

          // })
          // .catch((error) => {
          //   // Xử lý lỗi ở đây
          //   console.log("Error:", error);
          //   report.push({
          //     group: req.group,
          //     name: req.name,
          //     status: ":red_circle:",
          //     code: response.status,
          //     lengthOrData: "Error: " + error,
          //   });
          // });
        }

        if (req.method === "GET") {
          let response = await axios.get(req.url, req.data, {
            headers: req.headers,
          });

          let responseDataString = JSON.stringify(response.data, null, 2);
          allResponse += `${req.name}\n${responseDataString}\n\n`;
          console.log(response.data);
          // Xử lý response ở đây
          // console.log("Response:", response.data.length);
          // console.log("Status:", response.status);

          if (response.data !== "" && response.data !== undefined) {
            if (req.name !== "Auto import Disti") {
              logicCheck(req, response);
            } else {
              console.log(response.data?.data?.length);
              if (response.data?.data?.length > 0) {
                response.data?.data?.map((u) => {
                  let name = req.name + " from " + u.data_name;
                  if (u.status === true) {
                    report.push({
                      group: req.group,
                      name: name,
                      status: ":check:",
                      code: "good",
                      lengthOrData: response.data?.data,
                    });
                  } else {
                    report.push({
                      group: req.group,
                      name: name,
                      status: ":red_circle:",
                      code: "fail",
                      lengthOrData: response.data?.data,
                    });
                  }
                });
              } else {
                report.push({
                  group: req.group,
                  name: req.name,
                  status: ":red_circle:",
                  code: "fail",
                  lengthOrData: response.data?.data,
                });
              }
            }
          } else {
            console.log("Error:", response);
            report.push({
              group: req.group,
              name: req.name,
              status: ":red_circle:",
              code: response.status,
              lengthOrData: "Error: " + JSON.stringify(response, null, 2),
            });
          }
        }

        if (req.method === "EXEC") {
          const stdout = await runExec(req.url, req.group);
          if (stdout !== "") {
            let responseDataString = JSON.stringify(stdout, null, 2);
            allResponse += `${req.name}\n${responseDataString}\n\n`;

            if (req.name === "Perthmint") {
              if (stdout.toString().split("true").length - 1 > 1) {
                report.push({
                  group: req.group,
                  name: req.name,
                  status: ":check:",
                  code: "good",
                  lengthOrData: stdout,
                });
              } else {
                report.push({
                  group: req.group,
                  name: req.name,
                  status: ":red_circle:",
                  code: "fail",
                  lengthOrData: stdout,
                });
              }
            }

            if (req.group === "Test Log System") {
              report.push({
                group: req.group,
                name: req.name,
                status: ":check:",
                code: "good",
                lengthOrData: stdout,
              });
            }
          } else {
            console.log(stdout);
            let responseDataString = JSON.stringify(stdout, null, 2);
            allResponse += `${req.name}\n${responseDataString}\n\n`;
            report.push({
              group: req.group,
              name: req.name,
              status: ":red_circle:",
              code: "fail",
              lengthOrData: stdout,
            });
          }
        }
      } catch (error) {
        console.log("Error:", error);
        report.push({
          group: req.group,
          name: req.name,
          status: ":red_circle:",
          code: "bad",
          lengthOrData: "Error: " + JSON.stringify(error, null, 2),
        });
      }
    });

    await Promise.all(promises);

    let groupName = sortArray(report)[0]?.group;
    let no = 0;
    content += "||:high_voltage:**" + groupName + "**|||\n";
    sortArray(report).map((u, index) => {
      no += 1;
      if (u.group === groupName) {
        content +=
          "|" + no + "|" + u.name + "|**" + time + "**|" + u.status + "|\n";
      } else {
        no = 1;
        groupName = u.group;
        content += "||:high_voltage:**" + groupName + "**|||\n";
        content +=
          "|" + no + "|" + u.name + "|**" + time + "**|" + u.status + "|\n";
      }
    });

    let params = {
      type: "stream",
      to: "Result test - auto.nswteam.net",
      topic: "AU-dev",
      content: content,
      // content: JSON.stringify(report, null, 2),
    };

    let params1 = {
      type: "stream",
      to: "System Logs",
      topic: "stream events",
      content: content,
    };

    client.messages.send(params);
    client.messages.send(params1);
    report.map((r) => {
      allResponse += JSON.stringify(r, null, 2);
    });
    const fileName =
      "./app/store/logsAPI/" +
      moment(Date.now()).format("DD_MM_YYYY").toString() +
      ".log";

    addLogFunction(fileName, allResponse, "System Logs")

    // fs.writeFileSync("/home/logs/logSystems.txt", allResponse);
    console.log(sortArray(report));
  } catch (error) {
    console.log(error);
    if (
      JSON.stringify(error).includes(
        "https://zulip.ipsupply.com.au/api/v1/messages failed"
      )
    ) {
      checkMultipleRequest();
    }
  }
};

checkMultipleRequest();
