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 ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
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 React, { useEffect, useLayoutEffect, useMemo, useCallback, useState, useRef } from 'react';
import { Select, Space } from 'antd';
import debounce from 'lodash/debounce';
import dayjs from 'dayjs';
import { getUniqueId, locales } from '@pisell/utils';
var Option = Select.Option;
var getSelectInput = function getSelectInput(id) {
  var input = document.getElementById(id);
  if (input) {
    return input;
  }
};
var setSelectInputType = function setSelectInputType(_ref) {
  var input = _ref.input,
    type = _ref.type;
  if (input) {
    input.type = type;
  }
};
var DateSectionCom = function DateSectionCom(_ref2) {
  var value = _ref2.value,
    onChange = _ref2.onChange,
    showTime = _ref2.showTime,
    _ref2$className = _ref2.className,
    className = _ref2$className === void 0 ? '' : _ref2$className,
    _ref2$style = _ref2.style,
    style = _ref2$style === void 0 ? {} : _ref2$style,
    _ref2$useSpace = _ref2.useSpace,
    useSpace = _ref2$useSpace === void 0 ? true : _ref2$useSpace,
    format = _ref2.format,
    _ref2$itemStyle = _ref2.itemStyle,
    itemStyle = _ref2$itemStyle === void 0 ? {
      width: 100
    } : _ref2$itemStyle;
  var currentYear = dayjs().year();
  var locale = locales.locale;
  var dayRef = useRef(null);
  var monthRef = useRef(null);
  var yearRef = useRef(null);
  var _useState = useState({
      year: value ? dayjs(value).year() : null,
      month: value ? dayjs(value).month() + 1 : null,
      day: value ? dayjs(value).date() : null
    }),
    _useState2 = _slicedToArray(_useState, 2),
    date = _useState2[0],
    setDate = _useState2[1];
  var _useState3 = useState([]),
    _useState4 = _slicedToArray(_useState3, 2),
    dayOptions = _useState4[0],
    setDayOptions = _useState4[1];
  var _useState5 = useState([]),
    _useState6 = _slicedToArray(_useState5, 2),
    monthOptions = _useState6[0],
    setMonthOptions = _useState6[1];
  var _useState7 = useState([]),
    _useState8 = _slicedToArray(_useState7, 2),
    yearOptions = _useState8[0],
    setYearOptions = _useState8[1];
  var localeMap = {
    year: locales.getText('pisell2.text.date-year-text'),
    month: locales.getText('pisell2.text.date-month-text'),
    day: locales.getText('pisell2.text.date-day-text')
  };
  useEffect(function () {
    setDate({
      year: value ? dayjs(value).year() : null,
      month: value ? dayjs(value).month() + 1 : null,
      day: value ? dayjs(value).date() : null
    });
  }, [value]);
  useEffect(function () {
    setMonthOptions(renderOptions('month', 1, 12));
    setYearOptions(renderOptions('year', currentYear - 100, currentYear + 50));
  }, []);
  useEffect(function () {
    setDayOptions(renderOptions('day', 1, date.month ? getDaysInMonth(date.year || currentYear, date.month) : 31));
  }, [date.month, date.year]);

  /**
   * @title: 下拉框变化
   * @description:
   * @param {any} field
   * @param {any} value
   * @return {*}
   * @Author: chensheng.gu
   * @Date: 2024-03-22 17:49
   */
  var handleDateChange = function handleDateChange(field, value) {
    if (!value) {
      return;
    }
    var newDate = _defineProperty({
      year: date.year,
      month: date.month,
      day: date.day
    }, field, value);
    var foucsList = {
      day: monthRef,
      month: yearRef
    };

    // 如果是月份需要判断下日期
    if (field === 'month' || field === 'year') {
      var _newDate2, _newDate3, _newDate4;
      var daysInMonth = getDaysInMonth(((_newDate2 = newDate) === null || _newDate2 === void 0 ? void 0 : _newDate2.year) || currentYear, (_newDate3 = newDate) === null || _newDate3 === void 0 ? void 0 : _newDate3.month);
      var newDay = ((_newDate4 = newDate) === null || _newDate4 === void 0 ? void 0 : _newDate4.day) > daysInMonth ? daysInMonth : newDate.day;
      newDate = _objectSpread(_objectSpread({}, newDate), {}, {
        day: newDay
      });
    }
    setDate(newDate);
    if (foucsList[field]) {
      foucsList[field].current.focus();
    } else {
      yearRef.current.blur();
    }
    var _format = format || 'YYYY-MM-DD';
    if (newDate.year && newDate.month && newDate.day) {
      var _date = "".concat(newDate.year, "-").concat(newDate.month.toString().padStart(2, '0'), "-").concat(newDate.day.toString().padStart(2, '0'));
      onChange(dayjs(_date).format(_format));
    }
  };

  /**
   * @title: 获取日期
   * @description:
   * @param {any} year
   * @param {any} month
   * @return {*}
   * @Author: chensheng.gu
   * @Date: 2024-03-22 17:49
   */
  var getDaysInMonth = function getDaysInMonth(year, month) {
    return dayjs("".concat(year, "-").concat(month), 'YYYY-MM').daysInMonth();
  };

  /**
   * @title: 渲染下拉框列表
   * @description:
   * @param {any} field
   * @param {any} start
   * @param {any} end
   * @return {*}
   * @Author: chensheng.gu
   * @Date: 2024-03-22 17:50
   */
  var renderOptions = function renderOptions(field, start, end) {
    var options = [];
    var _text = locale !== 'en-US' && locale !== 'en' ? localeMap[field] : '';
    for (var i = start; i <= end; i++) {
      options.push({
        label: "".concat(i).concat(_text),
        value: i
      });
    }
    return options;
  };
  var selectId = useMemo(function () {
    return {
      dayId: getUniqueId('day'),
      monthId: getUniqueId('month'),
      yearId: getUniqueId('year')
    };
  }, []);
  useLayoutEffect(function () {
    setSelectInputType({
      input: getSelectInput(selectId.dayId),
      type: 'number'
    });
    setSelectInputType({
      input: getSelectInput(selectId.monthId),
      type: 'number'
    });
    setSelectInputType({
      input: getSelectInput(selectId.yearId),
      type: 'number'
    });
  }, [selectId]);
  var handleDateSearch = useCallback(debounce(function (field, value) {
    var dateOption = {
      day: dayOptions,
      month: monthOptions,
      year: yearOptions
    };
    var _value = Number(value);
    var index = dateOption[field].findIndex(function (item) {
      return item.value === _value;
    });
    if (index !== -1) {
      handleDateChange(field, _value);
    } else {
      handleDateChange(field, null);
    }
  }, 300), [dayOptions, monthOptions, yearOptions, date]);
  var content = /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(Select, {
    id: selectId.dayId,
    value: date.day,
    placeholder: locales.getText('pisell2.text.date-day-text'),
    onChange: function onChange(value) {
      return handleDateChange('day', value);
    },
    style: itemStyle,
    showSearch: true,
    onSearch: function onSearch(value) {
      handleDateSearch('day', value);
    },
    ref: dayRef,
    size: "large"
  }, dayOptions.map(function (item) {
    return /*#__PURE__*/React.createElement(Option, {
      key: item.value,
      value: item.value
    }, item.label);
  })), /*#__PURE__*/React.createElement(Select, {
    id: selectId.monthId,
    value: date.month,
    placeholder: locales.getText('pisell2.text.date-month-text'),
    onChange: function onChange(value) {
      return handleDateChange('month', value);
    },
    style: itemStyle,
    showSearch: true,
    onSearch: function onSearch(value) {
      handleDateSearch('month', value);
    },
    ref: monthRef,
    size: "large"
  }, monthOptions.map(function (item) {
    return /*#__PURE__*/React.createElement(Option, {
      key: item.value,
      value: item.value
    }, item.label);
  })), /*#__PURE__*/React.createElement(Select, {
    id: selectId.yearId,
    value: date.year,
    placeholder: locales.getText('pisell2.text.date-year-text'),
    onChange: function onChange(value) {
      return handleDateChange('year', value);
    },
    style: itemStyle,
    showSearch: true,
    onSearch: function onSearch(value) {
      handleDateSearch('year', value);
    },
    ref: yearRef,
    size: "large"
  }, yearOptions.map(function (item) {
    return /*#__PURE__*/React.createElement(Option, {
      key: item.value,
      value: item.value
    }, item.label);
  })));
  if (useSpace) {
    return /*#__PURE__*/React.createElement(Space, {
      className: className || '',
      style: style || {}
    }, content);
  }
  return /*#__PURE__*/React.createElement("div", {
    className: className || '',
    style: style || {}
  }, content);
};
export default DateSectionCom;