function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
var _excluded = ["picker", "onChange", "value", "format", "defaultValue", "showTime"];
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(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
function _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
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(arr, i) { var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"]; if (null != _i) { var _s, _e, _x, _r, _arr = [], _n = !0, _d = !1; try { if (_x = (_i = _i.call(arr)).next, 0 === i) { if (Object(_i) !== _i) return; _n = !1; } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0); } catch (err) { _d = !0, _e = err; } finally { try { if (!_n && null != _i.return && (_r = _i.return(), Object(_r) !== _r)) return; } finally { if (_d) throw _e; } } return _arr; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
import React, { useContext, useEffect, useMemo, useRef, useState } from 'react';
import dayjs from 'dayjs';
import classNames from 'classnames';
import { Button, ConfigProvider, DatePicker, Drawer, Input, Modal } from 'antd';
import BrowserSelect from "../browserSelect";
import { isFunction } from '@pisell/utils';
import { presetDetailMap } from "./constants";
import { getText } from "../../locales";
import useResponsive, { configResponsive } from "../../hooks/useResponsive";
import "./index.less";
var isValidDate = function isValidDate(dateString, format) {
  var date = window.dayjs(dateString, format, true);
  return date.isValid();
};
configResponsive({
  phone: 0,
  ipad: 768,
  pc: 1080
});
var DatePickerCpt = function DatePickerCpt(props) {
  var picker = props.picker,
    onChange = props.onChange,
    value = props.value,
    propsFormat = props.format,
    defaultValue = props.defaultValue,
    showTime = props.showTime,
    others = _objectWithoutProperties(props, _excluded);
  var _useContext = useContext(ConfigProvider.ConfigContext),
    locale = _useContext.locale;
  var _useState = useState(''),
    _useState2 = _slicedToArray(_useState, 2),
    currentShortcut = _useState2[0],
    setCurrentShortcut = _useState2[1];
  var _useState3 = useState(false),
    _useState4 = _slicedToArray(_useState3, 2),
    open = _useState4[0],
    setOpen = _useState4[1];
  var _useState5 = useState(false),
    _useState6 = _slicedToArray(_useState5, 2),
    popupOpen = _useState6[0],
    setPopupOpen = _useState6[1];
  var _useState7 = useState(value),
    _useState8 = _slicedToArray(_useState7, 2),
    _value = _useState8[0],
    setValue = _useState8[1];
  var _useState9 = useState(''),
    _useState10 = _slicedToArray(_useState9, 2),
    valueStr = _useState10[0],
    setValueStr = _useState10[1];
  var _useState11 = useState(false),
    _useState12 = _slicedToArray(_useState11, 2),
    error = _useState12[0],
    setError = _useState12[1];
  var ref = useRef(null);
  var panelRef = useRef(null);
  var canClose = useRef(true);
  var _useState13 = useState(0),
    _useState14 = _slicedToArray(_useState13, 2),
    panelTimeWidth = _useState14[0],
    setPanelTimeWidth = _useState14[1];

  // const isDesktop = useMediaQuery('@media (pointer: fine)');

  var responsive = useResponsive();
  var isDesktop = !('ontouchstart' in window || navigator.maxTouchPoints);
  useEffect(function () {
    document.body.id = 'body';
  }, []);
  useEffect(function () {
    setValue(value);
  }, [value]);
  useEffect(function () {
    setValueStr((_value === null || _value === void 0 ? void 0 : _value.format(format || 'YYYY-MM-DD')) || '');
  }, [_value]);
  var customPresetItems = useMemo(function () {
    var preset = [{
      label: presetDetailMap['today'].label(),
      value: 'today'
    }, {
      label: presetDetailMap['yesterday'].label(),
      value: 'yesterday'
    }, {
      label: presetDetailMap['tomorrow'].label(),
      value: 'tomorrow'
    }, {
      label: presetDetailMap['next_monday'].label(),
      value: 'next_monday'
    }, {
      label: presetDetailMap['last_friday'].label(),
      value: 'last_friday'
    }, {
      label: presetDetailMap['first_day_of_this_month'].label(),
      value: 'first_day_of_this_month'
    }, {
      label: presetDetailMap['last_day_of_this_month'].label(),
      value: 'last_day_of_this_month'
    }, {
      label: presetDetailMap['first_day_of_next_month'].label(),
      value: 'first_day_of_next_month'
    }, {
      label: presetDetailMap['last_day_of_last_month'].label(),
      value: 'last_day_of_last_month'
    }];
    if (!currentShortcut) {
      preset.push({
        label: getText('date-picker-shortcut-custom'),
        value: 'custom'
      });
    }
    return preset;
  }, [currentShortcut]);
  var format = useMemo(function () {
    if (propsFormat) {
      if (isFunction(propsFormat)) {
        return propsFormat(value);
      }
      return propsFormat + (showTime !== null && showTime !== void 0 && showTime.format ? " ".concat(showTime === null || showTime === void 0 ? void 0 : showTime.format) : '');
    }
    var localeValue = locale === null || locale === void 0 ? void 0 : locale.locale;
    return localeValue === 'en' || localeValue === 'en-US' ? 'DD/MM/YYYY' : 'YYYY/MM/DD';
  }, [propsFormat, locale]);
  var handleSelectChange = function handleSelectChange(e) {
    var _presetDetailMap;
    canClose.current = true;
    var shortcut = e.target.value;
    setCurrentShortcut(shortcut);
    var date = (_presetDetailMap = presetDetailMap[shortcut]) === null || _presetDetailMap === void 0 ? void 0 : _presetDetailMap.getValue();
    setValue(date);
    handleOk(date);
  };
  var handleTodayClick = function handleTodayClick() {
    var val = dayjs().startOf('day');
    handleChange(val);
    handleOpenChange(false);
  };
  var handleOpenChange = function handleOpenChange(visible) {
    if (!visible) {
      setOpen(visible);
      setTimeout(function () {
        var _ref$current;
        setPopupOpen(visible);
        (_ref$current = ref.current) === null || _ref$current === void 0 ? void 0 : _ref$current.blur();
      });
      return;
    }
    setOpen(visible);
    setPopupOpen(visible);
  };
  var handleOk = function handleOk(val) {
    var _returnValue;
    var returnValue = val;
    if (returnValue !== null) {
      returnValue = returnValue || _value;
    }
    onChange === null || onChange === void 0 ? void 0 : onChange(returnValue, (_returnValue = returnValue) === null || _returnValue === void 0 ? void 0 : _returnValue.format('YYYY-MM-DD'));
    handleOpenChange(false);
  };
  var handleChange = function handleChange(val, valStr, isNotChange) {
    if (!showTime) {
      canClose.current = true;
    }
    setError(false);
    setCurrentShortcut('');
    setValue(val);
    if (!isNotChange) {
      handleOk(val);
    }
  };
  var handleApply = function handleApply() {
    if (error) return;
    handleOk();
  };
  var handleDataStrChange = function handleDataStrChange(e) {
    var val = e.target.value;
    setValueStr(val);
    if (isValidDate(val, format)) {
      setError(false);
      var valDate = dayjs(val, format);
      setValue(valDate);
    } else {
      setError(true);
    }
  };
  useEffect(function () {
    var _panelRef$current;
    var width = 0;
    var childElements = ((_panelRef$current = panelRef.current) === null || _panelRef$current === void 0 ? void 0 : _panelRef$current.getElementsByClassName('pisell-lowcode-picker-time-panel')) || [];
    if (childElements.length > 0) {
      var childElement = childElements[0];
      width = childElement.offsetWidth;
    }
    if (width > 0) {
      setPanelTimeWidth(width);
    }
  }, [open]);
  var handleSelect = function handleSelect(val) {
    canClose.current = !showTime;
    setValue(val);
  };
  var handleTimeChange = function handleTimeChange(val) {
    setValue(function (preVal) {
      var _preVal$set, _preVal$set$set;
      return (preVal === null || preVal === void 0 ? void 0 : (_preVal$set = preVal.set('hour', (val === null || val === void 0 ? void 0 : val.get('hour')) || 0)) === null || _preVal$set === void 0 ? void 0 : (_preVal$set$set = _preVal$set.set('minute', (val === null || val === void 0 ? void 0 : val.get('minute')) || 0)) === null || _preVal$set$set === void 0 ? void 0 : _preVal$set$set.set('second', (val === null || val === void 0 ? void 0 : val.get('second')) || 0)) || null;
    });
  };
  var timeInputProps = useMemo(function () {
    var step = 1;
    var _format = '';
    if ((showTime === null || showTime === void 0 ? void 0 : showTime.format) === 'HH:mm') {
      step = undefined;
      _format = 'HH:mm';
    } else if ((showTime === null || showTime === void 0 ? void 0 : showTime.format) === 'HH:mm:ss' || showTime) {
      step = 1;
      _format = 'HH:mm:ss';
    }
    return {
      step: step,
      onChange: function onChange(e) {
        var val = e.target.value;
        handleTimeChange(window.dayjs(val, _format));
      },
      value: _value === null || _value === void 0 ? void 0 : _value.format(_format)
    };
  }, [showTime, _value]);
  if (!picker || picker === 'date') {
    return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(DatePicker, _extends({}, others, {
      ref: ref,
      onSelect: handleSelect,
      showTime: isDesktop ? showTime : false,
      defaultValue: defaultValue,
      showNow: false,
      onChange: function onChange(val, valStr) {
        return handleChange(val, valStr, !isDesktop && showTime);
      },
      open: popupOpen,
      renderExtraFooter: !(!showTime || isDesktop) ? function () {
        return /*#__PURE__*/React.createElement("div", {
          onMouseDown: function onMouseDown(e) {
            canClose.current = false;
            e.stopPropagation();
          }
        }, /*#__PURE__*/React.createElement("div", {
          className: "date-picker-time-label"
        }, "Time"), /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement("input", _extends({
          type: "time",
          className: "date-picker-input-time"
        }, timeInputProps))));
      } : undefined,
      className: classNames('pisell-lowcode-mode-date-picker', others.className),
      value: _value,
      onOpenChange: function onOpenChange(o) {
        if (!o && (!canClose.current || showTime)) {
          return;
        }
        handleOpenChange(o);
      },
      mode: "date",
      picker: "date",
      popupClassName: "date-picker-popup-wrap",
      format: currentShortcut ? function () {
        return presetDetailMap[currentShortcut].label();
      } : format,
      panelRender: function panelRender(panelNode) {
        var dom = /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("div", {
          className: classNames('pisell-lowcode-date-picker-custom-wrap', _defineProperty({}, 'pisell-lowcode-date-picker-custom-wrap-show-time', showTime)),
          ref: panelRef
        }, !showTime && /*#__PURE__*/React.createElement("div", {
          className: "pisell-lowcode-date-picker-custom-action",
          onMouseDown: function onMouseDown(e) {
            canClose.current = false;
            e.stopPropagation();
          },
          style: {
            width: "calc(100% - 48px - ".concat(panelTimeWidth, "px)")
          }
        }, /*#__PURE__*/React.createElement("div", {
          style: {
            width: '50%'
          }
        }, /*#__PURE__*/React.createElement(Input, {
          size: "large",
          placeholder: dayjs().format(format || 'YYYY-MM-DD'),
          value: valueStr,
          onChange: handleDataStrChange
        }), error && /*#__PURE__*/React.createElement("span", {
          className: "date-picker-error"
        }, getText('date-picker-invalid-date'))), /*#__PURE__*/React.createElement(BrowserSelect
        // @ts-ignore
        , {
          value: currentShortcut || 'custom',
          className: "date-picker-toolbar-select",
          options: customPresetItems
          // @ts-ignore
          ,
          size: 'large',
          onChange: handleSelectChange,
          style: {
            width: '50%'
          }
        })), panelNode), /*#__PURE__*/React.createElement("div", {
          className: "pisell-lowcode-custom-footer"
        }, /*#__PURE__*/React.createElement("span", {
          className: "pisell-lowcode-custom-footer-today",
          onClick: handleTodayClick
        }, getText('date-picker-today')), /*#__PURE__*/React.createElement(Button, {
          type: "primary",
          size: "large",
          onClick: handleApply
        }, getText('date-picker-apply'))));
        if (isDesktop) {
          return /*#__PURE__*/React.createElement("div", {
            className: "pisell-lowcode-date-picker-custom-popup-wrap pisell-lowcode-date-picker-dropdown-mode"
          }, /*#__PURE__*/React.createElement("div", {
            className: "pisell-lowcode-date-picker-custom-wrap"
          }, dom));
        }
        if (responsive === 'phone') {
          return /*#__PURE__*/React.createElement(Drawer, {
            placement: "bottom",
            open: open,
            height: "auto",
            closable: false,
            styles: {
              content: {
                borderRadius: '8px 8px 0 0'
              }
            },
            bodyStyle: {
              padding: 0
            },
            maskClosable: false
          }, /*#__PURE__*/React.createElement("div", {
            className: "pisell-lowcode-picker-custom-dropdown pisell-lowcode-date-picker-custom-popup-wrap",
            onMouseDown: function onMouseDown(e) {
              return e.stopPropagation();
            }
          }, /*#__PURE__*/React.createElement("div", {
            className: "pisell-lowcode-picker-panel-container pisell-lowcode-picker-date-panel-container"
          }, dom)));
        }
        return /*#__PURE__*/React.createElement(Modal, {
          width: 458,
          open: open,
          footer: null,
          closable: false,
          wrapClassName: 'pisell-lowcode-date-picker-modal'
        }, /*#__PURE__*/React.createElement("div", {
          className: "pisell-lowcode-picker-custom-dropdown pisell-lowcode-date-picker-custom-popup-wrap",
          onMouseDown: function onMouseDown(e) {
            return e.stopPropagation();
          }
        }, /*#__PURE__*/React.createElement("div", {
          className: "pisell-lowcode-picker-panel-container pisell-lowcode-picker-date-panel-container"
        }, dom)));
      }
    })));
  }
  return /*#__PURE__*/React.createElement(DatePicker, props);
};
export default DatePickerCpt;