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, { forwardRef, useEffect, useImperativeHandle, useMemo, useRef, useState } from 'react';
import { LeftOutlined, RightOutlined } from '@ant-design/icons';
import { Button } from 'antd';
import { DatePicker, Iconfont, SelectTime } from '@pisell/materials';
import { locales } from '@pisell/utils';
import { useMemoizedFn } from 'ahooks';
import classNames from 'classnames';
import dayjs from 'dayjs';
import useEngineContext from "../../../../hooks/useEngineContext";
import CompensatedPisellContainer from "../../../../pro/compensatedPisellContainer";
import { subscribeBookingDateChange, useSalesSdkBookingContext } from "../../../../plus/salesSdk";
import { withResponsive } from "../../../../responsive";
import localeTexts from "../../locales";
import "./index.less";
var DISPLAY_DATE_FORMAT = 'YYYY-MM-DD';
function resolveDate(rawDate) {
  if (rawDate && dayjs(rawDate).isValid()) {
    return dayjs(rawDate);
  }
  return dayjs();
}

/**
 * BigSaleTimeBar 只同步 SalesSdk BookingContext，不依赖 ticketBooking 的 mini-redux。
 */
var BigSaleTimeBar = /*#__PURE__*/forwardRef(function (props, ref) {
  var _engineContext$appHel, _engineContext$appHel2, _engineContext$appHel3, _context$sales$tempOr, _context$sales$salesD;
  var context = props.context,
    productLoadParams = props.productLoadParams,
    _props$locale = props.locale,
    locale = _props$locale === void 0 ? 'en' : _props$locale,
    orderId = props.orderId,
    _props$variant = props.variant,
    variant = _props$variant === void 0 ? 'desktop' : _props$variant,
    mobileDrawerOpen = props.mobileDrawerOpen,
    onMobileDrawerClose = props.onMobileDrawerClose;
  var engineContext = useEngineContext();
  var bookingContext = useSalesSdkBookingContext();
  var intervalRef = useRef(null);
  var _useState = useState(function () {
      return resolveDate(bookingContext.getDate());
    }),
    _useState2 = _slicedToArray(_useState, 2),
    currentDate = _useState2[0],
    setCurrentDate = _useState2[1];
  var _useState3 = useState(true),
    _useState4 = _slicedToArray(_useState3, 2),
    collapsed = _useState4[0],
    setCollapsed = _useState4[1];
  var _useState5 = useState(1),
    _useState6 = _slicedToArray(_useState5, 2),
    scaleCompensation = _useState6[0],
    setScaleCompensation = _useState6[1];
  var _useState7 = useState(true),
    _useState8 = _slicedToArray(_useState7, 2),
    intervalSetTime = _useState8[0],
    setIntervalSetTime = _useState8[1];
  var _useState9 = useState(false),
    _useState10 = _slicedToArray(_useState9, 2),
    isDateChange = _useState10[0],
    setIsDateChange = _useState10[1];
  var _useState11 = useState(false),
    _useState12 = _slicedToArray(_useState11, 2),
    isTimeChange = _useState12[0],
    setIsTimeChange = _useState12[1];
  var _useState13 = useState(false),
    _useState14 = _slicedToArray(_useState13, 2),
    internalMobileDrawerOpen = _useState14[0],
    setInternalMobileDrawerOpen = _useState14[1];
  var mergedMobileDrawerOpen = mobileDrawerOpen !== null && mobileDrawerOpen !== void 0 ? mobileDrawerOpen : internalMobileDrawerOpen;
  locales.init(localeTexts, (engineContext === null || engineContext === void 0 || (_engineContext$appHel = engineContext.appHelper) === null || _engineContext$appHel === void 0 || (_engineContext$appHel = _engineContext$appHel.utils) === null || _engineContext$appHel === void 0 || (_engineContext$appHel2 = _engineContext$appHel.getApp) === null || _engineContext$appHel2 === void 0 || (_engineContext$appHel2 = _engineContext$appHel2.call(_engineContext$appHel)) === null || _engineContext$appHel2 === void 0 || (_engineContext$appHel2 = _engineContext$appHel2.locales) === null || _engineContext$appHel2 === void 0 || (_engineContext$appHel3 = _engineContext$appHel2.getLocale) === null || _engineContext$appHel3 === void 0 ? void 0 : _engineContext$appHel3.call(_engineContext$appHel2)) || locale);
  useEffect(function () {
    setCurrentDate(resolveDate(bookingContext.getDate()));
  }, [bookingContext, context.sales.bookingTicket]);

  /** 订阅 OS BookingContext 日期变更，保持 TimeBar 与 store 同步。 */
  useEffect(function () {
    if (!context.sales.bookingTicket) return;
    return subscribeBookingDateChange(context.sales.bookingTicket, function (rawDate) {
      setCurrentDate(resolveDate(rawDate));
    });
  }, [context.sales.bookingTicket]);

  /**
   * SDK ready 后启动「跟随当前时间」定时器（对齐 ticketBooking `_setIntervalTime(true)`，不 reload 商品）。
   */
  useEffect(function () {
    if (!context.sales.isReady || !context.sales.bookingTicket) return;
    startNowInterval(false);
    return function () {
      stopInterval();
    };
  }, [context.sales.isReady, context.sales.bookingTicket]);
  useEffect(function () {
    var getBodyScale = function getBodyScale() {
      var transform = window.getComputedStyle(document.body).transform;
      if (!transform || transform === 'none') return 1;
      var matrix = transform.match(/matrix\(([^)]+)\)/);
      if (!matrix) return 1;
      var values = matrix[1].split(',').map(function (value) {
        return parseFloat(value.trim());
      });
      return values[0] || 1;
    };
    var updateScale = function updateScale() {
      setScaleCompensation(getBodyScale());
    };
    updateScale();
    var observer = new MutationObserver(updateScale);
    observer.observe(document.body, {
      attributes: true,
      attributeFilter: ['style', 'class']
    });
    window.addEventListener('resize', updateScale);
    return function () {
      observer.disconnect();
      window.removeEventListener('resize', updateScale);
    };
  }, []);
  useEffect(function () {
    return function () {
      if (intervalRef.current) {
        clearInterval(intervalRef.current);
      }
    };
  }, []);
  var reloadProducts = useMemoizedFn(function () {
    var _context$sales$bookin, _context$sales$bookin2, _context$sales$bookin3;
    var catalogLen = (_context$sales$bookin = (_context$sales$bookin2 = context.sales.bookingTicket) === null || _context$sales$bookin2 === void 0 || (_context$sales$bookin3 = _context$sales$bookin2.getProductCatalog) === null || _context$sales$bookin3 === void 0 || (_context$sales$bookin3 = _context$sales$bookin3.call(_context$sales$bookin2)) === null || _context$sales$bookin3 === void 0 || (_context$sales$bookin3 = _context$sales$bookin3.products) === null || _context$sales$bookin3 === void 0 ? void 0 : _context$sales$bookin3.length) !== null && _context$sales$bookin !== void 0 ? _context$sales$bookin : 0;
    var hasCatalog = catalogLen > 0 || context.products.products.length > 0;
    context.products.load(productLoadParams, {
      silent: hasCatalog
    }).catch(function (error) {
      console.error(error);
    });
  });
  var applyDate = useMemoizedFn(function (date) {
    var shouldReloadProducts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
    setCurrentDate(date);
    if (!context.sales.bookingTicket) return;
    bookingContext.setDate(date);
    if (shouldReloadProducts) {
      reloadProducts();
    }
  });
  var stopInterval = useMemoizedFn(function () {
    if (intervalRef.current) {
      clearInterval(intervalRef.current);
      intervalRef.current = null;
    }
    setIntervalSetTime(false);
  });

  /**
   * 开启「跟随当前时间」模式。
   * - 定时 tick 只同步 BookingContext（对齐 ticketBooking `_setDataChange`，不 reload 商品）
   * - 用户点 Today/Now 时传 shouldReloadProducts=true
   *
   * @example
   * startNowInterval(false); // mount 时
   * startNowInterval(true);  // 用户点「现在」
   */
  var startNowInterval = useMemoizedFn(function () {
    var shouldReloadProducts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
    if (intervalRef.current) {
      clearInterval(intervalRef.current);
    }
    setIsDateChange(false);
    setIsTimeChange(false);
    setIntervalSetTime(true);
    applyDate(dayjs(), shouldReloadProducts);
    intervalRef.current = setInterval(function () {
      applyDate(dayjs(), false);
    }, 1000 * 60);
  });
  var closeMobileDrawer = useMemoizedFn(function () {
    setInternalMobileDrawerOpen(false);
    onMobileDrawerClose === null || onMobileDrawerClose === void 0 || onMobileDrawerClose();
  });
  var openMobileDrawer = useMemoizedFn(function () {
    setInternalMobileDrawerOpen(true);
  });
  useImperativeHandle(ref, function () {
    return {
      openMobileDrawer: openMobileDrawer,
      closeMobileDrawer: closeMobileDrawer
    };
  });
  var handlePreviousDay = useMemoizedFn(function () {
    var newDate = currentDate.subtract(1, 'day');
    stopInterval();
    setIsDateChange(true);
    applyDate(newDate, true);
  });
  var handleNextDay = useMemoizedFn(function () {
    var newDate = currentDate.add(1, 'day');
    stopInterval();
    setIsDateChange(true);
    applyDate(newDate, true);
  });
  var handleDateChange = useMemoizedFn(function (date) {
    if (!date) return;
    stopInterval();
    setIsDateChange(true);
    applyDate(date, true);
  });
  var handleTimeChange = useMemoizedFn(function (timeString) {
    var _timeString$split$map = timeString.split(':').map(Number),
      _timeString$split$map2 = _slicedToArray(_timeString$split$map, 2),
      hours = _timeString$split$map2[0],
      minutes = _timeString$split$map2[1];
    var newDate = currentDate.hour(hours).minute(minutes).second(0);
    setIsTimeChange(true);
    applyDate(newDate, true);
    if (timeString === dayjs().format('HH:mm')) {
      startNowInterval(true);
    } else {
      stopInterval();
    }
  });
  var handleCreateClick = useMemoizedFn(function () {
    context.sales.createNew().then(function () {
      startNowInterval(false);
    }).catch(function (error) {
      console.error(error);
    });
  });
  var hasExistingOrder = Boolean(orderId || ((_context$sales$tempOr = context.sales.tempOrder) === null || _context$sales$tempOr === void 0 ? void 0 : _context$sales$tempOr.order_id) || ((_context$sales$salesD = context.sales.salesDetail) === null || _context$sales$salesD === void 0 || (_context$sales$salesD = _context$sales$salesD.header) === null || _context$sales$salesD === void 0 ? void 0 : _context$sales$salesD.order_id));
  var dateFormat = locale === 'en' ? 'dddd, DD MMM YYYY' : 'YYYY年MM月DD日';
  var collapsedHeight = 40 / scaleCompensation;
  return useMemo(function () {
    var isToday = currentDate.isSame(dayjs(), 'day');
    var collapsedText = isToday ? locales.getText('pisell2.big-sale.today') : currentDate.format(DISPLAY_DATE_FORMAT);
    if (variant === 'phone') {
      return /*#__PURE__*/React.createElement(CompensatedPisellContainer, {
        renderType: "drawer",
        showHandlerBar: true,
        onHandlerBarClick: closeMobileDrawer,
        props: {
          open: mergedMobileDrawerOpen,
          onClose: closeMobileDrawer,
          placement: 'bottom',
          header: false,
          footer: false,
          closable: false,
          destroyOnClose: false,
          className: 'pisell-big-sale-time-bar-drawer-phone',
          contentWrapperStyle: {
            maxWidth: 'none',
            height: 'auto'
          },
          styles: {
            body: {
              padding: 0
            }
          }
        }
      }, /*#__PURE__*/React.createElement("div", {
        className: "pisell-big-sale-time-bar-phone",
        style: {
          backgroundColor: isDateChange ? '#F79009' : undefined
        }
      }, /*#__PURE__*/React.createElement("div", {
        className: "pisell-big-sale-time-bar-phone__nav"
      }, /*#__PURE__*/React.createElement(Button, {
        icon: /*#__PURE__*/React.createElement(LeftOutlined, null),
        onClick: handlePreviousDay,
        size: "large"
      }), /*#__PURE__*/React.createElement("div", {
        className: classNames('pisell-big-sale-time-bar-phone__field', {
          'pisell-big-sale-time-bar__picker--selected': isDateChange
        })
      }, /*#__PURE__*/React.createElement(DatePicker, {
        inputReadOnly: true,
        value: currentDate,
        format: locale === 'en' ? 'DD MMM YYYY' : 'YYYY年MM月DD日',
        onChange: handleDateChange,
        size: "large",
        style: {
          width: '100%'
        }
      })), /*#__PURE__*/React.createElement(Button, {
        icon: /*#__PURE__*/React.createElement(RightOutlined, null),
        onClick: handleNextDay,
        size: "large"
      })), /*#__PURE__*/React.createElement(Button, {
        block: true,
        onClick: function onClick() {
          return startNowInterval(true);
        },
        size: "large",
        style: intervalSetTime ? {
          background: '#000',
          color: '#fff'
        } : undefined
      }, locales.getText('pisell2.big-sale.today')), /*#__PURE__*/React.createElement("div", {
        className: classNames('pisell-big-sale-time-bar-phone__field', {
          'pisell-big-sale-time-bar__picker--selected': isTimeChange
        })
      }, /*#__PURE__*/React.createElement(SelectTime, {
        value: currentDate.format('HH:mm'),
        onChange: handleTimeChange,
        popoverProps: {
          style: {
            zoom: 0.8
          }
        },
        timePickerProps: {},
        timeProps: {},
        slice: 5
      })), !hasExistingOrder && /*#__PURE__*/React.createElement(Button, {
        block: true,
        onClick: function onClick() {
          return startNowInterval(true);
        },
        size: "large",
        style: intervalSetTime ? {
          background: '#000',
          color: '#fff'
        } : undefined
      }, locales.getText('pisell2.big-sale.now')), hasExistingOrder && /*#__PURE__*/React.createElement(Button, {
        block: true,
        onClick: function onClick() {
          handleCreateClick();
          closeMobileDrawer();
        },
        size: "large",
        type: "primary"
      }, locales.getText('pisell2.big-sale.create-new'))));
    }
    if (collapsed) {
      return /*#__PURE__*/React.createElement("div", {
        className: classNames('pisell-big-sale-time-bar', 'pisell-big-sale-time-bar--collapsed', "pisell-big-sale-time-bar--".concat(variant)),
        style: {
          height: collapsedHeight,
          minHeight: collapsedHeight,
          maxHeight: collapsedHeight
        }
      }, /*#__PURE__*/React.createElement("div", {
        className: "pisell-big-sale-time-bar__collapsed-content",
        style: {
          height: collapsedHeight
        }
      }, /*#__PURE__*/React.createElement("span", {
        className: "pisell-big-sale-time-bar__collapsed-date",
        style: {
          lineHeight: "".concat(collapsedHeight, "px")
        }
      }, collapsedText), /*#__PURE__*/React.createElement(Button, {
        type: "link",
        size: "small",
        className: "pisell-big-sale-time-bar__collapsed-expand",
        onClick: function onClick() {
          return setCollapsed(false);
        },
        style: {
          lineHeight: "".concat(collapsedHeight, "px")
        }
      }, /*#__PURE__*/React.createElement("span", null, locales.getText('pisell2.big-sale.expand')), /*#__PURE__*/React.createElement(Iconfont, {
        type: "pisell2-chevron-right-double"
      }))));
    }
    return /*#__PURE__*/React.createElement("div", {
      className: classNames('pisell-big-sale-time-bar', "pisell-big-sale-time-bar--".concat(variant)),
      style: {
        backgroundColor: isDateChange ? '#F79009' : undefined
      }
    }, /*#__PURE__*/React.createElement("div", {
      className: "pisell-big-sale-time-bar__scroll"
    }, /*#__PURE__*/React.createElement("div", {
      className: "pisell-big-sale-time-bar__scroll-content"
    }, /*#__PURE__*/React.createElement(Button, {
      icon: /*#__PURE__*/React.createElement(LeftOutlined, null),
      onClick: handlePreviousDay,
      size: "large"
    }), /*#__PURE__*/React.createElement(Button, {
      onClick: function onClick() {
        return startNowInterval(true);
      },
      size: "large",
      style: intervalSetTime ? {
        background: '#000',
        color: '#fff'
      } : undefined
    }, locales.getText('pisell2.big-sale.today')), /*#__PURE__*/React.createElement("div", {
      className: classNames('pisell-big-sale-time-bar__date-picker', {
        'pisell-big-sale-time-bar__picker--selected': isDateChange
      })
    }, /*#__PURE__*/React.createElement(DatePicker, {
      inputReadOnly: true,
      value: currentDate,
      format: dateFormat,
      onChange: handleDateChange,
      size: "large",
      style: {
        width: '100%'
      }
    })), /*#__PURE__*/React.createElement(Button, {
      icon: /*#__PURE__*/React.createElement(RightOutlined, null),
      onClick: handleNextDay,
      size: "large"
    }), /*#__PURE__*/React.createElement("div", {
      className: classNames('pisell-big-sale-time-bar__time-picker', {
        'pisell-big-sale-time-bar__picker--selected': isTimeChange
      })
    }, /*#__PURE__*/React.createElement(SelectTime, {
      value: currentDate.format('HH:mm'),
      onChange: handleTimeChange,
      popoverProps: {
        style: {
          zoom: 0.8
        }
      },
      timePickerProps: {},
      timeProps: {},
      slice: 5
    })), !hasExistingOrder && /*#__PURE__*/React.createElement(Button, {
      onClick: function onClick() {
        return startNowInterval(true);
      },
      size: "large",
      style: intervalSetTime ? {
        background: '#000',
        color: '#fff'
      } : undefined
    }, locales.getText('pisell2.big-sale.now')), hasExistingOrder && /*#__PURE__*/React.createElement(Button, {
      onClick: handleCreateClick,
      size: "large",
      type: "primary"
    }, locales.getText('pisell2.big-sale.create-new')))), /*#__PURE__*/React.createElement(Button, {
      type: "link",
      className: "pisell-big-sale-time-bar__collapse",
      onClick: function onClick() {
        return setCollapsed(true);
      }
    }, /*#__PURE__*/React.createElement("span", null, locales.getText('pisell2.big-sale.collapse')), /*#__PURE__*/React.createElement(Iconfont, {
      type: "pisell2-chevron-left-double"
    })));
  }, [collapsed, collapsedHeight, currentDate, dateFormat, handleCreateClick, handleDateChange, handleNextDay, handlePreviousDay, handleTimeChange, hasExistingOrder, intervalSetTime, isDateChange, isTimeChange, locale, closeMobileDrawer, mergedMobileDrawerOpen, startNowInterval, variant]);
});
BigSaleTimeBar.displayName = 'BigSaleTimeBar';
export default withResponsive(BigSaleTimeBar);