/* eslint-disable standard/computed-property-even-spacing */
const SliderUnit = 0.5; // 一个色块代表0.5个小时
const TimeStart = 0;
const TimeEnd = 24;
const Amstart = 9,
  AmEnd = 12,
  PmStart = 14,
  PmEnd = 18; // 定义上午和下午的时间段区域
const DefaultOpenStartTime = 8;
const DefaultOpenEndTime = 22;
function generateTimeSliders(openStartTime, openEndTime, disabledPast = true) {
  let start = TimeStart,
    end = TimeEnd;
  let duration = end - start;
  let times = [];
  let { juggeValue } = getNowTime();
  for (let i = 0; i < duration / SliderUnit; i++) {
    let value = start + i * SliderUnit;
    let values = value.toString().split('.');
    let status = '';
    let label = '';
    if (values.length == 1) { // 代表是整数
      label = parseInt(values[0]) < 10 ? '0' + values[0] + ':00' : values[0] + ':00'
    } else { // 代表是有分钟
      let mniuts = SliderUnit * 60; // 转化分钟;
      label = parseInt(values[0]) < 10 ? '0' + values[0] + ':' + mniuts : values[0] + ':' + mniuts
    }
    if (disabledPast && value < juggeValue) {
      status = 'past' // 过去时间
    }

    if (openEndTime && (value < openStartTime || value >= openEndTime)) {
      status = 'unOpened' // 不在开放时间内
    }

    times.push({
      value,
      label,
      status
    })
  }

  return times;
}

function getNowTime() {
  let now = new Date();
  let hour = now.getHours();
  let minuts = now.getMinutes();
  // let hour = 16;
  // let minuts = 30;
  let minutsValue = 0;
  if (minuts < 30) { // 在30分钟内，都可以预约当前小时，故取0
    minutsValue = 0;
  } else {
    minutsValue = 0.5; // 在30分钟-59分钟内，都可以预约当前小时+半小时之后，故取0.5
  }
  let juggeValue = hour + minutsValue;

  return {
    juggeValue,
    trueValue: {
      hour,
      minuts
    }
  };
}

function getNowDate(date) {
  let now = new Date();
  return getDate(now);
}

function getTomorronDate() {
  let now = new Date().getTime();
  let tormorrow = new Date(now + 24 * 60 * 60 * 1000);
  return getDate(tormorrow);
}

function getDate(now) {
  let year = now.getFullYear(),
    month = now.getMonth() + 1,
    date = now.getDate();
  return [year, getTowNum(month), getTowNum(date)].join('-');
}

function getTowNum(num) {
  num = parseInt(num);
  return num < 10 ? '0' + num : num;
}

function formateTimeValue(timeValue) {
  let value = parseFloat(timeValue);
  let hour = parseInt(timeValue);
  let minits = (value - hour) * 60;
  return getTowNum(hour) + ':' + getTowNum(minits);
}

function formateTimeToValue(time) {
  let values = time.split(':');
  let hour = parseInt(values[0]);
  let mintusValue = parseInt(values[1]) / 60;
  return hour + mintusValue;
}

function formateTimeWithDateToValue(time) {
  if (typeof time === 'number') {
    time = formateDateObject(new Date(time), 'yyyy-MM-dd hh:mm:ss');
  }
  let values = time.split(' ');
  let date = values[0]; // 空格前的视为日期；
  let timeValue = formateTimeToValue(values[1]);
  return {
    date,
    time: timeValue
  }
}

function getWeekDay(date) {
  let week = date.getDay();
  let weekday = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
  return weekday[week];
}

function getMonthText(date) {
  let month = date.getMonth();
  let monthText = ['一', '二', '三', '四', '五', '六', '七', '八', '九', '十', '十一', '十二'];
  return `${monthText[month]}月`;
}

function formateTimeValueTocompletion(date, timeValue) {
  let time = formateTimeValue(timeValue) + ':00';
  return date + ' ' + time;
}

function formateRespanseTimeToDate(timeStr) {
  const values = timeStr.split(' ');
  const date = values[0]; // 空格前的视为日期；
  const times = values[1].split(':');
  let time = new Date(date);
  time.setHours(parseInt(times[0]), parseInt(times[1]), parseInt(times[2]));
  return time;
}

function formateBookedList(bookedList) {
  let list = {};
  if (!bookedList || (bookedList && bookedList.length == 0)) {
    return list;
  }
  bookedList.forEach(item => {
    let { startTime, endTime } = item;
    let start = formateTimeWithDateToValue(startTime);
    let end = formateTimeWithDateToValue(endTime);
    let key = start.date;
    let data = {
      start: start.time,
      startLabel: formateTimeValue(start.time),
      end: end.time,
      endLabel: formateTimeValue(end.time),
      userName: item.userName,
      ...item
    };
    if (!list[key]) {
      list[key] = [data];
    } else {
      list[key].push(data)
    }
  });

  return list;
}

function generateTimeValuesByArea(start, end) {
  let list = [];
  let duration = (end - start) / SliderUnit;
  for (let i = 0; i < duration; i++) {
    list.push(start + SliderUnit * i);
  }
  return list;
}
/**
 *
 * @param {2021-12-12} date 日期参数
 * @param {9.5} timeValue  时间段数值
 */
function getTimeValueDateObject(date, timeValue) {
  date = date.replace(/-/g, '/');
  let dateObject = new Date(date);
  dateObject.setHours(0);
  dateObject.setMinutes(0);
  dateObject.setSeconds(0);

  dateObject.setMinutes(parseFloat(timeValue) * 60);
  return dateObject;
}

function formatePeriodChargeList(chargeAllList, period) {
  if (!chargeAllList.length) {
    return [];
  }

  // period.start 可以从0开始, 故不能! period.start 来判断
  if (!period || (!(period && !(period.start == undefined || period.start == null) && period.end))) {
    return [];
  }

  let chareList = [];
  let selectedperiodValues = generateTimeValuesByArea(
    period.start,
    period.end
  );
  let remainNotInConfirmChargePeriodTimeValues = [...selectedperiodValues]; // 记录不在确定范围内的
  let chargeDefaulPriceItemIndex = chargeAllList.findIndex(
    charge => charge.periodType == '0' // periodType==0 代表通用时间
  );
  let chargeDefaulPrice = 0;
  let chargehasPeriodList = [...chargeAllList];

  // 过滤掉默认其他时间段价格的项目
  if (chargeDefaulPriceItemIndex !== -1) {
    chargeDefaulPrice = chargeAllList[chargeDefaulPriceItemIndex].unitPrice;
    chargehasPeriodList = [
      ...chargeAllList.slice(0, chargeDefaulPriceItemIndex),
      ...chargeAllList.slice(chargeDefaulPriceItemIndex + 1)
    ];
  }
  chargehasPeriodList = chargehasPeriodList.map(item => ({
    ...item,
    start: formateTimeToValue(item.startTime),
    end: formateTimeToValue(item.endTime)
  }))
  // 有峰值价格的时间段里去匹配选择的时间, 匹配上的从remainNotInConfirmChargePeriodTimeValues  拿走, 只保留不在的
  chargehasPeriodList.forEach(charge => {
    let inChargePeriodValues = [];
    remainNotInConfirmChargePeriodTimeValues.forEach(periodValue => {
      if (periodValue >= charge.start && periodValue < charge.end) {
        inChargePeriodValues.push(periodValue);
        // 找到后从剩余的里面拿掉
        remainNotInConfirmChargePeriodTimeValues = remainNotInConfirmChargePeriodTimeValues.filter(
          item => item !== periodValue
        );
      }
    });

    if (inChargePeriodValues.length) {
      chareList.push({
        price: charge.unitPrice,
        period: inChargePeriodValues
      });
    }
  });

  let remainPeriodList = [];
  if (remainNotInConfirmChargePeriodTimeValues.length) {
    remainPeriodList = [
      {
        period: [remainNotInConfirmChargePeriodTimeValues[0]],
        price: chargeDefaulPrice
      }
    ];
    let isMatchingPeriodIndex = 0;
    // 第一个已放入
    for (
      let i = 1;
      i < remainNotInConfirmChargePeriodTimeValues.length;
      i++
    ) {
      // 取最后一个 是连续的,则继续放入同一个时间段
      let currentmathPeriodLastValue =
        remainPeriodList[isMatchingPeriodIndex].period[
        remainPeriodList[isMatchingPeriodIndex].period.length - 1
        ];
      let timeValue = remainNotInConfirmChargePeriodTimeValues[i];
      if (currentmathPeriodLastValue + SliderUnit === timeValue) {
        remainPeriodList[isMatchingPeriodIndex].period.push(timeValue);
      } else if (remainNotInConfirmChargePeriodTimeValues[i + 1]) {
        // 不是连续的index +1 并且下一个值存在;则从下一个开始
        isMatchingPeriodIndex++;
        remainPeriodList[isMatchingPeriodIndex] = {
          period: [remainNotInConfirmChargePeriodTimeValues[i]],
          price: chargeDefaulPrice
        };
      } else if (i == remainNotInConfirmChargePeriodTimeValues.length - 1) {
        // 当前是最后一个,且没匹配上
        isMatchingPeriodIndex++;
        remainPeriodList[isMatchingPeriodIndex] = {
          period: [remainNotInConfirmChargePeriodTimeValues[i]],
          price: chargeDefaulPrice
        };
      }
    }
  }
  // remainNotInConfirmChargePeriodTimeValues 去遍历, 分组为连续时间段的,用来展示

  // 合并匹配到的峰值字段,和默认价格数组
  chareList = [...chareList, ...remainPeriodList];
  // 按照开始时间排序
  chareList = chareList.sort((pre, curr) => pre.period[0] - curr.period[0]);
  chareList = chareList.map(item => {
    let periodText = `${formateTimeValue(
      item.period[0]
    )}-${formateTimeValue(
      item.period[item.period.length - 1] + SliderUnit
    )}`;
    // toFixed 有个bug 0.015 精确到小数点2位会出现0.01 故采用这种方式四舍五入后, 再精确小数点2位
    let money = (Math.round(item.period.length * SliderUnit * item.price * 100) / 100).toFixed(2);
    return { ...item, periodText, money };
  });

  return chareList;
}

function formateDateObject(date, fmt) { // author: meizz
  var o = {
    'M+': date.getMonth() + 1, // 月份
    'd+': date.getDate(), // 日
    'h+': date.getHours(), // 小时
    'm+': date.getMinutes(), // 分
    's+': date.getSeconds(), // 秒
    'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
    'S': date.getMilliseconds() // 毫秒
  };
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
  }
  for (var k in o) {
    if (new RegExp('(' + k + ')').test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)));
    }
  }
  return fmt;
}

export {
  TimeStart,
  TimeEnd,
  SliderUnit,
  Amstart,
  AmEnd,
  PmStart,
  PmEnd,
  generateTimeSliders,
  getNowDate,
  getTomorronDate,
  getDate,
  formateTimeValue,
  getWeekDay,
  formateTimeToValue,
  formateTimeWithDateToValue,
  formateTimeValueTocompletion,
  getNowTime,
  formateBookedList,
  generateTimeValuesByArea,
  getTowNum,
  getMonthText,
  formateRespanseTimeToDate,
  formatePeriodChargeList,
  DefaultOpenStartTime,
  DefaultOpenEndTime,
  getTimeValueDateObject
}
