
import store from "@/store";
/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */
export function parseTime(time, cFormat) {
  if (arguments.length === 0) {
    return null
  }
  const format = cFormat || '{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)
    }
    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(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
    return value.toString().padStart(2, '0')
  })
  return time_str
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function param2Obj(url) {
  const search = url.split('?')[1]
  if (!search) {
    return {}
  }
  return JSON.parse(
    '{"' +
    decodeURIComponent(search)
      .replace(/"/g, '\\"')
      .replace(/&/g, '","')
      .replace(/=/g, '":"')
      .replace(/\+/g, ' ') +
    '"}'
  )
}

export function deepClone(source, map = new WeakMap()) {
  // 处理基本类型和函数（直接返回）
  if (typeof source !== 'object' || source === null) {
    return source;
  }

  // 处理循环引用
  if (map.has(source)) {
    return map.get(source);
  }

  // 创建新容器
  const target = Array.isArray(source) ? [] : {};
  map.set(source, target);  // 记录克隆关系

  // 克隆普通键值
  for (const key in source) {
    if (Object.prototype.hasOwnProperty.call(source, key)) {
      target[key] = deepClone(source[key], map);
    }
  }

  // 克隆Symbol键值（ES6+）
  const symbolKeys = Object.getOwnPropertySymbols(source);
  for (const symKey of symbolKeys) {
    if (source.propertyIsEnumerable(symKey)) {
      target[symKey] = deepClone(source[symKey], map);
    }
  }

  return target;
}
export function formatSize(size, fixed = 2) {
  if (isNaN(parseFloat(size))) return ''
  let kbSize = size / 1024
  if (kbSize <= 1024) {
    return `${kbSize.toFixed(fixed)}KB`
  }
  let mbSize = kbSize / 1024
  return `${mbSize.toFixed(fixed)}MB`
}

let timer = null,  // 网速定时器
  lastPercentage = 0,
  percentageById = {},
  imageId = null,
  bytesReceivedPerSecond = {}; // 时间节点上传文件总量
// 获取网速
export function getNetWorkSpeed() {
  if (timer) return false;
  // if (lastPercentage < 100) return false;
  if (imageId && imageId !== Id) return false
  imageId = null
  timer = setInterval(() => {
    let timeList = Object.keys(bytesReceivedPerSecond).sort((a, b) => a - b);
    if (timeList.length > 0) {
      let totalBytes = timeList.reduce((sum, bytes) => sum + bytesReceivedPerSecond[bytes], 0) / (5 * 1024);
      let unit = 'KB/s';
      if (totalBytes > 1024) {
        totalBytes = totalBytes / 1024;
        unit = "MB/s";
      }
      store.state.trials.uploadTip = totalBytes.toFixed(3) + unit;
    }
    if (timeList.length >= 5) {
      delete bytesReceivedPerSecond[timeList[0]]
    }
    let time = new Date().getTime();
    bytesReceivedPerSecond[time] = 0;
  }, 1000)

}
export function setNetWorkSpeedSize(totalPercentage, total, Id) {
  if (imageId && imageId !== Id) return false
  imageId = Id
  let percentage = totalPercentage - lastPercentage
  percentage = percentage / 100
  lastPercentage = totalPercentage
  // console.log(percentage, totalPercentage, total)
  let time = new Date().getTime();
  let timeList = Object.keys(bytesReceivedPerSecond).sort((a, b) => a - b);
  let bytesTime = timeList.find(item => time - item < 1000);
  if (bytesTime) {
    bytesReceivedPerSecond[bytesTime] += total * percentage;
  } else {
    // console.log("未查询到时间")
    if (timeList.length > 0) {
      bytesReceivedPerSecond[timeList[timeList.length - 1]] += total * percentage;
    } else {
      bytesReceivedPerSecond[time] = total * percentage;
    }
  }
  store.state.trials.uploadSize = `${formatSize(totalPercentage / 100 * total)}/${formatSize(total)}`
}
export function setNetWorkSpeedSizeAll(totalPercentage, total, Id) {
  if (!percentageById[Id]) {
    percentageById[Id] = 0
  }
  let percentage = totalPercentage - percentageById[Id]
  percentage = percentage / 100
  percentageById[Id] = totalPercentage
  // console.log(percentage, totalPercentage, total)
  let time = new Date().getTime();
  let timeList = Object.keys(bytesReceivedPerSecond).sort((a, b) => a - b);
  let bytesTime = timeList.find(item => time - item < 1000);
  if (bytesTime) {
    bytesReceivedPerSecond[bytesTime] += total * percentage;
  } else {
    // console.log("未查询到时间")
    if (timeList.length > 0) {
      bytesReceivedPerSecond[timeList[timeList.length - 1]] += total * percentage;
    } else {
      bytesReceivedPerSecond[time] = total * percentage;
    }
  }
  let isComplete = Object.keys(percentageById).every(key => percentageById[key >= 100])
  if (isComplete) {
    workSpeedclose(true)
  }
}
export function workSpeedclose(isForce = false) {
  if (!isForce && lastPercentage < 100) {
    return false
  }
  console.log('workSpeedclose')
  if (timer) {
    clearInterval(timer);
    timer = null;
    store.state.trials.uploadTip = '0KB/s'
    store.state.trials.uploadSize = ''
  }
  bytesReceivedPerSecond = {};
  lastPercentage = 0;
  imageId = null;
  percentageById = {};
}