import bigDecimal from "@/utils/bigDecimal";

/**
 * @description  分钟转时间
 * @author
 * @date
 * @param
 * @returns
 */
export function formatMinutes(minutes) {
  let tiemInfo = Number(minutes);
  var time = [];
  var day = parseInt(tiemInfo / 60 / 24);
  var hour = parseInt((tiemInfo / 60) % 24);
  var min = parseInt(tiemInfo % 60);
  time[0] = day > 0 ? day : 0;
  time[1] = hour > 0 ? hour : 0;
  time[2] = min > 0 ? parseFloat(min) : 0;
  return time;
}
/**
 * @description  时间转分钟
 * @author
 * @date
 * @param
 * @returns
 */
export function totalMinutes(day, hour, minute) {
  return day * 1440 + hour * 60 + minute;
}
/**
 * @description 数组指定必填项判断校验
 * @author   // arr要判断的数组  data要判断里面那些不能为空的字段
 * @date
 * @param
 * @returns
 */
export function everyI(arr, data, text) {
  let flag = arr.flatMap((item) => {
    let flag1 = data.flatMap((key) => {
      if (text == "不校验零") {
        if (item[key] || item[key] == 0) {
          return true;
        } else {
          false;
        }
      } else {
        if (item[key]) {
          return true;
        } else {
          false;
        }
      }
    });
    return flag1;
  });
  // 如果不只条的时候全部都要填写  every只要有一个不满足就不让走  smoe只要有一个满足就可以走
  let info = flag.every((val) => val);
  return info;
}
/**
 * @description 找下对应的字段显示上去  arr1枚举表 arr2对比数组  text取出的字段
 * @author cl
 * @date 2022-2-17
 * @param
 * @returns
 */
export function getArr(arr1, arr2, text) {
  let arrInfo = [];
  if (!arr2) return;
  arr1.map((item) => {
    arr2.split(",").map((n) => {
      if (n == item.value) {
        arrInfo.push(item[text]);
      }
    });
  });
  return arrInfo.join(",");
}
/**
 * @description
 * @author cl
 * @date 2022-2-18
 * @param arr要计算的数组数据  Array
 * @param num2要计算的价格字段  string
 * @param arr2要合并计算总价的数据  string
 * @param currency优惠券的币种字段  Array
 * @param currency要减去的优惠券币种字段  string
 * @param amount要减去的优惠券价格字段  string
 * @returns
 */
export function getPriceI(arr, num1, num2, arr2, currency, amount) {
  let arrInfo = arr2 ? arr2 : []; // 总计
  let currencyInfo = currency; // 优惠券币种
  let amountInfo = amount ? amount : 0; // 优惠价钱
  let price = {
    USD: 0,
    CNY: 0,
  };
  arr.concat(arrInfo).flatMap((i) => {
    if (i[num1] == "USD") {
      price.USD = Number(bigDecimal.add(price.USD, i[num2]));
    } else {
      price.CNY = Number(bigDecimal.add(price.CNY, i[num2]));
    }
  });
  // 有优惠卷的话减去优惠间
  if (currencyInfo === "CNY") {
    price.CNY = Number(bigDecimal.subtract(price.CNY, amountInfo));
  } else {
    price.USD = Number(bigDecimal.subtract(price.USD, amountInfo));
  }

  let arrI = [
    price.USD > 0 ? "USD：" + format_with_array(price.USD) : "USD：0.00",
    price.CNY > 0 ? "CNY：" + format_with_array(price.CNY) : "CNY：0.00",
  ]
    .filter((current) => {
      return current !== "USD：0.00" && current !== "CNY：0.00";
    })
    .join(" + ");
  return arrI;
}
/**
 * @description 数组字段拼接回调法
 * @author cl
 * @date 2022-12-9
 * @param
 * @returns
 */
export function _getArr(arr, name, id, child) {
  arr.forEach((item, index) => {
    // 作为键值对
    item.label = item[name];
    item.value = item[id];
    if (item.children) {
      _getArr(item.children, name, id);
    }
  });
  return arr;
}
/**
 * 防抖原理：一定时间内，只有最后一次操作，再过wait毫秒后才执行函数
 *
 * @param {Function} func 要执行的回调函数
 * @param {Number} wait 延时的时间
 * @param {Boolean} immediate 是否立即执行
 * @return null
 */
let timeout = null;
export function debounce(func, wait = 300, immediate = false) {
  // 清除定时器
  if (timeout !== null) clearTimeout(timeout);
  // 立即执行，此类情况一般用不到
  if (immediate) {
    const callNow = !timeout;
    timeout = setTimeout(() => {
      timeout = null;
    }, wait);
    if (callNow) typeof func === "function" && func();
  } else {
    // 设置定时器，当最后一次操作后，timeout不会再被清除，所以在延时wait毫秒后执行func回调方法
    timeout = setTimeout(() => {
      typeof func === "function" && func();
    }, wait);
  }
}
/**
 * @description 去重对比后去除已存在的替换  arrA已经选择的 arrB数据源  text去重的标识字段  type类型
 * @author cl
 * @date 2022-12-9
 * @param
 * @returns
 */
export function processI(arrA, arrB, text) {
  // 缓存用于记录
  const cache = [];
  for (const t of arrB) {
    // 检查缓存中是否已经存在
    if (arrA.find((c) => c[text] === t[text])) {
      // 已经存在说明以前记录过，现在这个就是多余的，直接忽略
      continue;
    }
    // 不存在就说明以前没遇到过，把它记录下来
    cache.push(t);
  }
  return cache;
}
/**
 * @description 去重去除已存在的   typeName类型标记
 * @author cl
 * @date 2022-2-17
 * @param
 * @returns
 */
export function duplicate(arr1, arr2, text, typeName, type) {
  arr1.map((item) => {
    // 检查缓存中是否已经存在
    if (arr2.find((c) => c[text] == item[text])) {
      // 已经存在说明以前记录过，现在这个就是多余的，直接忽略
      return;
    }
    // 不存在就说明以前没遇到过，把它记录下来
    if (typeName) {
      item[typeName] = type;
      arr2.push(item);
    } else {
      arr2.push(item);
    }
  });
  return arr2;
}
/**
 * 手机号格式化
 * @param {string | number} mobile 手机号
 * @returns '188 8888 8888'格式的手机号
 */

export function formatMobile(mobile) {
  const regMobile = /^1\d{10}/;
  if (!regMobile.test(mobile)) {
    return "";
  }
  return String(mobile).replace(/(^\d{3}|\d{4}\B)/g, "$1 ");
}
/**
 * @description 复制
 * @param {*} id DOM ID
 */
export function copyDomText(id) {
  const node = document.getElementById(id);
  if (node) {
    let createRange = document.createRange();
    createRange.selectNodeContents(document.getElementById(id));
    const selection = document.getSelection();
    selection.removeAllRanges();
    selection.addRange(createRange);
    document.execCommand("Copy");
    selection.removeAllRanges();
  }
}

/**
 * 金额 千分位
 * @param { number} mobile 金额
 * @returns '12,300,000' 金额格式
 */
export function format_with_array(
  number,
  decimals,
  dec_point,
  thousands_sep,
  round_tag
) {
  number = (number + "").replace(/[^0-9+-Ee.]/g, "");
  decimals = decimals || 2; //默认保留2位
  dec_point = dec_point || "."; //默认是'.';
  thousands_sep = thousands_sep || ","; //默认是',';
  round_tag = round_tag || "round"; //默认是四舍五入
  var n = !isFinite(+number) ? 0 : +number,
    prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
    sep = typeof thousands_sep === "undefined" ? "," : thousands_sep,
    dec = typeof dec_point === "undefined" ? "." : dec_point,
    s = "",
    toFixedFix = function (n, prec) {
      var k = Math.pow(10, prec);

      return (
        "" +
        parseFloat(
          Math[round_tag](parseFloat((n * k).toFixed(prec * 2))).toFixed(
            prec * 2
          )
        ) /
          k
      );
    };
  s = (prec ? toFixedFix(n, prec) : "" + Math.round(n)).split(".");
  var re = /(-?\d+)(\d{3})/;
  while (re.test(s[0])) {
    s[0] = s[0].replace(re, "$1" + sep + "$2");
  }
  if ((s[1] || "").length < prec) {
    s[1] = s[1] || "";
    s[1] += new Array(prec - s[1].length + 1).join("0");
  }
  return "￥" + s.join(dec);
}

// 获取两个时间段内的所有日期/月份 日   传入 YYYY-MM , YYYY-MM  (2020-09)  (2020-12)  返回 YYYY-MM 数组
export function getAllDay(start, end) {
  let result = [];
  let min = new Date(start);
  let max = new Date(end);
  let curr = min;
  do {
    let month = new Date(curr).getMonth() + 1;
    let t = "";
    if (month < 10) {
      t = "0" + month;
    } else t = month;
    let str = curr.getFullYear() + "-" + t;
    result.push(str);
    if (month == 12) {
      curr.setFullYear(new Date(curr).getFullYear() + 1);
      curr.setMonth(0);
    } else curr.setMonth(month);
  } while (curr <= max);

  return result;
}

// 日期格式化
export function parseTime(time, pattern) {
  if (arguments.length === 0 || !time) {
    return null;
  }
  const format = pattern || "{y}-{m}-{d} {h}:{i}:{s}";
  let date;
  if (typeof time === "object") {
    date = time;
  } else {
    if (typeof time === "string" && /^[0-9]+$/.test(time)) {
      time = parseInt(time);
    } else if (typeof time === "string") {
      time = time
        .replace(new RegExp(/-/gm), "/")
        .replace("T", " ")
        .replace(new RegExp(/\.[\d]{3}/gm), "");
    }
    if (typeof time === "number" && time.toString().length === 10) {
      time = time * 1000;
    }
    date = new Date(time);
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay(),
  };
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key];
    // Note: getDay() returns 0 on Sunday
    if (key === "a") {
      return ["日", "一", "二", "三", "四", "五", "六"][value];
    }
    if (result.length > 0 && value < 10) {
      value = "0" + value;
    }
    return value || 0;
  });
  return time_str;
}

// 表单重置
export function resetForm(refName) {
  if (this.$refs[refName]) {
    this.$refs[refName].resetFields();
  }
}

// 添加日期范围
export function addDateRange(params, dateRange, propName) {
  let search = params;
  search.params =
    typeof search.params === "object" &&
    search.params !== null &&
    !Array.isArray(search.params)
      ? search.params
      : {};
  dateRange = Array.isArray(dateRange) ? dateRange : [];
  if (typeof propName === "undefined") {
    search.params["beginTime"] = dateRange[0];
    search.params["endTime"] = dateRange[1];
  } else {
    search.params["begin" + propName] = dateRange[0];
    search.params["end" + propName] = dateRange[1];
  }
  return search;
}

// 回显数据字典
export function selectDictLabel(datas, value) {
  if (value === undefined) {
    return "";
  }
  var actions = [];
  Object.keys(datas).some((key) => {
    if (datas[key].value == "" + value) {
      actions.push(datas[key].label);
      return true;
    }
  });
  if (actions.length === 0) {
    actions.push(value);
  }
  return actions.join("");
}

// 回显数据字典（字符串数组）
export function selectDictLabels(datas, value, separator) {
  if (value === undefined || value.length === 0) {
    return "";
  }
  if (Array.isArray(value)) {
    value = value.join(",");
  }
  var actions = [];
  var currentSeparator = undefined === separator ? "," : separator;
  var temp = value.split(currentSeparator);
  Object.keys(value.split(currentSeparator)).some((val) => {
    var match = false;
    Object.keys(datas).some((key) => {
      if (datas[key].value == "" + temp[val]) {
        actions.push(datas[key].label + currentSeparator);
        match = true;
      }
    });
    if (!match) {
      actions.push(temp[val] + currentSeparator);
    }
  });
  return actions.join("").substring(0, actions.join("").length - 1);
}

// 字符串格式化(%s )
export function sprintf(str) {
  var args = arguments,
    flag = true,
    i = 1;
  str = str.replace(/%s/g, function () {
    var arg = args[i++];
    if (typeof arg === "undefined") {
      flag = false;
      return "";
    }
    return arg;
  });
  return flag ? str : "";
}

// 转换字符串，undefined,null等转化为""
export function parseStrEmpty(str) {
  if (!str || str == "undefined" || str == "null") {
    return "";
  }
  return str;
}

// 数据合并
export function mergeRecursive(source, target) {
  for (var p in target) {
    try {
      if (target[p].constructor == Object) {
        source[p] = mergeRecursive(source[p], target[p]);
      } else {
        source[p] = target[p];
      }
    } catch (e) {
      source[p] = target[p];
    }
  }
  return source;
}

/**
 * 构造树型结构数据
 * @param {*} data 数据源
 * @param {*} id id字段 默认 'id'
 * @param {*} parentId 父节点字段 默认 'parentId'
 * @param {*} children 孩子节点字段 默认 'children'
 */
export function handleTree(data, id, parentId, children) {
  let config = {
    id: id || "id",
    parentId: parentId || "parentId",
    childrenList: children || "children",
  };

  var childrenListMap = {};
  var nodeIds = {};
  var tree = [];

  for (let d of data) {
    let parentId = d[config.parentId];
    if (childrenListMap[parentId] == null) {
      childrenListMap[parentId] = [];
    }
    nodeIds[d[config.id]] = d;
    childrenListMap[parentId].push(d);
  }

  for (let d of data) {
    let parentId = d[config.parentId];
    if (nodeIds[parentId] == null) {
      tree.push(d);
    }
  }

  for (let t of tree) {
    adaptToChildrenList(t);
  }

  function adaptToChildrenList(o) {
    if (childrenListMap[o[config.id]] !== null) {
      o[config.childrenList] = childrenListMap[o[config.id]];
    }
    if (o[config.childrenList]) {
      for (let c of o[config.childrenList]) {
        adaptToChildrenList(c);
      }
    }
  }
  return tree;
}

/**
 * 参数处理
 * @param {*} params  参数
 */
export function tansParams(params) {
  let result = "";
  for (const propName of Object.keys(params)) {
    const value = params[propName];
    var part = encodeURIComponent(propName) + "=";
    if (value !== null && value !== "" && typeof value !== "undefined") {
      if (typeof value === "object") {
        for (const key of Object.keys(value)) {
          if (
            value[key] !== null &&
            value[key] !== "" &&
            typeof value[key] !== "undefined"
          ) {
            let params = propName + "[" + key + "]";
            var subPart = encodeURIComponent(params) + "=";
            result += subPart + encodeURIComponent(value[key]) + "&";
          }
        }
      } else {
        result += part + encodeURIComponent(value) + "&";
      }
    }
  }
  return result;
}

// 返回项目路径
export function getNormalPath(p) {
  if (p.length === 0 || !p || p == "undefined") {
    return p;
  }
  let res = p.replace("//", "/");
  if (res[res.length - 1] === "/") {
    return res.slice(0, res.length - 1);
  }
  return res;
}

// 验证是否为blob格式
export function blobValidate(data) {
  return data.type !== "application/json";
}

// 处理图片格式
export function disposeImage(primary, type = false) {
  if (primary && (primary.length || !Array.isArray(primary))) {
    let imgValue = null;
    if (Array.isArray(primary)) {
      imgValue = [];
      primary.forEach((item) => {
        if (
          (typeof item == "string" && type) ||
          (item.url && item.uuid && !type)
        ) {
          imgValue.push(item);
        } else {
          if (type) {
            if (item.prefix && item.path) {
              imgValue.push(item.prefix + item.path);
            } else {
              imgValue.push(item.url);
            }
          } else {
            imgValue.push({
              name: item.name,
              url: item.prefix + item.path,
              uuid: item.fileId,
            });
          }
        }
      });
    } else {
      if (
        (typeof primary == "string" && type) ||
        (primary.url && primary.uuid && !type)
      ) {
        imgValue = primary;
      } else {
        if (type) {
          if (primary.prefix && primary.path) {
            imgValue = primary.prefix + primary.path;
          } else {
            imgValue = primary.url;
          }
        } else {
          imgValue = {
            name: primary.name,
            url: primary.prefix + primary.path,
            uuid: primary.fileId,
          };
        }
      }
    }
    return imgValue;
  } else {
    return [];
  }
}

// 处理图片格式
export function getImage(primary) {
  if (primary && primary.length) {
    let imgArr = [];
    primary.forEach((item) => {
      imgArr.push(item.uuid);
    });
    return imgArr.toString();
  } else {
    return "";
  }
}

export function getUrl(url) {
  return new Promise((resolve, reject) => {
    getFileMessage({ fileId: url })
      .then((res) => {
        resolve(disposeImage(res.data));
      })
      .catch((row) => {
        ElMessage({
          message: "图片获取错误" + row,
          type: "error",
          duration: 5 * 1000,
        });
        reject(false);
      });
  });
}

// 获取图片详情
export async function getImageMessage(url, type = false) {
  if (!url || (Array.isArray(url) && !url.length)) {
  } else {
    let uuidList = null;
    if (typeof url == "string" || typeof url == "number") {
      uuidList = url.toString().split(",");
    } else if (Array.isArray(url)) {
      uuidList = url;
    }
    let imgurl = [];
    for (const item in uuidList) {
      const url = await getUrl(uuidList[item]);
      if (url) {
        if (type) {
          imgurl.push(url);
        } else {
          imgurl.push(url.url);
        }
      } else {
        imgurl.push(img);
      }
    }
    return imgurl;
  }
}

// 克隆
export function deepClone(obj) {
  if (obj === null || typeof obj !== "object") {
    // 如果 obj 是 null 或不是对象，则直接返回 obj
    return obj;
  }

  if (Array.isArray(obj)) {
    // 如果 obj 是数组
    const clonedArray = [];
    for (let i = 0; i < obj.length; i++) {
      // 递归克隆数组中的每个元素
      clonedArray[i] = deepClone(obj[i]);
    }
    return clonedArray;
  }

  // 如果 obj 是普通对象
  const clonedObj = {};
  for (let key in obj) {
    if (obj.hasOwnProperty(key)) {
      // 递归克隆对象的每个属性
      clonedObj[key] = deepClone(obj[key]);
    }
  }
  return clonedObj;
}

// 数组去重
export function removeDuplicate(arr) {
  const newArr = [];
  arr.forEach((item) => {
    if (newArr.indexOf(item) === -1) {
      newArr.push(item);
    }
  });
  return newArr; // 返回一个新数组
}


export function createThrottle(func, delay){
    let timeoutId;
    let lastExecTime = 0;
    
    return (...args) => {
        const currentTime = Date.now();
        
        // 立即执行第一次
        if (currentTime - lastExecTime > delay) {
            func.apply(this, args);
            lastExecTime = currentTime;
        } else {
            // 清除之前的定时器，设置新的定时器
            clearTimeout(timeoutId);
            timeoutId = setTimeout(() => {
                func.apply(this, args);
                lastExecTime = Date.now();
            }, delay);
        }
    };
};