import dayjs from "dayjs";
/*
 * @params key			名字
 * @params value			值
 * @params path			路径
 * @params expireDays	存取的时间
 */
export function setCookie(key, value, path, expireDays) {
  if (!key) return;
  let extDate = new Date();
  path = "path=" + (path || "") + "/;";
  extDate.setDate(extDate.getDate() + (expireDays || 0));
  expireDays = extDate.toGMTString();
  document.cookie = key.trim() + "=" + value + ";" + path + expireDays;
}

export function delCookie(key) {
  document.cookie = key + "=; path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;";
}

/**
 * 获取cookie值
 * @param name
 * @returns {null}
 */
export const getCookie = function (name) {
  let arr,
    reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
  if (arr == document.cookie.match(reg)) {
    return unescape(arr[2]);
  } else {
    return null;
  }
};

export function setLocalStrage(key, value) {
  if (!key || !window.localStorage) {
    return;
  } else {
    window.localStorage.setItem(key.trim(), value);
  }
}

export function delLocalSt(key) {
  if (!key || !window.localStorage) {
    return;
  } else {
    window.localStorage.removeItem(key);
  }
}

export function getLocalStrage(key) {
  if (!key || !window.localStorage) {
    return;
  } else {
    window.localStorage.getItem(key);
  }
}

export const getRandomKey = () => {
  let key = "" + new Date().getTime() + Math.floor(Math.random() * 1000000);
  return key;
};

export function browser() {
  var u = navigator.userAgent;
  //   app = navigator.appVersion;
  return {
    trident: u.indexOf("Trident") > -1, //IE内核
    presto: u.indexOf("Presto") > -1, //opera内核
    webKit: u.indexOf("AppleWebKit") > -1, //苹果、谷歌内核
    gecko: u.indexOf("Gecko") > -1 && u.indexOf("KHTML") == -1, //火狐内核
    mobile: !!u.match(/AppleWebKit.*Mobile.*/), //是否为移动终端
    ios: !!u.match(/Mac OS X/), //ios终端
    // ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
    android: u.indexOf("DAYAAPPA") > -1 || u.indexOf("Adr") > -1, //android终端
    iPhone: u.indexOf("DAYAAPPI") > -1, //是否为iPhone或者QQHD浏览器
    isApp: u.indexOf("DAYAAPPI") > -1 || u.indexOf("DAYAAPPA") > -1 || u.indexOf("Adr") > -1,
    iPad: u.indexOf("iPad") > -1, //是否iPad
    webApp: u.indexOf("Safari") == -1, //是否web应该程序，没有头部与底部
    weixin: u.indexOf("MicroMessenger") > -1, //是否微信 （2015-01-22新增）
    huawei: !!u.match(/huawei/i) || !!u.match(/honor/i),
    xiaomi: !!u.match(/mi\s/i) || !!u.match(/redmi/i) || !!u.match(/mix/i),
  };
}

// 获取时分秒
export function utilDateInfo(date) {
  if (typeof date == "string") {
    date = date.replace(/-/gi, "/");
  }
  let d = new Date(date);
  let hour = d.getHours() >= 10 ? d.getHours() : "0" + d.getHours();
  let minute = d.getMinutes() >= 10 ? d.getMinutes() : "0" + d.getMinutes();
  return hour + ":" + minute + ":00";
}

// 获取年月日
export function utilDate(date, type) {
  if (typeof date == "string") {
    date = date.replace(/-/gi, "/");
  }
  let d = new Date(date);
  let year = d.getFullYear() >= 10 ? d.getFullYear() : "0" + d.getFullYear();
  let month = d.getMonth() + 1 >= 10 ? d.getMonth() + 1 : "0" + (d.getMonth() + 1);
  let day = d.getDate() >= 10 ? d.getDate() : "0" + d.getDate();

  if (type == "ios") {
    return year + "/" + month + "/" + day;
  }
  return year + "-" + month + "-" + day;
}

/**
 * 小于10的数变成 (0x)
 * @param {数值} num
 */
export function getSTD(num) {
  return Number(num) >= 10 ? num : "0" + num;
}

/**
 * 获取格式化的年月日
 * @param {日期} time
 * @param {不是IOS里使用（多用于接口参数）} noIos
 */
export function getYMD(time, noIos) {
  let tempDate = time || new Date();
  if (typeof tempDate == "string") {
    tempDate = new Date(time.replace(/-/gi, "/"));
  }
  let t = noIos ? "-" : "/";
  let month = getSTD(tempDate.getMonth() + 1);
  let day = getSTD(tempDate.getDate());
  return tempDate.getFullYear() + t + month + t + day;
}

/**
 *
 * @param {周几的索引值} index
 */
export function getWeekString(index) {
  let weekText = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"];
  return weekText[index];
}

/**
 * 手机号验证
 * @param {手机号} phoneNumber
 */
export function checkPhone(phoneNumber) {
  let result = true;
  if (!/^1(3|4|5|6|7|8|9)\d{9}$/.test(phoneNumber)) {
    result = false;
  }
  return result;
}

// 学生地址
export function validStudentUrl() {
  let url = window.location.hostname;
  let returnUrl = "";
  if (/test/.test(url)) {
    // test环境
    returnUrl = "https://test.gym.lexiaoya.cn/mdaya";
  } else if (/dev/.test(url)) {
    // dev 环境
    returnUrl = "https://dev.gym.lexiaoya.cn/mdaya";
  } else {
    //线上
    returnUrl = "https://gym.lexiaoya.cn/mdaya";
  }
  return returnUrl;
}

// 老师地址
export function validTeacherUrl() {
  let url = window.location.hostname;
  let returnUrl = "";
  if (/test/.test(url)) {
    // test环境
    returnUrl = "https://test.gym.lexiaoya.cn/mteacher";
  } else if (/dev/.test(url)) {
    // dev 环境
    returnUrl = "https://dev.gym.lexiaoya.cn/mteacher";
  } else {
    //线上
    returnUrl = "https://gym.lexiaoya.cn/mteacher";
  }
  return returnUrl;
}

/**
 * @desc 函数防抖
 * @param func 目标函数
 * @param wait 延迟执行毫秒数
 */
export function debounce(func, wait) {
  let timeout = null;
  return function () {
    let context = this;
    let args = arguments;
    if (timeout) clearTimeout(timeout);
    timeout = setTimeout(() => {
      func.apply(context, args);
    }, wait);
  };
}

/**
 * @desc 函数节流
 * @param func 函数
 * @param wait 延迟执行毫秒数
 */
export function throttle(func, wait) {
  let timeout = null;
  return function () {
    let context = this;
    let args = arguments;
    if (!timeout) {
      timeout = setTimeout(() => {
        timeout = null;
        func.apply(context, args);
      }, wait);
    }
  };
}

/**
 * 转换金额为保留2位小数
 * @param x
 * @returns 强制保留2位小数的金额
 */
export function changeTwoDecimal(amt) {
  let f_x = parseFloat(amt);
  if (isNaN(f_x)) {
    return "0.00";
  }
  f_x = Math.round(f_x * 100) / 100;
  let s_x = f_x.toString();
  let pos_decimal = s_x.indexOf(".");
  if (pos_decimal < 0) {
    pos_decimal = s_x.length;
    s_x += ".";
  }
  while (s_x.length <= pos_decimal + 2) {
    s_x += "0";
  }
  return s_x;
}

export function addTimerFormMinute(classDate, startTime, time) {
  let endTime = dayjs(classDate + " " + startTime).add(time, "minute");
  if (!dayjs(classDate + " " + "23:59:59").isBefore(endTime)) {
    return endTime.format("HH:mm:ss");
  } else {
    return "";
  }
}

export function diffTimerFormMinute(classDate, startTime, endTime) {
  return Math.abs(dayjs(classDate + " " + startTime).diff(classDate + " " + endTime, "Minute"));
}

export function timerFormMinute(classDate, startTime, time) {
  let endTime = dayjs(classDate + " " + startTime).add(time, "minute");
  if (!dayjs(classDate + " " + "21:00").isBefore(endTime)) {
    return endTime.format("HH:mm");
  } else {
    return "";
  }
}
