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, { useState, useEffect, useCallback, useRef, useMemo } from 'react';
import { useDebounceFn, useMemoizedFn } from 'ahooks';
import dayjs from 'dayjs';
import { Table, DatePicker, Page, Button, Icon } from '@pisell/materials';
import { locales } from '@pisell/utils';
import { CalendarOutlined } from '@ant-design/icons';
import { useColumns, useSummary, useCupListsApi, useStatisticsApi, useEcoShopListsApi, useExportApi, useShareApi } from "./hooks";
import { SORT_SETTINGS, COLUMN_SETTING, FILTER, HEADER_RIGHT_OPTIONS } from "./const";
import PageHeader from "../components/PageHeader";
import CupActionModal from "../components/CupActionModal";
import SearchBar from "../components/SearchBar";
import { useLanguage, useModal, useGetGoalShopInfo, useIsApp, useGetShopId } from "../hooks";
import localeTexts from "../locales";
import { useGetShare } from "../hooks";
import "./index.less";
var prefixCls = 'ecocup-cup-list';
var SCAN_LISTENER_KEY = 'eco-cup-list-scan-listener';
var PAGE_SIZE = 10;
var FORMAT = 'YYYY-MM-DD HH:mm:ss';
var CupList = function CupList(props) {
  var _useState = useState([dayjs().startOf('day'), dayjs().endOf('day')]),
    _useState2 = _slicedToArray(_useState, 2),
    date = _useState2[0],
    setDate = _useState2[1];
  var cupActionModal = useModal('ecocup-list-action-modal');
  var _useGetGoalShopInfo = useGetGoalShopInfo(),
    isNormalShop = _useGetGoalShopInfo.isNormalShop;
  var shopId = useGetShopId();
  var isApp = useIsApp();
  var language = useLanguage();
  var _useGetShare = useGetShare(),
    isEcoShare = _useGetShare.isEcoShare;
  locales.init(localeTexts, language);
  var _useState3 = useState({
      skip: 1,
      num: PAGE_SIZE
    }),
    _useState4 = _slicedToArray(_useState3, 2),
    listParams = _useState4[0],
    setListParams = _useState4[1];
  // 使用 ref 保存最新的 listParams，用于在回调中获取最新值
  var listParamsRef = useRef(listParams);
  var _useCupListsApi = useCupListsApi({
      isEcoShare: isEcoShare
    }),
    loading = _useCupListsApi.loading,
    data = _useCupListsApi.data,
    run = _useCupListsApi.run;
  var _useStatisticsApi = useStatisticsApi({
      isEcoShare: isEcoShare
    }),
    staticsData = _useStatisticsApi.data,
    getStatics = _useStatisticsApi.getStatics;
  var _useEcoShopListsApi = useEcoShopListsApi({
      isEcoShare: isEcoShare
    }),
    ecoShopLists = _useEcoShopListsApi.data,
    getEcoShopLists = _useEcoShopListsApi.getEcoShopLists;
  var _useExportApi = useExportApi(),
    postExportApi = _useExportApi.postExportApi;
  var _useShareApi = useShareApi(),
    postShareApi = _useShareApi.postShareApi;
  var isPartner = useMemo(function () {
    return !!(isNormalShop || listParams !== null && listParams !== void 0 && listParams.partner_shop_id);
  }, [isNormalShop, listParams === null || listParams === void 0 ? void 0 : listParams.partner_shop_id]);
  useEffect(function () {
    listParamsRef.current = listParams;
  }, [listParams]);
  var getLists = useCallback(function (params) {
    run(_objectSpread(_objectSpread({}, (listParamsRef === null || listParamsRef === void 0 ? void 0 : listParamsRef.current) || {}), params));
  }, [listParams]);
  useEffect(function () {
    var _date$, _date$2;
    if (isApp) return;
    getStatics({
      started_at: date === null || date === void 0 || (_date$ = date[0]) === null || _date$ === void 0 ? void 0 : _date$.format(FORMAT),
      ended_at: date === null || date === void 0 || (_date$2 = date[1]) === null || _date$2 === void 0 ? void 0 : _date$2.format(FORMAT),
      partner_shop_id: listParams === null || listParams === void 0 ? void 0 : listParams.partner_shop_id
    });
  }, [date, isApp, listParams === null || listParams === void 0 ? void 0 : listParams.partner_shop_id]);
  useEffect(function () {
    if (isNormalShop || isApp) return;
    getEcoShopLists({});
  }, [isNormalShop, isApp]);
  useEffect(function () {
    getLists();
  }, [getLists]);
  var handleClickAction = useCallback(function (type, record) {
    cupActionModal.open({
      data: {
        type: type,
        cupData: record,
        customerData: (record === null || record === void 0 ? void 0 : record.customer) || {}
      },
      onCancel: cupActionModal.close,
      onOk: function onOk(values) {
        cupActionModal.close();
        getLists();
      }
    });
  }, [cupActionModal]);
  var columns = useColumns({
    onClickAction: handleClickAction,
    locales: locales,
    isEcoShare: isEcoShare
  });
  var summary = useSummary(locales, staticsData, isPartner);

  /**
   * @description: 值变化回调处理函数
   * @param {any} changedValues
   * @param {any} values
   * @return {*}
   */
  var handleValuesChange = function handleValuesChange(changedValues, values) {
    var _values$order_by, _values$pagination, _values$pagination2;
    // 分割排序字段
    var orderByTypes = values === null || values === void 0 || (_values$order_by = values.order_by) === null || _values$order_by === void 0 ? void 0 : _values$order_by.split(':');
    var params = _objectSpread(_objectSpread({}, (values === null || values === void 0 ? void 0 : values.filters) || {}), {}, {
      order_by: orderByTypes === null || orderByTypes === void 0 ? void 0 : orderByTypes[0],
      sort: orderByTypes === null || orderByTypes === void 0 ? void 0 : orderByTypes[1],
      skip: (values === null || values === void 0 || (_values$pagination = values.pagination) === null || _values$pagination === void 0 ? void 0 : _values$pagination.page) || 1,
      num: (values === null || values === void 0 || (_values$pagination2 = values.pagination) === null || _values$pagination2 === void 0 ? void 0 : _values$pagination2.size) || PAGE_SIZE,
      partner_shop_id: (values === null || values === void 0 ? void 0 : values.partner_shop_id) || undefined,
      status: (values === null || values === void 0 ? void 0 : values.status) || undefined
    });
    setListParams(function (prev) {
      return _objectSpread(_objectSpread({}, prev), params);
    });
  };

  /**
   * @description: 值变化回调防抖处理函数
   * @return {*}
   */
  var _useDebounceFn = useDebounceFn(handleValuesChange, {
      wait: 200
    }),
    handleValuesChangeDebounce = _useDebounceFn.run;
  var handleChange = function handleChange(value, type) {
    // 搜索code
    if (type === 'search') {
      setListParams(function (prev) {
        return _objectSpread(_objectSpread({}, prev), {}, {
          search: value,
          skip: 1
        });
      });
    } else {
      // 搜索日期
      setDate(value);
      setListParams(function (prev) {
        var _value$, _value$2;
        return _objectSpread(_objectSpread({}, prev), {}, {
          skip: 1,
          operated_at_start: value === null || value === void 0 || (_value$ = value[0]) === null || _value$ === void 0 ? void 0 : _value$.format(FORMAT),
          operated_at_end: value === null || value === void 0 || (_value$2 = value[1]) === null || _value$2 === void 0 ? void 0 : _value$2.format(FORMAT)
        });
      });
    }
  };
  var pagination = useMemo(function () {
    return {
      pageSize: PAGE_SIZE,
      total: (data === null || data === void 0 ? void 0 : data.count) || 0,
      size: 'large',
      current: (listParams === null || listParams === void 0 ? void 0 : listParams.skip) || 1,
      localPagination: false
    };
  }, [data === null || data === void 0 ? void 0 : data.count, listParams === null || listParams === void 0 ? void 0 : listParams.skip]);
  var onClickButton = useMemoizedFn(function (key) {
    if (key === 'export') {
      postExportApi({
        isPartner: isPartner,
        listParams: listParams
      });
    } else if (key === 'share') {
      postShareApi();
    }
  });
  var headerRightContent = useMemo(function () {
    // 只有总店有导出和分享功能
    if (isNormalShop || isEcoShare) {
      return null;
    }
    return /*#__PURE__*/React.createElement("div", {
      className: "".concat(prefixCls, "-header-right-content")
    }, HEADER_RIGHT_OPTIONS.map(function (button) {
      return /*#__PURE__*/React.createElement(Button, {
        key: button.key,
        type: button.type,
        size: "large",
        icon: /*#__PURE__*/React.createElement(Icon, {
          type: button.icon,
          size: 22
        }),
        onClick: function onClick() {
          return onClickButton(button.key);
        },
        className: "".concat(prefixCls, "-header-right-content-button")
      }, locales.getText(button.languageKey));
    }));
  }, [isNormalShop, onClickButton, isEcoShare]);
  return /*#__PURE__*/React.createElement("div", {
    className: "".concat(prefixCls, "-container")
  }, /*#__PURE__*/React.createElement(Page, {
    style: {
      height: '100%'
    }
  }, /*#__PURE__*/React.createElement(Table, {
    dataSource: (data === null || data === void 0 ? void 0 : data.list) || [],
    columns: columns,
    title: !isApp ? /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(PageHeader, {
      title: locales.getText('pisell2.text.ecocup.title'),
      rightContent: headerRightContent,
      isReturn: !isEcoShare
    }), /*#__PURE__*/React.createElement("div", {
      className: "".concat(prefixCls, "-header")
    }, /*#__PURE__*/React.createElement(DatePicker.RangePicker, {
      inputReadOnly: true,
      bordered: false,
      allowClear: false,
      size: "large",
      suffixIcon: /*#__PURE__*/React.createElement(CalendarOutlined, null),
      value: date,
      onChange: handleChange,
      format: "DD/MM/YYYY",
      className: "".concat(prefixCls, "-date-picker")
    }), /*#__PURE__*/React.createElement(SearchBar, {
      scanListenerKey: SCAN_LISTENER_KEY,
      size: "small",
      placeholder: locales.getText('pisell2.text.ecocup.scan-or-search'),
      onSearch: function onSearch(value) {
        return handleChange(value, 'search');
      }
    }))) : null,
    align: "center",
    pagination: pagination,
    columnSetting: !isApp ? COLUMN_SETTING : null,
    sort: !isApp ? SORT_SETTINGS : null,
    filter: !isApp ? FILTER(locales, isNormalShop, ecoShopLists, isPartner, listParams === null || listParams === void 0 ? void 0 : listParams.skip) : null,
    summary: !isApp ? summary : null,
    className: "".concat(prefixCls, "-table"),
    rowClassName: "".concat(prefixCls, "-table-row"),
    loading: loading,
    onValuesChange: handleValuesChangeDebounce,
    rowKey: "id",
    virtual: false,
    tableLayout: "",
    scroll: {
      scrollToFirstRowOnChange: true,
      autoCalc: true
    }
  })), cupActionModal.visible && /*#__PURE__*/React.createElement(CupActionModal, cupActionModal.modalProps));
};
export default CupList;