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, useRef, useState } from 'react';
import { useMemoizedFn } from 'ahooks';
import { locales } from '@pisell/utils';
import { PisellToast } from '@pisell/materials';
import "./index.less";
import SearchSection from "../../../../pro/comprehensiveSearch/components/searchSection";
import { useModal, useScanListener, useGetShopId } from "../../hooks";
import { SEARCH_BAR_RESULT_HEADER_CONFIG } from "./const";
import { useSearch, useCupScanStatus } from "./hooks";
import CupStatusModal from "../CupStatusModal";
import { ECupScanStatus } from "../../types";
import dayjs from 'dayjs';
var SearchBar = function SearchBar(props) {
  var scanListenerKey = props.scanListenerKey,
    _props$size = props.size,
    size = _props$size === void 0 ? 'large' : _props$size,
    placeholder = props.placeholder,
    onSearch = props.onSearch,
    searchType = props.searchType,
    onSearchResult = props.onSearchResult,
    customerId = props.customerId,
    onCupStatusValidate = props.onCupStatusValidate;
  var _useState = useState(''),
    _useState2 = _slicedToArray(_useState, 2),
    value = _useState2[0],
    setValue = _useState2[1];
  // 搜索结果
  var _useState3 = useState(null),
    _useState4 = _slicedToArray(_useState3, 2),
    searchResult = _useState4[0],
    setSearchResult = _useState4[1];
  var containerRef = useRef(null);
  // 扫码监听
  var _useScanListener = useScanListener(),
    addListener = _useScanListener.addListener,
    removeListener = _useScanListener.removeListener,
    setActiveListener = _useScanListener.setActiveListener;
  var searchHook = useSearch();
  var _useCupScanStatus = useCupScanStatus(),
    getCupScanStatus = _useCupScanStatus.getCupScanStatus;
  var cupStatusModal = useModal('ecocup-cup-status-modal');
  var shopId = useGetShopId();

  // 点击搜索结果回调
  var onSelectResult = useMemoizedFn(function (type, item) {
    setSearchResult(null);
    setValue('');
    onSearchResult === null || onSearchResult === void 0 || onSearchResult({
      type: type,
      data: item
    });
  });

  // 扫码或输入搜索回调
  var scanSearchCallback = useMemoizedFn(function (str) {
    console.log('scanSearchCallback>>>>>>>', str);
    if (onSearch) {
      onSearch(str || '');
      return;
    }
    if (!str) {
      setValue('');
      setSearchResult(null);
      return;
    }
    searchHook.run({
      searchType: searchType,
      searchText: str
    }).then(function (res) {
      if ((res === null || res === void 0 ? void 0 : res.status) === 'success') {
        var _res$data2;
        if ((res === null || res === void 0 ? void 0 : res.type) === 'cup') {
          var _res$data;
          var _cupData = (res === null || res === void 0 || (_res$data = res.data) === null || _res$data === void 0 ? void 0 : _res$data[0]) || null;
          var scanStatus = getCupScanStatus(_cupData, customerId);
          console.log(scanStatus, _cupData, shopId, 'sjdhfjj');

          // 自定义杯子状态函数验证
          if (onCupStatusValidate) {
            // 当前杯子属于当前店铺并且在库中
            // if (_cupData?.status == ECupStatus.IN_STOCK) {
            //   if (_cupData?.current_shop_id == shopId) {
            //     cupStatusModal.open({
            //       data: {
            //         scanStatus: ECupScanStatus.IN_STOCK,
            //         cupData: _cupData || { code: str },
            //       },
            //     });
            //     return;
            //   }
            // }

            if (scanStatus && scanStatus === ECupScanStatus.OTHER_RENT) {
              onCupStatusValidate === null || onCupStatusValidate === void 0 || onCupStatusValidate({
                data: _cupData || {
                  code: str
                }
              });
              setValue('');
              return;
            }
          }
          if (scanStatus) {
            cupStatusModal.open({
              data: {
                scanStatus: scanStatus,
                cupData: _cupData || {
                  code: str
                }
              }
            });
            return;
          }
        }
        var dataLength = (res === null || res === void 0 || (_res$data2 = res.data) === null || _res$data2 === void 0 ? void 0 : _res$data2.length) || 0;
        if (dataLength === 1) {
          var _res$data3;
          setValue('');
          setSearchResult(null);
          onSelectResult(res === null || res === void 0 ? void 0 : res.type, res === null || res === void 0 || (_res$data3 = res.data) === null || _res$data3 === void 0 ? void 0 : _res$data3[0]);
          return;
        }
        if (dataLength === 0 && (res === null || res === void 0 ? void 0 : res.type) === 'customer') {
          PisellToast({
            content: locales.getText('pisell2.text.ecocup.toast.fail-no-match-customer')
          });
          setSearchResult(null);
          return;
        }
        setSearchResult(res === null || res === void 0 ? void 0 : res.data);
      } else {
        if (res !== null && res !== void 0 && res.message) {
          PisellToast({
            content: res === null || res === void 0 ? void 0 : res.message
          });
        }
        setSearchResult(null);
      }
    });
  });
  useEffect(function () {
    addListener(scanListenerKey, function (result) {
      setValue('');
      setSearchResult(null);
      scanSearchCallback((result === null || result === void 0 ? void 0 : result.value) || '');
    });
    return function () {
      removeListener(scanListenerKey);
    };
  }, [scanListenerKey, scanSearchCallback]);
  useEffect(function () {
    /**
     * 点击非搜索区域时隐藏结果面板
     */
    var handleClickOutside = function handleClickOutside(event) {
      var target = event.target;
      if (!containerRef.current || !target) {
        return;
      }
      if (!containerRef.current.contains(target) && (searchResult === null || searchResult === void 0 ? void 0 : searchResult.length) > 1) {
        setSearchResult(null);
      }
    };
    document.addEventListener('mousedown', handleClickOutside);
    return function () {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, [searchResult]);
  return /*#__PURE__*/React.createElement("div", {
    ref: containerRef,
    className: "ecocup-cup-search-bar"
  }, /*#__PURE__*/React.createElement("div", {
    style: {
      flex: 1
    },
    onClick: function onClick() {
      console.log('onClick>>>>>>>', scanListenerKey);
      setActiveListener(scanListenerKey);
    }
  }, /*#__PURE__*/React.createElement(SearchSection, {
    value: value,
    onChange: setValue,
    loading: searchHook.loading,
    style: {
      flex: 1,
      height: size === 'large' ? '60px' : '48px',
      padding: 0
    },
    placeholder: placeholder || locales.getText('pisell2.text.cup-project.search-bar.placeholder'),
    searchButtonProps: {
      placement: 'inside',
      style: size === 'large' ? {
        height: 48,
        padding: 8,
        minWidth: 160
      } : {
        height: 32,
        padding: 8,
        minWidth: 120
      }
    },
    cameraButtonProps: {
      icon: ['pisell2-camera-01', 'pisell2-qr-code-02']
    },
    onSearch: function onSearch() {
      return scanSearchCallback(value);
    }
  })), (searchResult === null || searchResult === void 0 ? void 0 : searchResult.length) > 1 ? /*#__PURE__*/React.createElement("div", {
    className: "ecocup-cup-search-bar-result"
  }, /*#__PURE__*/React.createElement("div", {
    className: "ecocup-cup-search-bar-result-header"
  }, SEARCH_BAR_RESULT_HEADER_CONFIG === null || SEARCH_BAR_RESULT_HEADER_CONFIG === void 0 ? void 0 : SEARCH_BAR_RESULT_HEADER_CONFIG.map(function (item) {
    return /*#__PURE__*/React.createElement("div", {
      key: item.key
    }, locales.getText(item.label));
  })), /*#__PURE__*/React.createElement("div", {
    className: "ecocup-cup-search-bar-result-content"
  }, searchResult === null || searchResult === void 0 ? void 0 : searchResult.map(function (item) {
    var _tags$find, _tags$find2;
    var nickname = item.nickname,
      display_name = item.display_name,
      create_time = item.create_time,
      country_calling_code = item.country_calling_code,
      phone = item.phone,
      email = item.email,
      tags = item.tags;
    return /*#__PURE__*/React.createElement("div", {
      key: item.id,
      className: "ecocup-cup-search-bar-result-content-item",
      onClick: function onClick() {
        return onSelectResult('customer', item);
      }
    }, /*#__PURE__*/React.createElement("div", null, display_name || nickname || '-'), /*#__PURE__*/React.createElement("div", null, create_time ? dayjs(create_time).format('DD/MM/YYYY') : '-'), /*#__PURE__*/React.createElement("div", null, phone ? "(".concat(country_calling_code, ") ").concat(phone) : '-'), /*#__PURE__*/React.createElement("div", null, email || '-'), /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement("span", {
      className: "ecocup-cup-search-bar-result-content-item-membership"
    }, tags !== null && tags !== void 0 && (_tags$find = tags.find) !== null && _tags$find !== void 0 && _tags$find.call(tags, function (v) {
      return (v === null || v === void 0 ? void 0 : v.name) == 'admin';
    }) ? 'Admin' : tags !== null && tags !== void 0 && (_tags$find2 = tags.find) !== null && _tags$find2 !== void 0 && _tags$find2.call(tags, function (v) {
      return (v === null || v === void 0 ? void 0 : v.name) == 'business';
    }) ? 'Business' : 'Regular')));
  }))) : null, cupStatusModal.visible && /*#__PURE__*/React.createElement(CupStatusModal, cupStatusModal.modalProps));
};
export default SearchBar;