'use strict';

var _base = require('./base');

var _locale = require('./locale');

var _locale2 = _interopRequireDefault(_locale);

var _dateFormat = require('./dateFormat');

var _dateFormat2 = _interopRequireDefault(_dateFormat);

var _Slot = require('../../Slot');

var _Slot2 = _interopRequireDefault(_Slot);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var _console = console,
    warn = _console.warn,
    error = _console.error;

var colFlags = ['Y', 'M', 'D', 'T', 'h', 'H', 'm', 's', 'YMD', 'YMDW'];

/**
 * 解析参数值
 * @param { object | string | date | string | number  } value
 * @example {value: 1545484545454} [2018,2,1] 1212154545454, ***
 * @returns array
 */
function parseValue(value) {
  var date = new Date((0, _base.parseDate)(value));
  var timeType = void 0;
  if (value && value.timeType) {
    timeType = { AM: 0, PM: 1 }[value.timeType || 'AM'];
  } else {
    timeType = date.getHours() >= 12 ? 1 : 0;
  }
  return [date.getFullYear(), date.getMonth(), date.getDate(), timeType, date.getHours() >= 13 ? date.getHours() - 12 : date.getHours(), // 12小时制
  date.getHours(), date.getMinutes(), date.getSeconds(),
  // 获取年月日组合，转换成number
  '' + date.getFullYear() + (0, _base.addZero)(date.getMonth() + 1) + (0, _base.addZero)(date.getDate()) - 0, '' + date.getFullYear() + (0, _base.addZero)(date.getMonth() + 1) + (0, _base.addZero)(date.getDate()) - 0];
}

/**
 * sure 可以控制是否添加周"几" 根据日期获取一周中的一天，默认是 true
 * @param {*} days
 * @param {*} props
 * @param {*} sure
 */

function addDayOfWeek(days, props) {
  var sure = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;

  var daysNew = (0, _base.cloneDeep)(days);
  if ((0, _base.isArray)(days)) {
    days.forEach(function (day) {
      var dayNew = day;
      var date = new Date((0, _base.numToDate)(day.value));
      if (sure) {
        dayNew.text = (0, _dateFormat2.default)(date, 'YYYY/MM/DD') + ' ' + _locale2.default[props.locale].week[date.getDay()];
      } else {
        dayNew.text = (0, _dateFormat2.default)(date, 'YYYY/MM/DD');
      }
    });
    return;
  }
  var date = new Date((0, _base.numToDate)(days.value));
  if (sure) {
    daysNew.text = (0, _dateFormat2.default)(date, 'YYYY/MM/DD') + ' ' + _locale2.default[props.locale].week[date.getDay()];
  } else {
    daysNew.text = (0, _dateFormat2.default)(date, 'YYYY/MM/DD');
  }
}

/**
 * 根据 props columns 计算 slot list
 * @param {*} arr
 * @param {*} props
 */
function formatFromProps(arr, props) {
  var columns = props.columns;

  var displayList = [];
  for (var i = 0; i < columns.length; i += 1) {
    if (colFlags.indexOf(columns[i]) !== -1) {
      displayList.push(arr[colFlags.indexOf(columns[i])]);
    }
    if (columns[i] === 'YMDW') {
      addDayOfWeek(displayList[i], props);
    }
    if (columns[i] === 'YMD') {
      addDayOfWeek(displayList[i], props, false);
    }
  }
  return displayList;
}

/**
 * 添加年月日等文本
 * @param { array } arr
 * @param {string } text
 * @param { object } props
 */

function formatText(arr, text, props) {
  var formatArray = [];
  var localeCode = props.locale;
  for (var i = 0; i < arr.length; i += 1) {
    var el = arr[i];
    formatArray.push((0, _base.isArray)(el) ? formatText(el, _locale2.default[localeCode].surfix[colFlags[i]], props) : {
      text: (0, _base.addZero)(el.text) + ((0, _base.isUndefined)(text) ? _locale2.default[localeCode].surfix[colFlags[i]] : text),
      value: el.value
    });
  }
  return formatArray;
}

/**
 * 求时间区间的并集
 * @param { array } arr
 */
function parseDisabledArr(arr) {
  var min = void 0;
  var max = void 0;
  var arrNew = (0, _base.cloneDeep)(arr);
  arrNew = arrNew.map(function (item) {
    var start = item.start,
        end = item.end;

    if (!start && !end) {
      var dateTime = new Date(item).getTime();
      if (dateTime) {
        return {
          start: dateTime,
          end: dateTime
        };
      }
      return false;
    }
    return {
      start: new Date(start).getTime(),
      end: new Date(end).getTime()
    };
  });
  var newArr = arrNew.filter(function (item) {
    return !!item;
  });
  // 求时间并集并求出 最大值和最小值
  newArr = newArr.filter(function (item) {
    var start = item.start,
        end = item.end;

    if (start && !end) {
      // 求max
      if (!max) {
        max = start;
      } else {
        max = max > start ? start : max;
      }
      return false;
    }
    if (!start && end) {
      if (!min) {
        min = end;
      } else {
        min = min < end ? end : min;
      }
      return false;
    }
    if (end && start) {
      if (start > end) {
        warn('Datetime: Please check your disabledDate props returns');
        return false;
      }
      if (min && min >= start) {
        min = min < end ? end : min;
        return false;
      }
      if (max && max <= end) {
        max = max > start ? start : max;
        return false;
      }
      return true;
    }
    return true;
  });
  var startEnd = [];
  // 时间排序
  startEnd = newArr.sort(function (a, b) {
    return a.start - b.start;
  });
  return {
    maxTime: max,
    minTime: min,
    startEnd: startEnd
  };
}

/**
 * 求有限时间范围内的 disabledDate时间区间
 * @param { object } disabledArr
 * @param { string | number } minDateTime
 * @param { string | number } maxDateTime
 */

function getDateRangeArr(disabledDateObj, minDateTime, maxDateTime) {
  var minTime = disabledDateObj.minTime,
      maxTime = disabledDateObj.maxTime,
      startEnd = disabledDateObj.startEnd;
  // 时间范围

  var dateRangeArr = [];
  // 计算时间区间
  if (minTime) {
    // 计算小于区间
    if (minDateTime <= minTime) {
      dateRangeArr.push({
        start: minDateTime,
        end: minTime
      });
    }
  }
  /* eslint no-continue:0 */
  for (var i = 0; i < startEnd.length; i++) {
    // 计算中间区间
    var _startEnd$i = startEnd[i],
        start = _startEnd$i.start,
        end = _startEnd$i.end;

    if (end < start) {
      warn('Datetime: Please check your disabledDate props returns');
      continue;
    }
    if (start >= minDateTime && end <= maxDateTime) {
      // start end 都在 取值范围内
      dateRangeArr.push(startEnd[i]);
    }
    if (start <= minDateTime && end >= minDateTime && end <= maxDateTime) {
      // start 不在 end 在
      dateRangeArr.push({
        start: minDateTime,
        end: end
      });
      continue;
    }
    if (start >= minDateTime && start <= maxDateTime && end >= maxDateTime) {
      // end 不在 start 在
      dateRangeArr.push({
        start: start,
        end: maxDateTime
      });
      continue;
    }
    if (start <= minDateTime && end >= maxDateTime) {
      // end 不在 start 不在
      dateRangeArr.push({
        start: minDateTime,
        end: maxDateTime
      });
      continue;
    }
  }
  // 计算大于时间区间的范围
  if (maxTime) {
    if (maxDateTime > maxTime) {
      dateRangeArr.push({
        start: maxTime,
        end: maxDateTime
      });
    }
  }
  return dateRangeArr;
}

/**
 * 获取 options
 * @param {*} value
 * @param {*} props
 */
function getOptions(value, props) {
  var minDate = props.minDate,
      maxDate = props.maxDate;
  var minuteStep = props.minuteStep;

  minDate = (0, _base.parseDate)(minDate);
  maxDate = (0, _base.parseDate)(maxDate);
  if (maxDate <= minDate) {
    error(' Datetime： props maxDate must be greater than minDate ');
    return [];
  }
  minDate = new Date(minDate);
  maxDate = new Date(maxDate);
  var currentValue = new Date((0, _base.parseDate)(value));
  var dayYear = (0, _base.getDaysByYear)({ year: currentValue.getFullYear(), minDate: minDate, maxDate: maxDate });
  var options = [(0, _base.makeRange)(minDate.getFullYear(), maxDate.getFullYear()), (0, _base.makeRange)(1, 12).map(function (v) {
    return { text: '' + v, value: v - 1 };
  }), (0, _base.getDaysByMonth)({
    minDate: minDate, maxDate: maxDate, year: currentValue.getFullYear(), month: currentValue.getMonth()
  }), _locale2.default[props.locale].noon, (0, _base.makeRange)(0, 12), (0, _base.makeRange)(0, 23), (0, _base.makeRange)(0, 59, minuteStep), (0, _base.makeRange)(0, 59), dayYear, dayYear];
  return options;
}

/**
 * 过滤年份
 * @param { Array } arr
 * @param { object } disabledDateObj
 * @param { String } minDate
 */

function filterYear(arr, _ref) {
  var disabledDateObj = _ref.disabledDateObj,
      minDate = _ref.minDate,
      maxDate = _ref.maxDate;

  var minDateTime = new Date(minDate).getTime();
  var maxDateTime = new Date(maxDate).getTime();
  var yearRangeArr = getDateRangeArr(disabledDateObj, minDateTime, maxDateTime);
  var yearArr = [];
  yearRangeArr.forEach(function (item) {
    var start = item.start,
        end = item.end;

    start = new Date(start);
    end = new Date(end);
    var yearStart = start.getFullYear();
    var monthStart = start.getMonth();
    var dayStart = start.getDate();
    var yearEnd = end.getFullYear();
    var monthEnd = end.getMonth();
    var dayEnd = new Date(end.getTime() + 86400000).getDate();
    if (monthStart === 0 && dayStart === 1) {
      // 判断临界时 是否去掉整年
      if (monthEnd === 11 && dayEnd === 1) {
        for (var i = yearStart; i <= yearEnd; i++) {
          yearArr.push(i);
        }
      } else {
        for (var _i = yearStart; _i < yearEnd; _i++) {
          yearArr.push(_i);
        }
      }
    }
    if (monthEnd === 11 && dayEnd === 1) {
      for (var _i2 = yearStart + 1; _i2 <= yearEnd; _i2++) {
        yearArr.push(_i2);
      }
    } else {
      for (var _i3 = yearStart + 1; _i3 < yearEnd; _i3++) {
        yearArr.push(_i3);
      }
    }
  });
  return arr.filter(function (item) {
    var year = item.value;
    return yearArr.indexOf(year) === -1;
  });
}

/**
 * 过滤月份
 * @param { Array } arr
 * @param { Number } year
 * @param { object } disabledDateObj
 */

function filterMonth(arr, year, disabledDateObj) {
  var minDateTime = new Date(year, 0, 1).getTime();
  var maxDateTime = new Date(year, 11, 31).getTime();
  var monthRangeArr = getDateRangeArr(disabledDateObj, minDateTime, maxDateTime);
  var monthArr = [];
  monthRangeArr.forEach(function (item) {
    var start = item.start,
        end = item.end;

    start = new Date(start);
    end = new Date(end);

    var monthStart = start.getMonth();
    var monthEnd = end.getMonth();
    var dayStart = start.getDate();
    var dayEnd = new Date(end.getTime() + 86400000).getDate();
    if (dayStart === 1) {
      if (dayEnd === 1) {
        for (var i = monthStart; i <= monthEnd; i++) {
          monthArr.push(i);
        }
      } else {
        for (var _i4 = monthStart; _i4 < monthEnd; _i4++) {
          monthArr.push(_i4);
        }
      }
    }
    if (dayEnd === 1) {
      for (var _i5 = monthStart + 1; _i5 <= monthEnd; _i5++) {
        monthArr.push(_i5);
      }
    } else {
      for (var _i6 = monthStart + 1; _i6 < monthEnd; _i6++) {
        monthArr.push(_i6);
      }
    }
  });
  return arr.filter(function (item) {
    var month = item.value;
    return monthArr.indexOf(month) === -1;
  });
}

/**
 * 过滤日
 * @param { Array } arr
 * @param { Number } year
 * @param { Number } month
 * @param { object } disabledDateObj
 */
function filterDay(arr, year, month, disabledDateObj) {
  var minDateTime = new Date(year, month, 1).getTime();
  var maxDateTime = new Date(year, month + 1, 0).getTime();
  var dayRangeArr = getDateRangeArr(disabledDateObj, minDateTime, maxDateTime);
  var dayArr = [];
  dayRangeArr.forEach(function (item) {
    var start = item.start,
        end = item.end;

    start = new Date(start).getDate();
    end = new Date(end).getDate();
    for (var i = start; i <= end; i++) {
      dayArr.push(i);
    }
  });
  return arr.filter(function (item) {
    var day = item.value;
    return dayArr.indexOf(day) === -1;
  });
}

/**
 * 初始化过滤
 * @param { Array } data
 * @param { Array } value
 * @param { fun } disabledDate
 * @param { String|NUmber } minDate
 * @param { String|NUmber } maxDate
 * @param { array } disabledArr
 */

function filterDate(_ref2) {
  var data = _ref2.data,
      value = _ref2.value,
      disabledArr = _ref2.disabledArr,
      minDate = _ref2.minDate,
      maxDate = _ref2.maxDate,
      _ref2$oldData = _ref2.oldData,
      oldData = _ref2$oldData === undefined ? {} : _ref2$oldData,
      props = _ref2.props;

  var disabledArrNew = parseDisabledArr(disabledArr);
  var year = value[0].value;
  var month = value[1].value;
  var yearData = data[0];
  var monthData = (0, _base.getMonthsByYear)({ year: year, minDate: minDate, maxDate: maxDate });
  var dayData = (0, _base.getDaysByMonth)({
    year: year, month: month, minDate: minDate, maxDate: maxDate
  });
  if (disabledArrNew.startEnd || disabledArrNew.minTime || disabledArrNew.maxTime) {
    if (oldData.yearData) {
      yearData = oldData.yearData;
    } else {
      yearData = filterYear(yearData, { disabledDateObj: disabledArrNew, minDate: minDate, maxDate: maxDate });
    }
    if (oldData.monthData) {
      monthData = oldData.monthData;
    } else {
      var monthArr = filterMonth(monthData, year, disabledArrNew);
      monthData = monthArr.length ? monthArr : monthData;
    }
    var dayArr = filterDay(dayData, year, month, disabledArrNew);
    dayData = dayArr.length ? dayArr : dayData;
    var unit = _locale2.default[props.locale].surfix.D;
    dayData = dayData.map(function (item) {
      item.text = (0, _base.addZero)(item.text) + (unit || '');
      return item;
    });
  }
  if (disabledArrNew.minTime >= disabledArrNew.maxTime) {
    warn('Datetime: Please check your disabledDate props');
    return [];
  }
  if (!yearData.length) {
    return [];
  }
  var outArr = [yearData, monthData, dayData];
  if (data[3]) {
    outArr.push(data[3]);
  }
  return outArr;
}
function getSlotFormattedValue(value, props) {
  // 使用当前时间或传入时间作为默认值
  // 形成候选项
  var currentValueNew = parseValue(value);
  var options = getOptions(value, props);
  // 数据格式化
  var ret = _Slot2.default.formatDataValue([].concat(options), [].concat(currentValueNew));
  return formatFromProps(ret.value, props);
}
module.exports = {
  parseValue: parseValue,
  addDayOfWeek: addDayOfWeek,
  formatFromProps: formatFromProps,
  formatText: formatText,
  getOptions: getOptions,
  Slot: _Slot2.default,
  locale: _locale2.default,
  filterDate: filterDate,
  getSlotFormattedValue: getSlotFormattedValue
};