/*
 * @Author:
 * @Date: 2024-01-04 15:04:20
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2024-03-13 17:30:17
 * @Description: tel files
 * @filePath:
 */
import axios from "axios";
import PublicLib from "./PublicLib";
import CryptoJS from "crypto-js";
const request = axios.create({
  // 请求超时时间
  timeout: 5000
});

// 加密函数
const encryptByDES = function (message) {
  const keyHex = CryptoJS.enc.Utf8.parse("&L^kg4N9");
  const ivHex = CryptoJS.enc.Utf8.parse("&L^kg4N9");
  const encrypted = CryptoJS.DES.encrypt(message, keyHex, {
    iv: ivHex,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7
  });
  return encrypted.toString();
};

// 请求方法
const postRequest = (url, params) => {
  console.log("请求参数:", params);
  const param = new URLSearchParams();
  param.append("value", encryptByDES(JSON.stringify(params)));
  return request({
    url,
    method: "post",
    headers: {
      "Content-Type": "application/x-www-form-urlencoded"
    },
    data: param
  });
};

// 更新本地URL列表
const putURL = list => {
  PublicLib.putCookieInfo({
    Key: "URL_INTERFACE",
    Value: list,
    Type: 3,
    Conf: { dbname: "PROJECT_INTERFACE", version: 1, table: "INTERFACE_List" }
  });
};

// 获取本地URL列表
const getURL = () => {
  return PublicLib.getCookieInfo({
    Key: "URL_INTERFACE",
    Type: 3,
    Conf: { dbname: "PROJECT_INTERFACE", version: 1, table: "INTERFACE_List" }
  });
};

// URL列表资源
const getAllPlate = () => {
  return new Promise(async (resolve, reject) => {
    postRequest(
      "http://localhost:5800/noauth/api/groupsforadmin",
      {
        key: "tel#2024"
      }
    )
      .then(async res => {
        resolve(res.data.data);
      })
      .catch(err => {
        throw Error(err);
      });
  });
};

// 比对版本号且做更新
const getGroupUrl = async (checkPlate = []) => {
  return new Promise(async (resolve, reject) => {
    const URLLIST = (await getURL()) || {};
    const parameters = { userId: 1, groups: [] };
    if (checkPlate.length == 0) {
      checkPlate = await getAllPlate();
    }
    parameters.groups = checkPlate.map(item => {
      return {
        name: item,
        version: URLLIST && URLLIST[item] ? URLLIST[item].groupVersion : 0
      };
    });
    const timer = setTimeout(() => {
      resolve(URLLIST);
      throw Error(
        "GET URLLIST FAIL, BECAUSE INTERFACE IS TIMEOUT, NOW RETURN LOCAL URLLIST"
      );
    }, 5000);
    postRequest(
      "http://localhost:5800/noauth/api/listforadmin",
      parameters
    )
      .then(async res => {
        clearTimeout(timer);
        if (Object.keys(URLLIST).length === 0) {
          putURL(res.data.data);
          resolve(res.data.data);
        } else {
          if (res.data.status == "1") {
            // 全部接口循环读取更新
            const onlineurl = res.data.data;
            for (const key in onlineurl) {
              if (
                URLLIST[key] &&
                onlineurl[key].groupVersion > URLLIST[key].groupVersion
              ) {
                URLLIST[key] = onlineurl[key];
                console.log("更新列表:", key);
                putURL(URLLIST);
              }
            }
            resolve(URLLIST);
          } else {
            resolve(URLLIST);
            throw Error(
              "GET URLLIST FAIL, BECAUSE INTERFACE STATUS IS ERROR, NOW RETURN LOCAL URLLIST"
            );
          }
        }
      })
      .catch(err => {
        resolve(URLLIST);
        throw Error(err);
      });
  });
};

export { getGroupUrl };
