// 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;
      // 濡傛灉璁惧畾涓篿mmediate===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;
}

// 楠岃瘉鏄惁涓篵lob鏍煎紡
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 灞炴€ц繑鍥炰竴涓璞★紝瀹冩彁渚涗簡鐢ㄤ簬鍒涘缓鍜岀鐞嗗璞RLs鐨勯潤鎬佹柟娉�
    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);
}