import { isLeapYear } from "@mobileUI/utils";
import { dateKey, timeKey } from "./variable";
/**
 * 获取年月对应的一月日数,如果不传year,2月取29
 * @param month
 * @param year
 * @returns number
 */
export const onGetDayNumber = (month, year) => {
  const month31 = [1, 3, 5, 7, 8, 10, 12];
  if (month === 2) {
    // 如果存在年份,且是闰年
    if (year && isLeapYear(year)) {
      return 29;
    } else {
      return 28;
    }
  } else {
    if (month31.includes(month)) {
      return 31;
    } else {
      return 30;
    }
  }
};
/**
 * 将picker返回的数据格式话为日期
 * @param data picker选择的数据
 */
export const onGetTime = (data) => {
  let time = data.reduce((pre, cur, currentIndex) => {
    let prefix = "", suffix = "";
    if ([dateKey.day, dateKey.month].includes(cur.type) && pre) {
      prefix = "/";
    }
    if ([timeKey.minute, timeKey.second].includes(cur.type) && pre) {
      prefix = ":";
    }
    if(cur.type === timeKey.hour && pre){
      prefix = " "
    }
    if(cur.type === timeKey.hour && currentIndex === data.length - 1){
      suffix = ":0:0"
    }
    pre = pre + prefix + cur.value + suffix;
    return pre;
  }, "");
  // 如果只有一个/表示是年/月的格式，在ios中无法用这个格式进行获取日期，会直接返回NaN
  if(time.indexOf("/") === time.lastIndexOf("/") && time.indexOf("/") !== -1){
    time += "/1";
  }
  if(time.indexOf("/") === -1){
    const currentTime = new Date()
    time += `/${currentTime.getMonth() + 1}/${currentTime.getDate()}`
  }
  return new Date(time)
};
