import { parseTime } from "./ruoyi";
import { ElMessage } from "element-plus";

/**
 * 表格时间格式化
 */
export function formatDate(cellValue) {
  if (cellValue == null || cellValue == "") return "";
  var date = new Date(cellValue);
  var year = date.getFullYear();
  var month =
    date.getMonth() + 1 < 10
      ? "0" + (date.getMonth() + 1)
      : date.getMonth() + 1;
  var day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
  var hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
  var minutes =
    date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
  var seconds =
    date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
  return (
    year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds
  );
}

/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time, option) {
  if (("" + time).length === 10) {
    time = parseInt(time) * 1000;
  } else {
    time = +time;
  }
  const d = new Date(time);
  const now = Date.now();

  const diff = (now - d) / 1000;

  if (diff < 30) {
    return "刚刚";
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + "分钟前";
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + "小时前";
  } else if (diff < 3600 * 24 * 2) {
    return "1天前";
  }
  if (option) {
    return parseTime(time, option);
  } else {
    return (
      d.getMonth() +
      1 +
      "月" +
      d.getDate() +
      "日" +
      d.getHours() +
      "时" +
      d.getMinutes() +
      "分"
    );
  }
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function getQueryObject(url) {
  url = url == null ? window.location.href : url;
  const search = url.substring(url.lastIndexOf("?") + 1);
  const obj = {};
  const reg = /([^?&=]+)=([^?&=]*)/g;
  search.replace(reg, (rs, $1, $2) => {
    const name = decodeURIComponent($1);
    let val = decodeURIComponent($2);
    val = String(val);
    obj[name] = val;
    return rs;
  });
  return obj;
}

/**
 * @param {string} input value
 * @returns {number} output value
 */
export function byteLength(str) {
  // returns the byte length of an utf8 string
  let s = str.length;
  for (var i = str.length - 1; i >= 0; i--) {
    const code = str.charCodeAt(i);
    if (code > 0x7f && code <= 0x7ff) s++;
    else if (code > 0x7ff && code <= 0xffff) s += 2;
    if (code >= 0xdc00 && code <= 0xdfff) i--;
  }
  return s;
}

/**
 * @param {Array} actual
 * @returns {Array}
 */
export function cleanArray(actual) {
  const newArray = [];
  for (let i = 0; i < actual.length; i++) {
    if (actual[i]) {
      newArray.push(actual[i]);
    }
  }
  return newArray;
}

/**
 * @param {Object} json
 * @returns {Array}
 */
export function param(json) {
  if (!json) return "";
  return cleanArray(
    Object.keys(json).map((key) => {
      if (json[key] === undefined) return "";
      return encodeURIComponent(key) + "=" + encodeURIComponent(json[key]);
    })
  ).join("&");
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function param2Obj(url) {
  const search = decodeURIComponent(url.split("?")[1]).replace(/\+/g, " ");
  if (!search) {
    return {};
  }
  const obj = {};
  const searchArr = search.split("&");
  searchArr.forEach((v) => {
    const index = v.indexOf("=");
    if (index !== -1) {
      const name = v.substring(0, index);
      const val = v.substring(index + 1, v.length);
      obj[name] = val;
    }
  });
  return obj;
}

/**
 * @param {string} val
 * @returns {string}
 */
export function html2Text(val) {
  const div = document.createElement("div");
  div.innerHTML = val;
  return div.textContent || div.innerText;
}

/**
 * Merges two objects, giving the last one precedence
 * @param {Object} target
 * @param {(Object|Array)} source
 * @returns {Object}
 */
export function objectMerge(target, source) {
  if (typeof target !== "object") {
    target = {};
  }
  if (Array.isArray(source)) {
    return source.slice();
  }
  Object.keys(source).forEach((property) => {
    const sourceProperty = source[property];
    if (typeof sourceProperty === "object") {
      target[property] = objectMerge(target[property], sourceProperty);
    } else {
      target[property] = sourceProperty;
    }
  });
  return target;
}

/**
 * @param {HTMLElement} element
 * @param {string} className
 */
export function toggleClass(element, className) {
  if (!element || !className) {
    return;
  }
  let classString = element.className;
  const nameIndex = classString.indexOf(className);
  if (nameIndex === -1) {
    classString += "" + className;
  } else {
    classString =
      classString.substr(0, nameIndex) +
      classString.substr(nameIndex + className.length);
  }
  element.className = classString;
}

/**
 * @param {string} type
 * @returns {Date}
 */
export function getTime(type) {
  if (type === "start") {
    return new Date().getTime() - 3600 * 1000 * 24 * 90;
  } else {
    return new Date(new Date().toDateString());
  }
}

/**
 * @param {Function} func
 * @param {number} wait
 * @param {boolean} immediate
 * @return {*}
 */
export function debounce(func, wait, immediate) {
  let timeout, args, context, timestamp, result;

  const later = function () {
    // 据上一次触发时间间隔
    const last = +new Date() - timestamp;

    // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
    if (last < wait && last > 0) {
      timeout = setTimeout(later, wait - last);
    } else {
      timeout = null;
      // 如果设定为immediate===true，因为开始边界已经调用过了此处无需调用
      if (!immediate) {
        result = func.apply(context, args);
        if (!timeout) context = args = null;
      }
    }
  };

  return function (...args) {
    context = this;
    timestamp = +new Date();
    const callNow = immediate && !timeout;
    // 如果延时不存在，重新设定延时
    if (!timeout) timeout = setTimeout(later, wait);
    if (callNow) {
      result = func.apply(context, args);
      context = args = null;
    }

    return result;
  };
}

/**
 * This is just a simple version of deep copy
 * Has a lot of edge cases bug
 * If you want to use a perfect deep copy, use lodash's _.cloneDeep
 * @param {Object} source
 * @returns {Object}
 */
export function deepClone(source) {
  if (!source && typeof source !== "object") {
    throw new Error("error arguments", "deepClone");
  }
  const targetObj = source.constructor === Array ? [] : {};
  Object.keys(source).forEach((keys) => {
    if (source[keys] && typeof source[keys] === "object") {
      targetObj[keys] = deepClone(source[keys]);
    } else {
      targetObj[keys] = source[keys];
    }
  });
  return targetObj;
}

/**
 * @param {Array} arr
 * @returns {Array}
 */
export function uniqueArr(arr) {
  return Array.from(new Set(arr));
}

/**
 * @returns {string}
 */
export function createUniqueString() {
  const timestamp = +new Date() + "";
  const randomNum = parseInt((1 + Math.random()) * 65536) + "";
  return (+(randomNum + timestamp)).toString(32);
}

/**
 * Check if an element has a class
 * @param {HTMLElement} elm
 * @param {string} cls
 * @returns {boolean}
 */
export function hasClass(ele, cls) {
  return !!ele.className.match(new RegExp("(\\s|^)" + cls + "(\\s|$)"));
}

/**
 * Add class to element
 * @param {HTMLElement} elm
 * @param {string} cls
 */
export function addClass(ele, cls) {
  if (!hasClass(ele, cls)) ele.className += " " + cls;
}

/**
 * Remove class from element
 * @param {HTMLElement} elm
 * @param {string} cls
 */
export function removeClass(ele, cls) {
  if (hasClass(ele, cls)) {
    const reg = new RegExp("(\\s|^)" + cls + "(\\s|$)");
    ele.className = ele.className.replace(reg, " ");
  }
}

export function makeMap(str, expectsLowerCase) {
  const map = Object.create(null);
  const list = str.split(",");
  for (let i = 0; i < list.length; i++) {
    map[list[i]] = true;
  }
  return expectsLowerCase ? (val) => map[val.toLowerCase()] : (val) => map[val];
}

export const exportDefault = "export default ";

export const beautifierConf = {
  html: {
    indent_size: "2",
    indent_char: " ",
    max_preserve_newlines: "-1",
    preserve_newlines: false,
    keep_array_indentation: false,
    break_chained_methods: false,
    indent_scripts: "separate",
    brace_style: "end-expand",
    space_before_conditional: true,
    unescape_strings: false,
    jslint_happy: false,
    end_with_newline: true,
    wrap_line_length: "110",
    indent_inner_html: true,
    comma_first: false,
    e4x: true,
    indent_empty_lines: true,
  },
  js: {
    indent_size: "2",
    indent_char: " ",
    max_preserve_newlines: "-1",
    preserve_newlines: false,
    keep_array_indentation: false,
    break_chained_methods: false,
    indent_scripts: "normal",
    brace_style: "end-expand",
    space_before_conditional: true,
    unescape_strings: false,
    jslint_happy: true,
    end_with_newline: true,
    wrap_line_length: "110",
    indent_inner_html: true,
    comma_first: false,
    e4x: true,
    indent_empty_lines: true,
  },
};

// 首字母大小
export function titleCase(str) {
  return str.replace(/( |^)[a-z]/g, (L) => L.toUpperCase());
}

// 下划转驼峰
export function camelCase(str) {
  return str.replace(/_[a-z]/g, (str1) => str1.substr(-1).toUpperCase());
}

export function isNumberStr(str) {
  return /^[+-]?(0|([1-9]\d*))(\.\d+)?$/g.test(str);
}

export const NumToLetter = [
  "A",
  "B",
  "C",
  "D",
  "E",
  "F",
  "G",
  "H",
  "I",
  "J",
  "K",
  "L",
  "M",
  "N",
  "O",
  "P",
  "Q",
  "R",
  "S",
  "T",
  "U",
  "V",
  "W",
  "X",
  "Y",
  "Z",
];

export const NumToChineseNumerals = [
  "一",
  "二",
  "三",
  "四",
  "五",
  "六",
  "七",
  "八",
  "九",
  "十",
  "十一",
  "十二",
  "十三",
  "十四",
  "十五",
  "十六",
  "十七",
  "十八",
  "十九",
  "二十",
  "二十一",
  "二十二",
  "二十三",
  "二十四",
  "二十五",
  "二十六",
  "二十七",
  "二十八",
  "二十九",
  "三十",
  "三十一",
  "三十二",
  "三十三",
  "三十四",
  "三十五",
  "三十六",
  "三十七",
  "三十八",
  "三十九",
  "四十",
  "四十一",
  "四十二",
  "四十三",
  "四十四",
  "四十五",
  "四十六",
  "四十七",
  "四十八",
  "四十九",
  "五十",
  "五十一",
  "五十二",
  "五十三",
  "五十四",
  "五十五",
  "五十六",
  "五十七",
  "五十八",
  "五十九",
  "六十",
  "六十一",
  "六十二",
  "六十三",
  "六十四",
  "六十五",
  "六十六",
  "六十七",
  "六十八",
  "六十九",
  "七十",
  "七十一",
  "七十二",
  "七十三",
  "七十四",
  "七十五",
  "七十六",
  "七十七",
  "七十八",
  "七十九",
  "八十",
  "八十一",
  "八十二",
  "八十三",
  "八十四",
  "八十五",
  "八十六",
  "八十七",
  "八十八",
  "八十九",
  "九十",
  "九十一",
  "九十二",
  "九十三",
  "九十四",
  "九十五",
  "九十六",
  "九十七",
  "九十八",
  "九十九",
  "一百",
];

export const AnswerToNum = {
  A: 0,
  B: 1,
  C: 2,
  D: 3,
  E: 4,
  F: 5,
  G: 6,
  H: 7,
  I: 8,
  J: 9,
  K: 10,
  L: 11,
  M: 12,
  N: 13,
  O: 14,
  P: 15,
  Q: 16,
  R: 17,
  S: 18,
  T: 19,
  U: 20,
  V: 21,
  W: 22,
  X: 23,
  Y: 24,
  Z: 25,
};

/**
 * @description: 生成随机ID
 * @param {string} prefix
 */
export const genId = (prefix) =>
  `${prefix || ""}${Math.random()?.toString(16)?.slice(2)}`;

// 格式化试题
export const formatTitleToPaper = (data, isChild = false) =>
  data.map((i) => {
    let analyze = [];
    i.titleAnalyze && analyze.push(i.titleAnalyze);
    i.titleAnalyzeJson && analyze.push(...JSON.parse(i.titleAnalyzeJson));

    let answer = i.answer;
    try {
      const answers = JSON.parse(i.answer);
      answer = answers.join("；");
    } catch (err) {}

    // ['填空题', '完形填空'].includes(i.channelTypeName) &&
    if (i.answer) {
      // if (isChild === false) {
      const titleAnswers = i.answer.split(",");
      let answerIndex = 0; // 用于逐一取出答案
      let info = "";
      i.title = i.title.replace(
        /<div[^>]*class=['"]quizPutTag['"][^>]*>(.*?)<\/div>/g,
        () => {
          const answer = titleAnswers[answerIndex] || "";
          let res = "";
          if (i.channelTypeName === "完形填空") {
            info =
              i.children?.[answerIndex]?.optionList?.[0]?.[
                AnswerToNum[answer]
              ] || "";
            res = `<span class="title-answer">${info}</span>`;
          } else {
            res = `<span class="title-answer">${answer}</span>`;
          }
          answerIndex++;
          return res;
        }
      );
      // }
      // else {
      //   i.title = i.title.replace(
      //     /<div[^>]*class=['"]quizPutTag['"][^>]*>(.*?)<\/div>/g,
      //     `<span class="title-answer">${i.answer}</span>`
      //   );
      // }
    }

    return {
      id: i.id,
      baseId: i.baseId,
      qNo: i.titleNo || null,
      type: i.channelTypeName,
      typeId: i.channelTypeId,
      difficulty: i.difficulty,
      groupCount: i.groupCount, // 组卷次数
      quotes: i.subjectTitlePagerVoList || [], // 引用
      updateTime: i.updateTime,
      sourceName: i.sourceName, // 来源
      title: i.title, // 题目
      options: i.optionList, // 选项
      score: isChild ? null : i.score, // 分数
      children:
        i.children && i.children.length > 0
          ? formatTitleToPaper(i.children, true)
          : null, // 子题
      knowledge: i.subjectKnowledgeTitleVoList,
      answer, // 答案
      analyze, // 解析
      analyzePic: i.titleAnalyzePicture, // 解析 - 图片格式
      collectFlag: i.collectFlag, // 0-未收藏 1-已收藏
      voiceUrl: i.voiceUrl, // 音频文件
      stagePid: i.stagePid, // 归属ID
      subjectId: i.subjectId, // 归属ID
      answerStatistics: i.jobAnswerStatisticsVo, // 作答情况
      scoreRate: i.scoreRate, // 最近一次得分率
      jobFlag: i.jobFlag, // 是否出过作业
      show: false,
    };
  });

/**
 * @description: 打开新页面
 * @param {string} url
 * @param {*} target
 */
export const newPage = (url, target = "_blank") => {
  const a = document.createElement("a");
  a.setAttribute("href", url);
  a.setAttribute("target", target);
  a.setAttribute("id", "newPage");
  if (!document.getElementById("newPage")) {
    document.body.appendChild(a);
  }
  a.click();
  document.body.removeChild(a);
};

export const hookCopy = (str, msg = "复制成功") => {
  try {
    if (str == null) return;
    const tempInput = document.createElement("input");
    document.body.appendChild(tempInput);
    tempInput.setAttribute("value", str);
    tempInput.select();
    document.execCommand("copy");
    document.body.removeChild(tempInput);
    // navigator.clipboard.writeText(str);
    ElMessage.success(msg);
  } catch {
    ElMessage.error("浏览器版本太低，不支持复制功能");
  }
};

// 分数高亮
export function getScoreColor(v) {
  const val = v / 100;
  if (val >= 85) {
    return "#67c23a";
  } else if (val >= 70) {
    return "#409eff";
  } else if (val >= 60) {
    return "#e6a23c";
  }
  return "#f56c6c";
}
