/**
 * Created by jiachenpan on 16/11/18.
 */
import dayjs from "dayjs";
import moment from "moment";

export function parseTime(time) {
  // eslint-disable-next-line no-console
  if (time) {
    const date = new Date(
      typeof time === "string" ? time.replace(/-/g, "/") : time
    );
    const year = date.getFullYear();
    /* 在日期格式中，月份是从0开始的，因此要加0
     * 使用三元表达式在小于10的前面加0，以达到格式统一  如 09:11:05
     * */
    const month =
      date.getMonth() + 1 < 10
        ? `0${date.getMonth() + 1}`
        : date.getMonth() + 1;
    const day = date.getDate() < 10 ? `0${date.getDate()}` : date.getDate();
    const hours =
      date.getHours() < 10 ? `0${date.getHours()}` : date.getHours();
    const minutes =
      date.getMinutes() < 10 ? `0${date.getMinutes()}` : date.getMinutes();
    const seconds =
      date.getSeconds() < 10 ? `0${date.getSeconds()}` : date.getSeconds();
    // 拼接
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  }
  return "";
}

export function formatNum(n, is_int = false) {
  n = Number(n);
  // 转化成字符串
  let str = n.toString();
  // 若是整数自动补全小数位
  if (str.indexOf(".") === -1) {
    str = str + ".00";
  }
  // 全部替换
  if (str.indexOf(",") !== -1) {
    str = str.replace(new RegExp(",", "g"), "");
  }
  // 取到整数部分
  const intSum = str
    .substring(0, str.indexOf("."))
    .replace(/\B(?=(?:\d{3})+$)/g, ",");
  if (is_int) {
    return intSum;
  }
  // 取到小数部分搜索
  const dot = str.substring(str.length, str.indexOf("."));
  const ret = intSum + dot;
  return ret;
}

export function toPercentage(a, digit) {
  let result = "";
  const num = Number(a);
  result = (num * 100).toFixed(digit) + "%";
  return result;
}

export function parseTimeSecond(time) {
  // eslint-disable-next-line no-console
  if (time) {
    const date = new Date(time * 1000);
    const year = date.getFullYear();
    /* 在日期格式中，月份是从0开始的，因此要加0
     * 使用三元表达式在小于10的前面加0，以达到格式统一  如 09:11:05
     * */
    const month =
      date.getMonth() + 1 < 10
        ? `0${date.getMonth() + 1}`
        : date.getMonth() + 1;
    const day = date.getDate() < 10 ? `0${date.getDate()}` : date.getDate();
    const hours =
      date.getHours() < 10 ? `0${date.getHours()}` : date.getHours();
    const minutes =
      date.getMinutes() < 10 ? `0${date.getMinutes()}` : date.getMinutes();
    const seconds =
      date.getSeconds() < 10 ? `0${date.getSeconds()}` : date.getSeconds();
    // 拼接
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  }
  return "";
}

export function formatTime(time, option) {
  time = +time * 1000;
  const d = new Date(time);
  const now = Date.now();

  const diff = (now - d) / 1000;

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

export function debounce(func, wait, immediate) {
  let timeout;
  let args;
  let context;
  let timestamp;
  let 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;
  };
}

export function isExternal(path) {
  return /^(https?:|mailto:|tel:)/.test(path);
}

// 替换邮箱字符
export function regEmail(email) {
  if (String(email).indexOf("@") > 0) {
    const str = email.split("@");
    let _s = "";
    if (str[0].length > 3) {
      for (let i = 0; i < str[0].length - 3; i++) {
        _s += "*";
      }
    }
    var new_email = `${str[0].substr(0, 3) + _s}@${str[1]}`;
  }
  return new_email;
}

// 替换手机字符
export function regMobile(mobile) {
  if (mobile.length > 7) {
    var new_mobile = `${mobile.substr(0, 3)}****${mobile.substr(7)}`;
  }
  return new_mobile;
}

/**
 * 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 getStringLen(str) {
  let len = 0;
  if (str === null || str === "") return 0;
  str.split("").map((item, i) => {
    if (str.charCodeAt(i) > 255) {
      len = len + 2;
    } else {
      len = len + 1;
    }
  });
  return len;
}
// 过滤特殊字符
export function stripscript(s) {
  const pattern = new RegExp(
    "[`~!@#$^&*()=|{}':;',\\[\\].<>/?~！@#￥……&*（）——|{}【】‘；：”“'。，、？↵\r\n]"
  );
  let rs = "";
  for (let i = 0; i < s.length; i++) {
    rs = rs + s.substr(i, 1).replace(pattern, "");
  }
  return rs;
}
export function formatDecimal(num, decimal) {
  num = num.toString();
  const index = num.indexOf(".");
  if (index !== -1) {
    num = num.substring(0, decimal + index + 1);
  } else {
    return Number(num);
  }
  if (Number(num) === 0) {
    return 0;
  }
  return parseFloat(num).toFixed(decimal);
}

export function toPrice(row, showName = false) {
  let price = "";
  if (row.feesList) {
    row.feesList.forEach((val, index) => {
      const fen = val.price / 100;
      // switch (val.period) {
      //   case 0:
      //     price += '免费永久,单笔提佣'
      //     break
      //   case 7:
      //     price = price + fen + '元/周'
      //     break
      //   case 14:
      //     price = price + fen + '元/月'
      //     break
      //   case 16:
      //     price = price + fen + '元/季度'
      //     break
      //   case 19:
      //     price = price + fen + '元/半年'
      //     break
      //   case 20:
      //     price = price + fen + '元/年'
      //     break
      //   case 99:
      //     price = showName ? row.strategyName + '：' : ''
      //     price = price + fen + '元/篇，收费永久,单篇收费'
      //     break
      //   default:
      //     break
      // }
      switch (val.period) {
        // case 0:
        //   price += '免费永久,单笔提佣'
        //   break
        case 1:
          price = price + fen + "元/周";
          break;
        case 2:
          price = price + fen + "元/月";
          break;
        case 3:
          price = price + fen + "元/季度";
          break;
        case 4:
          price = price + fen + "元/半年";
          break;
        case 5:
          price = price + fen + "元/年";
          break;
        case 0:
          price = showName ? row.strategyName + "：" : "";
          price = price + fen + "元/篇，收费永久,单篇收费";
          break;
        default:
          break;
      }
      if (index + 1 < row.feesList.length) {
        price += "；";
      }
    });
  }
  return price;
}

export function getStatus(value) {
  if (value == null) return "--";
  switch (value) {
    case 1:
      return "待提交";
    case 2:
      return "待一级审核";
    case 11:
      return "待二级审核";
    case 12:
      return "待三级审核";
    case 3:
      return "已上架";
    case 4:
      return "已驳回";
    case 5:
      return "已下架";
  }
}

export function timeFormat(second) {
  return moment.utc(second).format("HH:mm:ss");
}

export function timeFormatTwo(second) {
  const hours = Math.floor(second / 3600);
  const minutes = Math.floor((second % 3600) / 60);
  const secs = Math.floor(second % 60);

  // 使用 padStart 方法确保分钟和秒总是两位数
  const paddedMinutes = minutes.toString().padStart(2, "0");
  const paddedSeconds = secs.toString().padStart(2, "0");

  // 格式化时间
  const formattedTime = `${hours}:${paddedMinutes}:${paddedSeconds}`;
  return formattedTime;
}
