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 React, { useEffect, useMemo, useState } from 'react';
import { Button } from 'antd';
// import type { CalendarProps } from 'antd';
import dayjs from 'dayjs';
import "./styles/index.less";
import classNames from 'classnames';
import { LeftOutlined, RightOutlined } from '@ant-design/icons';
import CalendarMonthPicker from "./CalendarMonthPicker";
import useStyle from "./styles";
var CalendarCoordPicker = function CalendarCoordPicker(props) {
  var _props$type = props.type,
    type = _props$type === void 0 ? 'directPick' : _props$type,
    year = props.year;
  var componentName = 'spec-calendar-coordinate';
  var _useStyle = useStyle(componentName),
    _useStyle2 = _slicedToArray(_useStyle, 2),
    wrapSSR = _useStyle2[0],
    hashId = _useStyle2[1];
  var _useState = useState(dayjs().year()),
    _useState2 = _slicedToArray(_useState, 2),
    yearNum = _useState2[0],
    setYearNum = _useState2[1];
  useEffect(function () {
    setYearNum(year || dayjs().year());
  }, [year]);
  // const cellDays = useMemo(() => {
  //   return
  // }, [])
  // const onPanelChange = (value: Dayjs, mode: CalendarProps<Dayjs>['mode']) => {
  //   console.log(value.format('YYYY-MM-DD'), mode);
  // };
  useEffect(function () {
    // 获取日历格子元素
    //     var calendarCells = document.querySelectorAll('.calendar-cell');
    var calendarCells = document.querySelectorAll('.ant-picker-cell');
    // console.log('calendarCells', calendarCells)
    // console.log('calendarCells', document.getElementsByClassName('ant-picker-cell-in-view'))
    // 记录鼠标按下的位置
    var startX, startY;

    // 记录鼠标框选的起始位置和结束位置
    //     let startCell: any;
    var endCell;
    var startCellIndex, endCellIndex;
    var startCellRect, endCellRect;
    var cellSelectProcessing = false;

    // 监听鼠标按下事件
    document.addEventListener('mousedown', function (event) {
      // 记录鼠标按下的位置
      startX = event.clientX;
      startY = event.clientY;
      var startCellConfig = getCellFromCoordinates(startX, startY);
      // 获取鼠标按下的日历格子
      // startCell = startCellConfig.cell;
      startCellIndex = startCellConfig.cellIndex;
      startCellRect = startCellConfig.cellRect;
      cellSelectProcessing = true;
    });

    // 监听鼠标移动事件
    document.addEventListener('mousemove', function (event) {
      // 获取鼠标移动的位置
      var currentX = event.clientX;
      var currentY = event.clientY;

      // 获取鼠标移动的日历格子
      var currentCellConfig = getCellFromCoordinates(currentX, currentY);
      var currentCell = currentCellConfig.cell;
      var currentCellIndex = currentCellConfig.cellIndex;
      var currentCellRect = currentCellConfig.cellRect;

      // 如果鼠标移动的日历格子不为空，则进行框选
      if (cellSelectProcessing && currentCell) {
        // 清除之前的框选样式
        clearSelection();
        // 设置当前日历格子的框选样式
        // currentCell.classList.add('spec-calendar-coordinate-picker__order-selected');
        // 记录结束位置
        endCell = currentCell;
        endCellIndex = currentCellIndex;
        endCellRect = currentCellRect;
        type === 'orderPick' ? getCellSelected() : getCellCoordinate();
      }
    });

    // 监听鼠标松开事件
    document.addEventListener('mouseup', function (event) {
      // 清除框选样式
      clearSelection();

      // 获取鼠标松开的位置
      var endX = event.clientX;
      var endY = event.clientY;

      // 获取鼠标松开的日历格子
      var endCellConfig = getCellFromCoordinates(endX, endY);
      endCell = endCellConfig.cell;
      endCellIndex = endCellConfig.cellIndex;
      endCellRect = endCellConfig.cellRect;

      // 如果鼠标松开的日历格子不为空，则进行框选
      if (endCell) {
        type === 'orderPick' ? getCellSelected() : getCellCoordinate();
      }
      cellSelectProcessing = false;
    });

    // 按坐标内的顺序选中
    var getCellSelected = function getCellSelected() {
      for (var i = Math.min(startCellIndex, endCellIndex); i <= Math.max(startCellIndex, endCellIndex); i++) {
        // const rect = calendarCells[i].getBoundingClientRect();
        if (calendarCells[i].classList.contains('ant-picker-cell-in-view')) {
          calendarCells[i].classList.add('spec-calendar-coordinate-picker__order-selected');
        }
      }
    };
    // 按坐标内的范围选中
    var getCellCoordinate = function getCellCoordinate() {
      var _startCellRect, _endCellRect, _startCellRect2, _endCellRect2, _startCellRect3, _endCellRect3;
      var direct = ''; // 选中单元格方位
      if (!startCellRect && !endCellRect) return;
      if (((_startCellRect = startCellRect) === null || _startCellRect === void 0 ? void 0 : _startCellRect.x) === ((_endCellRect = endCellRect) === null || _endCellRect === void 0 ? void 0 : _endCellRect.x)) {
        if (startCellRect.y === endCellRect.y) {
          direct = 'center';
        } else if (startCellRect.y > endCellRect.y) {
          direct = 'centerTop';
        } else if (startCellRect.y < endCellRect.y) {
          direct = 'centerBottom';
        }
      } else if (((_startCellRect2 = startCellRect) === null || _startCellRect2 === void 0 ? void 0 : _startCellRect2.x) > ((_endCellRect2 = endCellRect) === null || _endCellRect2 === void 0 ? void 0 : _endCellRect2.x)) {
        if (startCellRect.y === endCellRect.y) {
          direct = 'centerLeft';
        } else if (startCellRect.y > endCellRect.y) {
          direct = 'leftTop';
        } else if (startCellRect.y < endCellRect.y) {
          direct = 'leftBottom';
        }
      } else if (((_startCellRect3 = startCellRect) === null || _startCellRect3 === void 0 ? void 0 : _startCellRect3.x) < ((_endCellRect3 = endCellRect) === null || _endCellRect3 === void 0 ? void 0 : _endCellRect3.x)) {
        if (startCellRect.y === endCellRect.y) {
          direct = 'centerRight';
        } else if (startCellRect.y > endCellRect.y) {
          direct = 'rightTop';
        } else if (startCellRect.y < endCellRect.y) {
          direct = 'rightBottom';
        }
      }
      var selectedCells = []; // 过滤当前选中的单元格
      for (var i = 0; i < calendarCells.length; i++) {
        var rect = calendarCells[i].getBoundingClientRect();
        if (rect && calendarCells[i].classList.contains('ant-picker-cell-in-view')) {
          switch (direct) {
            case 'center':
              if (rect.x === endCellRect.x && rect.y === endCellRect.y) {
                selectedCells.push(calendarCells[i]);
              }
              break;
            case 'centerTop':
              if (rect.x === endCellRect.x && rect.y >= endCellRect.y && rect.x === endCellRect.x && rect.y <= startCellRect.y) {
                selectedCells.push(calendarCells[i]);
              }
              break;
            case 'centerBottom':
              if (rect.x === endCellRect.x && rect.y <= endCellRect.y && rect.x === endCellRect.x && rect.y >= startCellRect.y) {
                selectedCells.push(calendarCells[i]);
              }
              break;
            case 'centerRight':
              if (rect.y === endCellRect.y && rect.x <= endCellRect.x && rect.y === endCellRect.y && rect.x >= startCellRect.x) {
                selectedCells.push(calendarCells[i]);
              }
              break;
            case 'rightBottom':
              if (rect.y >= startCellRect.y && rect.y <= endCellRect.y && rect.x >= startCellRect.x && rect.x <= endCellRect.x) {
                selectedCells.push(calendarCells[i]);
              }
              break;
            case 'rightTop':
              if (rect.x >= startCellRect.x && rect.x <= endCellRect.x && rect.y >= endCellRect.y && rect.y <= startCellRect.y) {
                selectedCells.push(calendarCells[i]);
              }
              break;
            case 'centerLeft':
              if (rect.y === endCellRect.y && rect.x >= endCellRect.x && rect.y === endCellRect.y && rect.x <= startCellRect.x) {
                selectedCells.push(calendarCells[i]);
              }
              break;
            case 'leftBottom':
              if (rect.y >= startCellRect.y && rect.y <= endCellRect.y && rect.x <= startCellRect.x && rect.x >= endCellRect.x) {
                selectedCells.push(calendarCells[i]);
              }
              break;
            case 'leftTop':
              if (rect.y <= startCellRect.y && rect.y >= endCellRect.y && rect.x <= startCellRect.x && rect.x >= endCellRect.x) {
                selectedCells.push(calendarCells[i]);
              }
              break;
          }
        }
      }
      // console.log('selectedCells', calendarCells)
      for (var j = 0; j < selectedCells.length; j++) {
        // rect.x  >= startX && rect.x  <= overX && rect.y >= startY && rect.y <= overY
        selectedCells[j].classList.add('spec-calendar-coordinate-picker__directed-selected');
      }
    };
    // 获取指定坐标的日历格子（按坐标）
    var getCellFromCoordinates = function getCellFromCoordinates(x, y) {
      var cell = null;
      var cellIndex = null;
      var cellRect = null; // 当前格子的坐标信息
      // 遍历所有日历格子
      for (var i = 0; i < calendarCells.length; i++) {
        var rect = calendarCells[i].getBoundingClientRect();
        // 判断坐标是否在日历格子的范围内
        if (x >= rect.left && x <= rect.right && y >= rect.top && y <= rect.bottom) {
          cell = calendarCells[i];
          cellIndex = i;
          cellRect = rect;
          break;
        }
      }
      return {
        cellIndex: cellIndex,
        cell: cell,
        cellRect: cellRect
      };
    };

    // 清除框选样式
    var clearSelection = function clearSelection() {
      for (var i = 0; i < calendarCells.length; i++) {
        calendarCells[i].classList.remove('spec-calendar-coordinate-picker__order-selected');
        calendarCells[i].classList.remove('spec-calendar-coordinate-picker__directed-selected');
      }
    };
    return function () {
      document.removeEventListener('mousedown', function () {}, false);
      document.removeEventListener('mousemove', function () {}, false);
      document.removeEventListener('mouseup', function () {}, false);
    };
  }, [type]);
  var renderPickerHeader = function renderPickerHeader(_ref) {
    var value = _ref.value;
    //
    // const start = 0;
    // const end = 12;
    // const monthOptions = [];
    var current = value.clone();
    var localeData = value.localeData();
    var months = [];
    for (var i = 0; i < 12; i++) {
      current.month(i);
      months.push(localeData.monthsShort(current));
    }
    return /*#__PURE__*/React.createElement("div", {
      style: {
        textAlign: 'right',
        fontSize: '16px',
        paddingRight: '10px'
      }
    }, months[value.month()]);
  };
  var monthArray = useMemo(function () {
    var months = [];
    for (var i = 0; i < 12; i++) {
      months.push(i + 1);
    }
    return months;
  }, []);
  return wrapSSR( /*#__PURE__*/React.createElement("div", {
    className: classNames(componentName, hashId)
  }, /*#__PURE__*/React.createElement("div", {
    className: 'spec-calendar-coordinate-header'
  }, /*#__PURE__*/React.createElement("div", {
    className: 'spec-calendar-coordinate-header-action prev'
  }, /*#__PURE__*/React.createElement(Button, {
    size: 'small',
    icon: /*#__PURE__*/React.createElement(LeftOutlined, null),
    title: "".concat(yearNum - 1, "\u5E74"),
    onClick: function onClick() {
      return setYearNum(yearNum - 1);
    }
  })), /*#__PURE__*/React.createElement("div", {
    className: 'spec-calendar-coordinate-header-year'
  }, yearNum, "\u5E74"), /*#__PURE__*/React.createElement("div", {
    className: 'spec-calendar-coordinate-header-action  next'
  }, /*#__PURE__*/React.createElement(Button, {
    size: 'small',
    icon: /*#__PURE__*/React.createElement(RightOutlined, null),
    title: "".concat(yearNum + 1, "\u5E74"),
    onClick: function onClick() {
      return setYearNum(yearNum + 1);
    }
  }))), /*#__PURE__*/React.createElement("div", {
    className: 'spec-calendar-coordinate-picker'
  }, monthArray.map(function (mItem) {
    return /*#__PURE__*/React.createElement("div", {
      className: 'spec-calendar-coordinate-picker-col',
      key: mItem
    }, /*#__PURE__*/React.createElement(CalendarMonthPicker, {
      month: mItem,
      year: yearNum,
      headerRender: renderPickerHeader
    }));
  }))));
};
export default CalendarCoordPicker;