import weui from '../../../utils/weui';

export function timePicker(options) {
  const { start, end, defaultTime } = options;
  // start time
  const [startHour, startMin] = (start || '00:00').split(':');
  const startTime = parseInt(startHour) * 60 + parseInt(startMin);
  // end time
  const [endHour, endMin] = (end || '23:59').split(':');
  const endTime = parseInt(endHour) * 60 + parseInt(endMin);
  if (startTime > endTime) {
    throw 'startTime is bigger then endTime';
  }
  // init time
  const nowTime = new Date();
  const [initHour, initMin] = (
    defaultTime || `${nowTime.getHours()}:${nowTime.getMinutes()}`
  ).split(':');
  const initTime = parseInt(initHour) * 60 + parseInt(initMin);
  const fixInitTime = Math.max(startTime, Math.min(endTime, initTime));
  const fixInitHour = parseInt(fixInitTime / 60);
  const fixInitMin = parseInt(fixInitTime % 60);

  const hours = [];
  for (let hour = 0; hour < 24; hour++) {
    const mins = [];
    for (let min = 0; min < 60; min++) {
      const now = hour * 60 + min;
      if (now >= startTime && now <= endTime) {
        mins.push({
          value: min < 10 ? `0${min}` : `${min}`,
          label: min < 10 ? `0${min}` : `${min}`,
        });
      }
    }
    if (mins.length > 0) {
      hours.push({
        value: hour < 10 ? `0${hour}` : `${hour}`,
        label: hour < 10 ? `0${hour}` : `${hour}`,
        children: mins,
      });
    }
  }

  const defaultValue = [
    fixInitHour < 10 ? `0${fixInitHour}` : `${fixInitHour}`,
    fixInitMin < 10 ? `0${fixInitMin}` : `${fixInitMin}`,
  ];
  weui.picker(hours, {
    ...options,
    start: [startHour, startMin],
    end: [endHour, endMin],
    defaultValue,
  });
}
