function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
import { useState, useImperativeHandle, forwardRef, useMemo } from 'react';
import Dayjs from 'dayjs';
import isSameOrBefore from 'dayjs/plugin/isSameOrBefore';
import { PisellModal, Iconfont } from '@pisell/materials';
import { isMobile } from '@pisell/utils';
Dayjs.extend(isSameOrBefore);
import { weekListText, statusColor, getStatus, getCallToBookStatus } from "./state";
import classNames from 'classnames';
import Status from "./Status";

// 引入组件
// import { useDrawer } from '@/pisell-design/hooks';

import "./index.less";
var CalendarDate = function CalendarDate(props, ref) {
  var cutTime = props.cutTime,
    getLimitData = props.getLimitData,
    dateLimitData = props.dateLimitData,
    loading = props.loading;
  var _useState = useState(''),
    _useState2 = _slicedToArray(_useState, 2),
    productId = _useState2[0],
    setProductId = _useState2[1];
  var _useState3 = useState(''),
    _useState4 = _slicedToArray(_useState3, 2),
    currentDate = _useState4[0],
    setCurrentDate = _useState4[1];
  // 生成7天的时间列表
  var _useState5 = useState([]),
    _useState6 = _slicedToArray(_useState5, 2),
    dateMonthList = _useState6[0],
    setDateMonthList = _useState6[1];
  // 切换的月份
  var _useState7 = useState(function () {
      return Dayjs();
    }),
    _useState8 = _slicedToArray(_useState7, 2),
    currentMonth = _useState8[0],
    setCurrentMonth = _useState8[1];
  var _useState9 = useState(false),
    _useState10 = _slicedToArray(_useState9, 2),
    open = _useState10[0],
    setOpen = _useState10[1];

  // 计算开始渲染的列
  var startingColumn = 0 % 7; // 0 表示星期日
  var columns = Array.from({
    length: 7
  }, function (_, index) {
    return (index + 7 - startingColumn) % 7;
  });

  /**
   * @title: 接口和当前月进行对比
   * @description:
   * @param {*}
   * @return {*}
   * @Author: 严文强
   * @Date: 2024-02-01 20:30
   */
  var calendarDays = function calendarDays(days, list) {
    var index = list === null || list === void 0 ? void 0 : list.find(function (i) {
      return (i === null || i === void 0 ? void 0 : i.day) == days;
    });
    if (!index) {
      return 0;
    } else {
      return index === null || index === void 0 ? void 0 : index.status;
    }
  };

  /**
   * @title: 获取当前月日期
   * @description:
   * @param {*}
   * @return {*}
   * @Author: 严文强
   * @Date: 2024-02-01 20:30
   */
  var getMonthData = function getMonthData(date) {
    var firstDay = Dayjs("".concat(date, "-01"));
    var startDay = firstDay.day(); // 获取本月1号是星期几
    var daysInMonth = firstDay.daysInMonth(); // 获取本月总天数
    var monthData = [];
    // 填充前面的空白
    for (var i = 0; i < startDay; i++) {
      monthData.push({
        day: -1,
        // 表示前一个月的日期
        date: Dayjs(firstDay).subtract(startDay - i, 'day').toDate()
      });
    }

    // 填充本月的日期
    for (var _i = 1; _i <= daysInMonth; _i++) {
      monthData.push({
        day: _i,
        date: firstDay.date(_i).format('YYYY-MM-DD')
      });
    }
    return monthData;
  };

  /**
   * @title: 计算是否已经切换到当前月，如果是则禁止继续点击上一个月
   * @description:
   * @param {*}
   * @return {*}
   * @Author: 严文强
   * @Date: 2024-02-01 19:27
   */
  var lastMonthDisable = function lastMonthDisable() {
    var newCurrentMonth = currentMonth.format('YYYY-MM');
    var lastDate = Dayjs(newCurrentMonth).subtract(1, 'month');
    return lastDate.isBefore(Dayjs(), 'month');
  };

  /**
   * @title: 切换上个月
   * @description:
   * @param {*}
   * @return {*}
   * @Author: 严文强
   * @Date: 2024-02-01 19:15
   */
  var lastMonth = function lastMonth() {
    var currentLastText = currentMonth.format('YYYY-MM');
    var newLastMonth = Dayjs(currentLastText).subtract(1, 'month');
    setCurrentMonth(newLastMonth);
    setDateMonthList(getMonthData(newLastMonth.format('YYYY-MM')));
  };

  /**
   * @title: 切换下个月
   * @description:
   * @param {*}
   * @return {*}
   * @Author: 严文强
   * @Date: 2024-02-01 19:15
   */
  var nextMonth = function nextMonth() {
    var currentMonthText = currentMonth.format('YYYY-MM');
    var newNextMonth = Dayjs(currentMonthText).add(1, 'month');
    setCurrentMonth(newNextMonth);
    setDateMonthList(getMonthData(newNextMonth.format('YYYY-MM')));
  };

  /**
   * @title: 根据当前选择的月份剩余量
   * @description:
   * @return {*}
   * @Author: xiangxiang.shao
   * @Date: 2024-02-07 14:13
   */
  // useEffect(() => {
  //   if (productId) {
  //     getLimitData(
  //       currentMonth.format('YYYY-MM-01'),
  //       currentMonth.endOf('month').format('YYYY-MM-DD')
  //     );
  //   }
  // }, [currentMonth.format('YYYY-MM'), productId]);

  var CalendarDateContent = useMemo(function () {
    return /*#__PURE__*/React.createElement("div", {
      className: 'calendar-box'
    }, /*#__PURE__*/React.createElement("div", {
      className: 'calendar-header'
    }, /*#__PURE__*/React.createElement("div", {
      className: classNames('calendar-last-month', {
        'last-month-disabled': lastMonthDisable()
      }),
      onClick: function onClick() {
        if (lastMonthDisable()) return;
        lastMonth();
      }
    }, /*#__PURE__*/React.createElement(Iconfont, {
      type: "pisell2-chevron-left"
    })), /*#__PURE__*/React.createElement("div", {
      className: 'calendar-current-month'
    }, currentMonth.format('MMMM YYYY')), /*#__PURE__*/React.createElement("div", {
      className: 'calendar-next-month',
      onClick: function onClick() {
        nextMonth();
      }
    }, /*#__PURE__*/React.createElement(Iconfont, {
      type: "pisell2-chevron-right"
    }))), /*#__PURE__*/React.createElement("div", {
      className: 'calendar-content'
    }, /*#__PURE__*/React.createElement("div", {
      className: 'calendar-weeks'
    }, columns.map(function (col) {
      return /*#__PURE__*/React.createElement("div", {
        key: col,
        className: 'calendar-weeks-items'
      }, weekListText[Number(col)]);
    })), /*#__PURE__*/React.createElement("div", {
      className: 'calendar-days'
    }, dateMonthList.map(function (day, index) {
      var date = Dayjs(day.date).format('YYYY-MM-DD');
      var _getStatus = getStatus(dateLimitData, date, cutTime),
        status = _getStatus.status,
        disabled = _getStatus.disabled;
      var isShowCallToBook = getCallToBookStatus(date, dateLimitData, cutTime);
      // 在当天和cut-off time的日期之前这段日期，如果某天还存在可预约的商品，才显示Call to book。
      var currentStatus = isShowCallToBook && (status === 'lots_of_space' || status === 'filling_up_fast') ? 'call_to_book' : status;
      return /*#__PURE__*/React.createElement("div", {
        key: index,
        className: classNames('calendar-days-items', {
          disabledDate: disabled || loading,
          disabledSelect: status === 'sold_out',
          selectDate: currentDate === date,
          'other-month-days': (day === null || day === void 0 ? void 0 : day.day) < 1
        }),
        onClick: function onClick() {
          if (loading) return;
          props.dateChange(date);
          // hideModal();
        }
      }, (day === null || day === void 0 ? void 0 : day.day) >= 1 && /*#__PURE__*/React.createElement("div", {
        style: {
          '--lineColor': !loading ? statusColor[currentStatus] : ''
        },
        className: classNames('day-text', {
          'day-line': !disabled
        })
      }, (day === null || day === void 0 ? void 0 : day.day) < 1 ? '' : day === null || day === void 0 ? void 0 : day.day));
    }))), /*#__PURE__*/React.createElement(Status, {
      style: {
        margin: 0
      }
    }));
  }, [currentMonth, dateMonthList, getLimitData, currentDate]);
  useImperativeHandle(ref, function () {
    return {
      open: function open(date, id) {
        // setProductId(id);
        // showModal();
        setOpen(true);
        var daysText = Dayjs(date).format('YYYY-MM');
        setCurrentMonth(Dayjs(date));
        setCurrentDate(date);
        setDateMonthList(getMonthData(daysText));
      }
    };
  });
  return /*#__PURE__*/React.createElement(PisellModal, {
    open: open,
    title: 'device',
    mobileModalHeight: 'auto',
    platform: isMobile() ? 'h5' : 'pc',
    bodyStyle: {
      padding: isMobile() ? '16px 24px' : 32
    },
    destroyOnClose: true,
    className: "select-holder-modal",
    footer: null,
    onCancel: function onCancel() {
      return setOpen(false);
    }
  }, CalendarDateContent);
};
export default /*#__PURE__*/forwardRef(CalendarDate);