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, { useCallback, useMemo, useState } from 'react';
import { Spin, Tooltip } from 'antd';
import { useRequest } from 'ahooks';
import { locales } from '@pisell/utils';
import { PisellModal } from '@pisell/materials';
import Forms from "../../../components/booking/forms/forms";
import useEngineContext from "../../../hooks/useEngineContext";
import { getRelationRecords } from "../serve";
var BookingFormsPreview = function BookingFormsPreview(props) {
  var _context$appHelper;
  var context = useEngineContext();
  var utils = (context === null || context === void 0 || (_context$appHelper = context.appHelper) === null || _context$appHelper === void 0 ? void 0 : _context$appHelper.utils) || {};
  var value = props.value,
    uniqueTables = props.uniqueTables,
    bookingLabels = props.bookingLabels,
    textStyles = props.textStyles,
    relationId = props.relationId,
    relationType = props.relationType,
    customer = props.customer;
  var appointmentForms = Array.isArray(value) ? value : [];
  var _useState = useState(false),
    _useState2 = _slicedToArray(_useState, 2),
    modalOpen = _useState2[0],
    setModalOpen = _useState2[1];
  var _useState3 = useState(null),
    _useState4 = _slicedToArray(_useState3, 2),
    activeTable = _useState4[0],
    setActiveTable = _useState4[1];
  var _getRelationRecords = useRequest(getRelationRecords, {
    manual: true
  });
  var _useState5 = useState(false),
    _useState6 = _slicedToArray(_useState5, 2),
    hasRequested = _useState6[0],
    setHasRequested = _useState6[1];
  var _useState7 = useState(false),
    _useState8 = _slicedToArray(_useState7, 2),
    tooltipOpen = _useState8[0],
    setTooltipOpen = _useState8[1];
  var countsByFormId = useMemo(function () {
    return appointmentForms.reduce(function (result, item) {
      var formId = item === null || item === void 0 ? void 0 : item.form_id;
      if (formId != null) {
        var key = String(formId);
        result[key] = (result[key] || 0) + 1;
      }
      return result;
    }, {});
  }, [appointmentForms]);
  var tableItems = useMemo(function () {
    return (uniqueTables || []).map(function (t) {
      var _t$form, _t$form2;
      var baseTitle = (t === null || t === void 0 || (_t$form = t.form) === null || _t$form === void 0 || (_t$form = _t$form.setting) === null || _t$form === void 0 || (_t$form = _t$form.title) === null || _t$form === void 0 ? void 0 : _t$form.original) || (t === null || t === void 0 || (_t$form2 = t.form) === null || _t$form2 === void 0 ? void 0 : _t$form2.title) || '';
      if (!baseTitle) return null;
      var formId = t === null || t === void 0 ? void 0 : t.form_id;
      var count = formId != null ? countsByFormId[String(formId)] || 0 : 0;
      var title = "".concat(baseTitle, " (").concat(count, ")");
      return {
        title: title,
        baseTitle: baseTitle,
        formId: formId,
        count: count,
        table: t
      };
    }).filter(function (t) {
      return t;
    });
  }, [uniqueTables, countsByFormId]);
  var showAll = tableItems.length <= 3;
  var displayItems = showAll ? tableItems : tableItems.slice(0, 3);
  var moreCount = tableItems.length - displayItems.length;
  var handleOpenModal = useCallback(function (item, event) {
    event.stopPropagation();
    setActiveTable(item);
    setModalOpen(true);
    setTooltipOpen(false);
    if (!_getRelationRecords.loading && !hasRequested) {
      setHasRequested(true);
      _getRelationRecords.run({
        relation_type: relationType || 'appointment_booking',
        relation_id: relationId
      });
    }
  }, [_getRelationRecords, relationId, hasRequested, relationType]);
  var relationRecords = useMemo(function () {
    return Array.isArray(_getRelationRecords.data) ? _getRelationRecords.data : [];
  }, [_getRelationRecords.data]);
  var selectedForm = useMemo(function () {
    if (!(activeTable !== null && activeTable !== void 0 && activeTable.formId)) return null;
    var matchedRecord = relationRecords.find(function (item) {
      return String(item === null || item === void 0 ? void 0 : item.form_id) === String(activeTable === null || activeTable === void 0 ? void 0 : activeTable.formId);
    });
    return matchedRecord;
  }, [activeTable, relationRecords]);
  if (tableItems.length === 0) {
    return /*#__PURE__*/React.createElement("div", {
      style: {
        minWidth: 0,
        maxWidth: '100%',
        textAlign: 'center'
      }
    }, "-");
  }
  var tooltipContent = /*#__PURE__*/React.createElement("div", {
    style: {
      display: 'flex',
      flexDirection: 'column',
      gap: 10
    }
  }, tableItems.map(function (item, idx) {
    var clickable = item.count > 0;
    return /*#__PURE__*/React.createElement("div", {
      key: "".concat(item.title, "-").concat(idx),
      style: {
        fontSize: 12,
        color: clickable ? '#7f56d9' : '#98A2B3',
        textDecoration: clickable ? 'underline' : 'none',
        whiteSpace: 'nowrap',
        lineHeight: '18px',
        cursor: clickable ? 'pointer' : 'default'
      },
      onClick: function onClick(event) {
        if (!clickable) return;
        handleOpenModal(item, event);
      }
    }, item.title);
  }));
  return /*#__PURE__*/React.createElement("div", {
    onClick: function onClick(event) {
      return event.stopPropagation();
    },
    style: {
      minWidth: 0,
      maxWidth: '100%',
      overflow: 'hidden',
      boxSizing: 'border-box'
    }
  }, showAll ? /*#__PURE__*/React.createElement("div", {
    style: {
      display: 'flex',
      flexDirection: 'column'
    }
  }, displayItems.map(function (item, idx) {
    return /*#__PURE__*/React.createElement("div", {
      key: "".concat(item.title, "-").concat(idx),
      style: _objectSpread(_objectSpread({}, (textStyles === null || textStyles === void 0 ? void 0 : textStyles.text) || {}), {}, {
        color: '#7f56d9',
        textDecoration: 'underline',
        cursor: 'pointer',
        textAlign: 'left',
        overflow: 'hidden',
        textOverflow: 'ellipsis',
        whiteSpace: 'nowrap'
      }),
      onClick: function onClick(event) {
        return handleOpenModal(item, event);
      }
    }, item.title);
  })) : /*#__PURE__*/React.createElement("div", {
    style: {
      display: 'flex',
      flexDirection: 'column'
    }
  }, displayItems.map(function (item, idx) {
    return /*#__PURE__*/React.createElement("div", {
      key: "".concat(item.title, "-").concat(idx),
      style: _objectSpread(_objectSpread({}, (textStyles === null || textStyles === void 0 ? void 0 : textStyles.text) || {}), {}, {
        color: '#475467',
        textDecoration: 'none',
        cursor: 'default',
        textAlign: 'left',
        overflow: 'hidden',
        textOverflow: 'ellipsis',
        whiteSpace: 'nowrap'
      })
    }, item.title);
  }), moreCount > 0 ? /*#__PURE__*/React.createElement(Tooltip, {
    title: tooltipContent,
    open: modalOpen ? false : tooltipOpen,
    onOpenChange: function onOpenChange(nextOpen) {
      if (!modalOpen) {
        setTooltipOpen(nextOpen);
      }
    }
  }, /*#__PURE__*/React.createElement("div", {
    style: _objectSpread(_objectSpread({}, (textStyles === null || textStyles === void 0 ? void 0 : textStyles.text) || {}), {}, {
      color: '#7f56d9',
      textDecoration: 'underline',
      cursor: 'default',
      alignSelf: 'flex-start'
    })
  }, "+".concat(moreCount, " ").concat(locales.getText('pisell2.salesManagement.booking.common.more')))) : null), /*#__PURE__*/React.createElement(PisellModal, {
    open: modalOpen,
    title: bookingLabels === null || bookingLabels === void 0 ? void 0 : bookingLabels.forms,
    width: 600,
    footer: null,
    destroyOnClose: true,
    onCancel: function onCancel() {
      return setModalOpen(false);
    }
  }, _getRelationRecords.loading || !hasRequested ? /*#__PURE__*/React.createElement("div", {
    style: {
      display: 'flex',
      justifyContent: 'center',
      alignItems: 'center',
      padding: '48px 0'
    }
  }, /*#__PURE__*/React.createElement(Spin, null)) : selectedForm ? /*#__PURE__*/React.createElement(Forms
  // modalOpen={modalOpen}
  , {
    forms: [selectedForm],
    value: _defineProperty({}, selectedForm.form_id, selectedForm.form_record || []),
    onChange: function onChange() {},
    addCallback: function addCallback() {},
    client: customer,
    action: utils.action
  }) : null));
};
export default BookingFormsPreview;