// 1496311370052 转成 'yyyy-MM-dd hh:mm:ss' 或 'yyyyMMddhhmmss'
import TIM from "tim-js-sdk/tim-js-friendship";
import tim from "@/tim";

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 (("" + time).length === 10) time = parseInt(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];
    if (key === "a") return ["日", "一", "二", "三", "四", "五", "六"][value];
    if (result.length > 0 && value < 10) {
      value = "0" + value;
    }
    return value || 0;
  });
  return time_str;
}

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 "刚刚";
  } 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() + "分";
  }
}
// 表单重置
export function resetForm(refName) {
  if (this.$refs[refName]) {
    this.$refs[refName].resetFields();
  }
}
// 格式化时间
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;
}
// 添加日期范围
export function addDateRange(params, dateRange, propName) {
  var search = params;
  if (null != dateRange && "" != dateRange) {
    if (typeof propName === "undefined") {
      search["beginTime"] = dateRange[0];
      search["endTime"] = dateRange[1];
    } else {
      search["begin" + propName] = dateRange[0];
      search["end" + propName] = dateRange[1];
    }
  }
  // console.log()
  return search;
}
//检验是否是IP
export function isValidIP(ip) {
  var reg =
    /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/;
  return reg.test(ip);
}
//检验是否是Mac
export function isValidMAC(mac) {
  var reg = /([A-Fa-f0-9]{2}-){5}[A-Fa-f0-9]{2}/;
  return reg.test(mac);
}
// 验证手机号
export function checkPhone(rule, value, callback) {
  let reg = /^1[345789]\d{9}$/;
  if (!reg.test(value)) {
    callback(new Error("请输入11位手机号"));
  } else {
    callback();
  }
}
/**
 * @param {string} path
 * @returns {Boolean}
 */
export function isExternal(path) {
  return /^(https?:|mailto:|tel:)/.test(path);
}

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

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("&");
}

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

export function objectMerge(target, source) {
  /* Merges two  objects,
   giving the last one precedence */

  if (typeof target !== "object") {
    target = {};
  }
  if (Array.isArray(source)) {
    return source.slice();
  }
  for (const property in source) {
    if (Object.prototype.hasOwnProperty.call(source, property)) {
      const sourceProperty = source[property];
      if (typeof sourceProperty === "object") {
        target[property] = objectMerge(target[property], sourceProperty);
        continue;
      }
      target[property] = sourceProperty;
    }
  }
  return target;
}

export function scrollTo(element, to, duration) {
  if (duration <= 0) return;
  const difference = to - element.scrollTop;
  const perTick = (difference / duration) * 10;
  setTimeout(() => {
    element.scrollTop = element.scrollTop + perTick;
    if (element.scrollTop === to) return;
    scrollTo(element, to, duration - 10);
  }, 10);
}

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;
}

export const pickerOptions = [
  {
    text: "今天",
    onClick(picker) {
      const end = new Date();
      const start = new Date(new Date().toDateString());
      end.setTime(start.getTime());
      picker.$emit("pick", [start, end]);
    },
  },
  {
    text: "最近一周",
    onClick(picker) {
      const end = new Date(new Date().toDateString());
      const start = new Date();
      start.setTime(end.getTime() - 3600 * 1000 * 24 * 7);
      picker.$emit("pick", [start, end]);
    },
  },
  {
    text: "最近一个月",
    onClick(picker) {
      const end = new Date(new Date().toDateString());
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
      picker.$emit("pick", [start, end]);
    },
  },
  {
    text: "最近三个月",
    onClick(picker) {
      const end = new Date(new Date().toDateString());
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
      picker.$emit("pick", [start, end]);
    },
  },
];

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

// 防抖
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;
  };
}

// 对象深克隆
export function deepClone(source) {
  if (!source && typeof source !== "object") {
    throw new Error("error arguments", "shallowClone");
  }
  const targetObj = source.constructor === Array ? [] : {};
  for (const keys in source) {
    if (Object.prototype.hasOwnProperty.call(source, keys)) {
      if (source[keys] && typeof source[keys] === "object") {
        targetObj[keys] = source[keys].constructor === Array ? [] : {};
        targetObj[keys] = deepClone(source[keys]);
      } else {
        targetObj[keys] = source[keys];
      }
    }
  }
  return targetObj;
}
/**
 * 构造树型结构数据
 * @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 && typeof value !== "undefined") {
      if (typeof value === "object") {
        for (const key of Object.keys(value)) {
          if (value[key] !== null && typeof value[key] !== "undefined") {
            let params = propName + "[" + key + "]";
            var subPart = encodeURIComponent(params) + "=";
            result += subPart + encodeURIComponent(value[key]) + "&";
          }
        }
      } else {
        result += part + encodeURIComponent(value) + "&";
      }
    }
  }
  return result;
}

// 验证是否为blob格式
export async function blobValidate(data) {
  try {
    const text = await data.text();
    JSON.parse(text);
    return false;
  } catch (error) {
    return true;
  }
}

// 1496311370052 转成
export function formatDate(date, fmt) {
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
  }
  let o = {
    "M+": date.getMonth() + 1,
    "d+": date.getDate(),
    "h+": date.getHours(),
    "m+": date.getMinutes(),
    "s+": date.getSeconds(),
  };
  for (let k in o) {
    if (new RegExp(`(${k})`).test(fmt)) {
      let str = o[k] + "";
      fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : ("00" + str).substr(str.length));
    }
  }
  return fmt;
}

export const getConfig = async (key) => {
  const res = await fetch("config.json");
  return new Promise((resolve, reject) => {
    res
      .json()
      .then(async (response) => {
        if (key) {
          if (Object.prototype.hasOwnProperty.call(response, key)) {
            resolve(response[key]);
            return response[key];
          } else {
            resolve(null);
            return null;
          }
        } else {
          resolve(response);
          return response;
        }
      })
      .catch((error) => {
        reject(new Error(error));
      });
  });
};

export function filterCallingMessage(currentMessageList) {
  currentMessageList.forEach((item) => {
    if (item.callType) {
      // 对于自己伪造的消息不需要解析
      return;
    }
    if (item.type === TIM.TYPES.MSG_MERGER && item.payload.downloadKey !== "") {
      let promise = tim.downloadMergerMessage(item);
      promise
        .then(function (imResponse) {
          // 下载成功后，SDK会更新 message.payload.messageList 等信息
          item = imResponse;
        })
        .catch(function (imError) {
          // 下载失败
          console.warn("downloadMergerMessage error:", imError);
        });
    }
    // if (item.type === TIM.TYPES.MSG_CUSTOM) {
    //   let payloadData = {};
    //   try {
    //     payloadData = JSON.parse(item.payload.data);
    //   } catch (e) {
    //     payloadData = {};
    //   }
    //   if (payloadData.businessID === 1) {
    //     if (item.conversationType === TIM.TYPES.CONV_GROUP) {
    //       if (payloadData.actionType === 5) {
    //         item.nick = payloadData.inviteeList
    //           ? payloadData.inviteeList.join(",")
    //           : item.from;
    //       }
    //       let _text = window.trtcCalling.extractCallingInfoFromMessage(item);
    //       let group_text = `${_text}`;
    //       item.type = TIM.TYPES.MSG_GRP_TIP;
    //       item.payload = {
    //         operationType: 256,
    //         text: group_text,
    //         userIDList: [],
    //       }; //JSON.stringify(customData)
    //     }
    //     if (item.conversationType === TIM.TYPES.CONV_C2C) {
    //       let c2c_text = window.trtcCalling.extractCallingInfoFromMessage(item);
    //       item.payload = {
    //         text: c2c_text,
    //       }; //JSON.stringify(customData)
    //     }
    //   }
    // }
  });
}

export function getUrlParam(key) {
  const url = decodeURI(window.location.href.replace(/^[^?]*\?/, ""));
  const regexp = new RegExp(`(^|&)${key}=([^&#]*)(&|$|)`, "i");
  const paramMatch = url.match(regexp);

  return paramMatch ? paramMatch[2] : null;
}

export function clearUrlParam() {
  location.href = location.href.slice(0, location.href.indexOf("?") > 0 ? location.href.indexOf("?") : location.href.length);
}

export function isUndefined(value) {
  return value === "undefined";
}

/**
 * 获取语言
 * @returns language
 */
export function getLanguage() {
  let language = localStorage.getItem("trtc-quick-vue2-language") || getUrlParam("lang") || navigator.language || "zh";
  language = language.replace(/_/, "-").toLowerCase();

  if (language === "zh-cn" || language === "zh") {
    language = "zh";
  } else if (language === "en" || language === "en-us" || language === "en-GB") {
    language = "en";
  }
  return language;
}

/**
 * 当前浏览器是否为移动端浏览器
 */
export const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);

export const getImgInfo = (file, maxWidth = 100, maxHeight = 100) => {
  return new Promise(function (resolve, reject) {
    //Window.URL 属性返回一个对象，它提供了用于创建和管理对象URLs的静态方法
    let _URL = window.URL || window.webkitURL;
    let img = new Image();
    img.onload = () => {
      let valid = img.width <= maxWidth && img.height <= maxHeight;
      valid ? resolve() : reject();
    };
    //https://developer.mozilla.org/zh-CN/docs/Web/API/URL/createObjectURL  具体查看
    img.src = _URL.createObjectURL(file);
  }).then(
    () => {
      return file;
    },
    () => {
      return Promise.reject();
    }
  );
};

export const genRandom = (min, max) => ((Math.random() * (max - min + 1)) | 0) + min;

export function handleDebounce(func, wait) {
  let context = this;
  let args = arguments;
  if (this.timeout) clearTimeout(this.timeout);
  this.timeout = setTimeout(() => {
    func.apply(context, args);
  }, wait);
}
