import dict from "./dict";
import dayjs from './monent';

const confirm = (content, title, config) => {
  let ops = {content}
  if (typeof title == 'object') {
    ops = {...ops, ...title}
  } else ops = {...ops, title: title || "提示"}
  return new Promise((resolve, reject) => {
    uni.showModal({
      ...ops, ...config, success: res => {
        if (res?.confirm) {
          resolve()
        } else if (res?.cancel) {
          reject()
        }
      }
    })
  })
}

/**
 * 获取年龄
 * @param code
 */
const calcAge = (code) => {
  let birthday
  if (typeof code == 'string' && code.length == 18) {
    birthday = dayjs(code.substring(6, 14), 'YYYYMMDD')
  } else if (typeof code == 'object') {
    birthday = code
  }
  return Math.ceil(dayjs().year() - dayjs(birthday).year())
}

export default {
  dict,
  confirm,
  calcAge,
  dateFormat: (time, format) => {
    return dayjs(time).format(format || 'YYYY-MM-DD').replace("Invalid Date", "")
  },
  formatName: (name) => {
    return Array.from(name)?.slice(-2)?.toString() || "";
  },
  loading: title => {
    uni.showLoading({
      title: title ? title : '加载中',
      mask: true
    })
  },
  hideLoading: () => {
    uni.hideLoading()
  },
  colorUtils: {
    Hex2RGBA(color, alpha = 1) {
      let hex = 0;
      if (color.charAt(0) == "#") {
        if (color.length == 4) {
          //检测诸如#FFF简写格式
          color = "#" + color.charAt(1).repeat(2) +
              color.charAt(2).repeat(2) +
              color.charAt(3).repeat(2);
        }
        hex = parseInt(color.slice(1), 16);
      }
      let r = hex >> 16 & 0xFF;
      let g = hex >> 8 & 0xFF;
      let b = hex & 0xFF;
      return `rgba(${r},${g},${b},${alpha})`;
    },
    RGBtoHex(r, g, b) {
      let hex = r << 16 | g << 8 | b;
      return "#" + hex.toString(16);
    }
  },
  dayjs
}
