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); }
import React, { useMemo } from 'react';
import { Typography } from '@pisell/materials';
import { locales } from '@pisell/utils';
import "./index.less";
var Text = Typography.Text;
function UsageRules(_ref) {
  var _ref$className = _ref.className,
    className = _ref$className === void 0 ? '' : _ref$className,
    style = _ref.style,
    dataSource = _ref.dataSource;
  var _ref2 = dataSource || {},
    _ref2$extension_data = _ref2.extension_data,
    extension_data = _ref2$extension_data === void 0 ? [] : _ref2$extension_data,
    _ref2$customer_order_ = _ref2.customer_order_behavior_count,
    customer_order_behavior_count = _ref2$customer_order_ === void 0 ? 0 : _ref2$customer_order_,
    _ref2$total_order_beh = _ref2.total_order_behavior_count,
    total_order_behavior_count = _ref2$total_order_beh === void 0 ? 0 : _ref2$total_order_beh;
  var creditsData = useMemo(function () {
    var usageCreditsItem = extension_data.find(function (item) {
      return item.field_key === 'usage_credits';
    });
    return usageCreditsItem === null || usageCreditsItem === void 0 ? void 0 : usageCreditsItem.value;
  }, [extension_data]);
  var rules = useMemo(function () {
    if (!creditsData) return [];
    var rules = [];

    // Add daily limit if exists
    if (creditsData.max_per_day > 0) {
      rules.push({
        type: 'daily',
        limit: creditsData.max_per_day,
        description: '',
        // Will be filled by localized text
        resetTime: '' // Will be filled by localized text
      });
    }

    // Add weekly limit if exists
    if (creditsData.max_per_week > 0) {
      rules.push({
        type: 'weekly',
        limit: creditsData.max_per_week,
        description: '',
        // Will be filled by localized text
        resetTime: '' // Will be filled by localized text
      });
    }

    // Add monthly limit if exists
    if (creditsData.max_per_month > 0) {
      rules.push({
        type: 'monthly',
        limit: creditsData.max_per_month,
        description: '',
        // Will be filled by localized text
        resetTime: '' // Will be filled by localized text
      });
    }
    return rules;
  }, [creditsData]);

  // Generate personal limit data
  var personalLimit = useMemo(function () {
    if (!creditsData) return undefined;
    var totalCredits = creditsData.total_credits || 0;
    var perUserLimit = creditsData.per_user_limit || 0;

    // 使用 total_credits 和 per_user_limit 中的较小值且非 0 的值作为总数
    // 如果 totalCredits 是 0，则使用 perUserLimit
    var total = 0;
    if (totalCredits > 0 && perUserLimit > 0) {
      total = Math.min(totalCredits, perUserLimit);
    } else {
      total = Math.max(totalCredits, perUserLimit);
    }

    // 单张卡剩余多少
    var total_remaining = 0;
    if (totalCredits > 0) {
      total_remaining = totalCredits - (total_order_behavior_count || 0);
    }
    // 个人剩余多少
    var perUser_remaining = 0;
    if (perUserLimit > 0) {
      perUser_remaining = perUserLimit - (customer_order_behavior_count || 0);
    }
    var remaining = 0;
    if (total_remaining > 0 && perUser_remaining > 0) {
      remaining = Math.min(total_remaining, perUser_remaining);
    } else {
      // 如果有一个是 0，还需要看是否是因为配置是 0 才导致的 0
      // 先看总次数是不是剩余 0，是因为什么剩余 0
      if (total_remaining === 0) {
        if (totalCredits === 0) {
          // 代表不限制总使用次数
          remaining = perUser_remaining;
        } else {
          // 代表限制总使用次数，但是总使用次数为 0，则 remaining 为 0
          remaining = 0;
        }
      } else {
        // 如果剩余总使用次数大于 0，个人使用次数为 0，则 remaining 为 0
        if (perUser_remaining === 0) {
          remaining = 0;
        }
      }
    }
    return {
      total: total,
      remaining: remaining,
      note: '' // Will be filled by localized text
    };
  }, [creditsData, total_order_behavior_count, customer_order_behavior_count]);

  // Helper function to interpolate text with variables
  var interpolateText = function interpolateText(text, variables) {
    var ret = text.replace(/\{(\w+)\}/g, function (match, key) {
      return variables[key] !== undefined ? variables[key] : match;
    });
    return ret;
  };

  // Get localized text with fallback
  var getText = function getText(key, fallback) {
    return (locales === null || locales === void 0 ? void 0 : locales.getText(key)) || fallback || key;
  };

  // Generate rule description with limit value
  var getRuleDescription = function getRuleDescription(type, limit) {
    // Handle unlimited case (limit = 0 means unlimited)
    if (limit === 0 && type === 'monthly') {
      return getText('wallet-pass-gallery.monthlyLimitUnlimited', '无限制');
    }
    var templateKey = "wallet-pass-gallery.".concat(type, "LimitDesc");
    var template = getText(templateKey, '');
    return interpolateText(template, {
      limit: limit
    });
  };

  // Generate rule reset time text
  var getRuleResetTime = function getRuleResetTime(type) {
    var resetKey = "wallet-pass-gallery.".concat(type, "Reset");
    return getText(resetKey, '');
  };

  // Default rules with localized text
  var defaultRules = [{
    type: 'daily',
    limit: 3,
    description: getRuleDescription('daily', 3),
    resetTime: getRuleResetTime('daily')
  }, {
    type: 'weekly',
    limit: 15,
    description: getRuleDescription('weekly', 15),
    resetTime: getRuleResetTime('weekly')
  }, {
    type: 'monthly',
    limit: 60,
    description: getRuleDescription('monthly', 60),
    resetTime: getRuleResetTime('monthly')
  }];

  // Process rules to add localized descriptions
  var processedRules = rules ? rules.map(function (rule) {
    return _objectSpread(_objectSpread({}, rule), {}, {
      description: getRuleDescription(rule.type, rule.limit),
      resetTime: getRuleResetTime(rule.type)
    });
  }) : defaultRules;
  var finalRules = processedRules;
  var getRuleLabel = function getRuleLabel(type) {
    switch (type) {
      case 'daily':
        return getText('wallet-pass-gallery.dailyLimit', '每日限制:');
      case 'weekly':
        return getText('wallet-pass-gallery.weeklyLimit', '每周限制:');
      case 'monthly':
        return getText('wallet-pass-gallery.monthlyLimit', '每月限制:');
      default:
        return getText('wallet-pass-gallery.dailyLimit', '限制:');
    }
  };
  if (!creditsData) return null;
  return /*#__PURE__*/React.createElement("div", {
    className: "pisell-wallet-pass-gallery_usage-rules ".concat(className),
    style: style
  }, /*#__PURE__*/React.createElement(Text, {
    className: "pisell-wallet-pass-gallery_usage-rules-title"
  }, getText('wallet-pass-gallery.usageRules', '使用规则')), /*#__PURE__*/React.createElement(Text, {
    className: "pisell-wallet-pass-gallery_usage-rules-subtitle"
  }, getText('wallet-pass-gallery.usageRulesSubtitle', '请仔细阅读以下使用条件')), /*#__PURE__*/React.createElement("div", {
    className: "pisell-wallet-pass-gallery_usage-rules-section"
  }, /*#__PURE__*/React.createElement(Text, {
    className: "pisell-wallet-pass-gallery_usage-rules-section-title"
  }, getText('wallet-pass-gallery.timeUsageLimits', '时间使用限制')), /*#__PURE__*/React.createElement("div", {
    className: "pisell-wallet-pass-gallery_usage-rules-list"
  }, finalRules.length > 0 ? finalRules.map(function (rule, index) {
    return /*#__PURE__*/React.createElement("div", {
      key: index,
      className: "pisell-wallet-pass-gallery_usage-rules-item"
    }, /*#__PURE__*/React.createElement("div", {
      className: "pisell-wallet-pass-gallery_usage-rules-item-content"
    }, /*#__PURE__*/React.createElement("div", {
      className: "pisell-wallet-pass-gallery_usage-rules-item-main-line"
    }, /*#__PURE__*/React.createElement(Text, {
      className: "pisell-wallet-pass-gallery_usage-rules-item-label"
    }, getRuleLabel(rule.type)), /*#__PURE__*/React.createElement(Text, {
      className: "pisell-wallet-pass-gallery_usage-rules-item-description"
    }, rule.description)), rule.resetTime && /*#__PURE__*/React.createElement(Text, {
      className: "pisell-wallet-pass-gallery_usage-rules-item-reset"
    }, rule.resetTime)));
  }) : /*#__PURE__*/React.createElement("div", {
    className: "pisell-wallet-pass-gallery_usage-rules-item"
  }, /*#__PURE__*/React.createElement("div", {
    className: "pisell-wallet-pass-gallery_usage-rules-item-content"
  }, /*#__PURE__*/React.createElement(Text, {
    className: "pisell-wallet-pass-gallery_usage-rules-item-description"
  }, getText('wallet-pass-gallery.monthlyLimitUnlimited', '无限制')))))), /*#__PURE__*/React.createElement("div", {
    className: "pisell-wallet-pass-gallery_usage-rules-section"
  }, /*#__PURE__*/React.createElement(Text, {
    className: "pisell-wallet-pass-gallery_usage-rules-section-title"
  }, getText('wallet-pass-gallery.totalQuantityControl', '总量控制')), /*#__PURE__*/React.createElement("div", {
    className: "pisell-wallet-pass-gallery_usage-rules-item"
  }, /*#__PURE__*/React.createElement("div", {
    className: "pisell-wallet-pass-gallery_usage-rules-item-content"
  }, personalLimit && personalLimit.total > 0 ? /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(Text, {
    className: "pisell-wallet-pass-gallery_usage-rules-item-label"
  }, getText('wallet-pass-gallery.personalLimit', '个人限额:')), /*#__PURE__*/React.createElement(Text, {
    className: "pisell-wallet-pass-gallery_usage-rules-item-description"
  }, interpolateText(getText('wallet-pass-gallery.personalLimitDesc', '您最多可使用此券{total}次(剩余{remaining}次)'), {
    total: personalLimit.total,
    remaining: personalLimit.remaining
  })), /*#__PURE__*/React.createElement(Text, {
    className: "pisell-wallet-pass-gallery_usage-rules-item-note"
  }, getText('wallet-pass-gallery.voucherExpireNote', '用完后此券将自动失效'))) : /*#__PURE__*/React.createElement(Text, {
    className: "pisell-wallet-pass-gallery_usage-rules-item-description"
  }, getText('wallet-pass-gallery.monthlyLimitUnlimited', '无限制'))))));
}
export default UsageRules;