import dayjs from "dayjs";
import duration from "dayjs/plugin/duration";
import { appConfig } from "@/config";

dayjs.extend(duration);

export const DATE = {
  format(str: any, fmt: string = "YYYY-MM-DD") {
    return str ? dayjs(str).format(fmt) : dayjs().format(fmt);
  },
  formatTimeMinute(str: any) {
    return DATE.format(str, "YYYY-MM-DD HH:mm");
  },
  diff(params: any) {
    const ref = params.ref ? dayjs(params.ref) : dayjs();
    const target = params.target ? dayjs(params.target) : dayjs();
    const measure = params.measure || "days";
    return ref.diff(target, measure);
  },
  duration(time: any, fmt = "H小时m分s秒", measure: any = "seconds") {
    return dayjs.duration(time, measure).format(fmt);
  },
  isAfter(date1: any, date2: any, type?: any) {
    return dayjs(date1).isAfter(date2, type);
  },
};

export const STORAGE = {
  setLocal(label: any, value: any, stringify = false) {
    localStorage.setItem(label, stringify ? JSON.stringify(value) : value);
  },
  getLocal(label: any, parse: any = false) {
    const item = localStorage.getItem(label);
    if (!item) {
      return "";
    }
    try {
      return parse ? JSON.parse(item) : item;
    } catch (err) {
      return "";
    }
  },
  clearLocal() {
    localStorage.clear();
  },
  removeLocal(label: any) {
    localStorage.removeItem(label);
  },
};

export const getApiBaseURL = () => {
  let baseApi = appConfig.apiBaseUrl;
  return baseApi;
};

export const isArray = (obj: any) => {
  if (Array.isArray) {
    return Array.isArray(obj);
  } else {
    return Object.prototype.toString.call(obj) === "[object Array]";
  }
};

export const brToLf = (params: string) => {
  if (!params) return "";
  console.log("转换前", params);

  console.log("转换后", params.replace(/<br\s*\/?>/g, "\n"));

  return params.replace(/<br\s*\/?>/g, "\n");
};

export const getYearNo = (length: number) => {
  let theYear = [];
  let y = new Date().getFullYear();
  for (var i = 1; i <= length; i++) {
    if (i < 50) {
      theYear.push({
        value: `${y - i}-${y - i + 1}`,
        label: `${y - i}-${y - i + 1}`,
      });
    }
    // else {
    //   for (var x = 1; x < 51; x++) {
    //     theYear.push({ value: y + x, label: y + x + '年' });
    //   }
    // }
  }
  return theYear;
};
export const getImage = (url) => {
  let image = new Image();
  let pictureType;
  let picture;
  image.setAttribute("crossOrigin", "Anonymous");
  image.src = url + "?v=1.1"; // 参数不要随机，否则会击穿CDN缓存
  image.onload = () => {
    let width = image.width;
    let height = image.height;
    let ratio = 375 / 300;
    pictureType = width / height > ratio ? "row-image" : "column-image";
    picture = getBase64Image(image);
  };
  console.log("image", image);
  return image;
};
