function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
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 dayjs from "dayjs";
import React, { useEffect, useState, useRef, useContext, useMemo } from "react";
import CalendarItem from "./calendarItem";
import { Context } from "../model";
import { createArray } from "@pisell/utils";
import "./index.less";
import { useRequest } from "ahooks";
import { getScheduleAvailability } from "./serve";
import { Spin } from "antd";
import { formatAvailability } from "./utils";
var MONTH_CARD_WIDTH = 300;
var Calendar = function Calendar() {
  var _useContext = useContext(Context),
    state = _useContext.state,
    dispatch = _useContext.dispatch;
  var calendar = state.calendar,
    currentSelectDayDetail = state.currentSelectDayDetail;
  var _ref = calendar || {},
    allData = _ref.allData,
    editData = _ref.editData,
    isEdit = _ref.isEdit;
  var _ref2 = currentSelectDayDetail || {},
    selectDate = _ref2.date;
  var calenderRef = useRef(null);
  // 每行显示的列数
  var _useState = useState(4),
    _useState2 = _slicedToArray(_useState, 2),
    colCount = _useState2[0],
    setColCount = _useState2[1];
  // 日期范围/今年初到明年中
  var _useState3 = useState([dayjs().format("YYYY-01"), dayjs().add(1, "year").format("YYYY-06")]),
    _useState4 = _slicedToArray(_useState3, 1),
    dateRange = _useState4[0];

  // 年份为key值的月份列表
  var _useState5 = useState({}),
    _useState6 = _slicedToArray(_useState5, 2),
    monthData = _useState6[0],
    setMonthDate = _useState6[1];

  // 根据日期范围列举月份列表
  useEffect(function () {
    var startMonth = dayjs(dateRange[0]);
    var endMonth = dayjs(dateRange[1]);
    var months = _defineProperty({}, dayjs(dateRange[0]).format("YYYY"), [dateRange[0]]);
    var currentMonth = startMonth;
    while (currentMonth.isBefore(endMonth) || currentMonth.isSame(endMonth, "month")) {
      currentMonth = currentMonth.add(1, "month");
      var year = currentMonth.format("YYYY");
      if (!months[year]) {
        months[year] = [];
      }
      months[year].push(currentMonth.format("YYYY-MM"));
    }
    setMonthDate(months);
  }, [dateRange]);
  useEffect(function () {
    if (!calenderRef.current) {
      return;
    }
    // 监听尺寸变化
    var resizeObserver = new ResizeObserver(function () {
      var _calenderRef$current;
      var width = ((_calenderRef$current = calenderRef.current) === null || _calenderRef$current === void 0 ? void 0 : _calenderRef$current.clientWidth) || 0;
      var colCount = Math.floor((width - 20) / MONTH_CARD_WIDTH);
      setColCount(colCount > 4 ? 4 : colCount);
    });
    resizeObserver.observe(calenderRef.current);
    return function () {
      resizeObserver.disconnect();
    };
  }, []);
  var _useRequest = useRequest(getScheduleAvailability, {
      manual: true,
      onSuccess: function onSuccess(result, params) {
        if (result.status) {
          dispatch({
            type: "setCalendar",
            payload: {
              sourceData: result.data,
              allData: formatAvailability(result.data)
            }
          });
        }
      }
    }),
    loading = _useRequest.loading,
    run = _useRequest.run,
    refresh = _useRequest.refresh;
  useEffect(function () {
    run({});
  }, []);
  var handleSelectDate = function handleSelectDate(date, item) {
    if (isEdit) {
      return;
    }
    if (selectDate === date) {
      dispatch({
        type: "setState",
        payload: {
          currentSelectDayDetail: null
        }
      });
    } else {
      dispatch({
        type: "setState",
        payload: {
          currentSelectDayDetail: {
            date: date,
            scheduleIds: item === null || item === void 0 ? void 0 : item.schedule_ids
          }
        }
      });
    }
    dispatch({
      type: "setCalendar",
      payload: {
        isEdit: false,
        editData: []
      }
    });
  };
  var schedulesData = useMemo(function () {
    if (isEdit) {
      return editData || [];
    }
    return allData;
  }, [isEdit, allData, editData]);
  return /*#__PURE__*/React.createElement(Spin, {
    spinning: loading
  }, /*#__PURE__*/React.createElement("div", {
    className: "calender-box",
    ref: calenderRef
  }, Object.keys(monthData).map(function (year) {
    return /*#__PURE__*/React.createElement("div", {
      key: year,
      className: "calender-year-wrap"
    }, /*#__PURE__*/React.createElement("div", {
      className: "calender-year"
    }, year), /*#__PURE__*/React.createElement("div", {
      className: "month-list"
    }, monthData[year].map(function (month, index) {
      return /*#__PURE__*/React.createElement("div", {
        className: "month-item-box month-item-".concat(colCount),
        key: index,
        style: {
          // width: `calc(100% / ${colCount})`,
        }
      }, /*#__PURE__*/React.createElement(CalendarItem, {
        isEdit: isEdit,
        month: month,
        schedulesData: schedulesData,
        selectDate: selectDate,
        onSelect: handleSelectDate
      }));
    }), monthData[year].length % colCount ? createArray(colCount - monthData[year].length % colCount, function (_, i) {
      return /*#__PURE__*/React.createElement("div", {
        key: i,
        style: {
          width: MONTH_CARD_WIDTH
        }
      });
    }) : null));
  })));
};
export default Calendar;