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); }
var _excluded = ["containerProps", "children"],
  _excluded2 = ["renderType", "open"],
  _excluded3 = ["originalValue", "value", "onChange", "keyboardProps"];
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 _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
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, useMemo, useState, useId, useCallback } from 'react';
import { Popover, Segmented, InputNumber } from 'antd';
import Decimal from 'decimal.js';
//@ts-ignore
import { locales } from '@pisell/utils';
import { PisellText, Keyboard, VirtualInput, PisellModal } from '@pisell/materials';
import { useControllableValue } from 'ahooks';
import useRightItems from "../../hooks/rightItems";
import useKeyActions from "../../hooks/keyActions";
import { setKeyboardTheme } from "../../utils";
import useEngineContext from "../../../../hooks/useEngineContext";
import localeTexts from "./locales";
import "./index.less";
var TIP_COLORS = {
  positive: '#CA8504',
  negative: '#1570EF',
  overflow: '#D92D20'
};

/**
 * originalValue: 当前订单原始值
 * defaultValue: 折扣后金额
 * onEnter: 折扣金额回调
 */
var DiscountKeyboardBase = function DiscountKeyboardBase(props) {
  var _context$appHelper$ut, _context$appHelper$ut2, _context$appHelper$ut3, _context$appHelper$ut4;
  var defaultValue = props.defaultValue,
    originalValue = props.originalValue,
    _props$selectType = props.selectType,
    selectType = _props$selectType === void 0 ? 'light' : _props$selectType,
    tips = props.tips,
    resetText = props.resetText,
    doneText = props.doneText,
    onEnter = props.onEnter,
    onReset = props.onReset,
    _props$enableExceedMa = props.enableExceedMaxAmount,
    enableExceedMaxAmount = _props$enableExceedMa === void 0 ? false : _props$enableExceedMa;
  var context = useEngineContext();
  var _useState = useState(true),
    _useState2 = _slicedToArray(_useState, 2),
    isFirstInput = _useState2[0],
    setIsFirstInput = _useState2[1];
  locales.init(localeTexts, ((_context$appHelper$ut = context.appHelper.utils) === null || _context$appHelper$ut === void 0 || (_context$appHelper$ut2 = _context$appHelper$ut.getApp) === null || _context$appHelper$ut2 === void 0 || (_context$appHelper$ut2 = _context$appHelper$ut2.call(_context$appHelper$ut)) === null || _context$appHelper$ut2 === void 0 || (_context$appHelper$ut2 = _context$appHelper$ut2.locales) === null || _context$appHelper$ut2 === void 0 || (_context$appHelper$ut3 = _context$appHelper$ut2.getLocale) === null || _context$appHelper$ut3 === void 0 ? void 0 : _context$appHelper$ut3.call(_context$appHelper$ut2)) || ((_context$appHelper$ut4 = context.appHelper.utils) === null || _context$appHelper$ut4 === void 0 || (_context$appHelper$ut4 = _context$appHelper$ut4.storage) === null || _context$appHelper$ut4 === void 0 ? void 0 : _context$appHelper$ut4.get('umi_locale')) || 'en');
  var getData = context.appHelper.utils.getData;
  var amountSymbol = props.amountSymbol || (getData === null || getData === void 0 ? void 0 : getData('shop_symbol')) || '$';
  var uniqueId = useId();
  var uniqueKeyboardId = "virtual-keyboard-".concat(uniqueId.replace(/:/g, '-'));
  // 一口价或者折扣
  var _useState3 = useState('priceOverride'),
    _useState4 = _slicedToArray(_useState3, 2),
    updateMode = _useState4[0],
    setUpdateMode = _useState4[1];
  // 折扣模式分为 金额 和 百分比
  var _useState5 = useState('amount'),
    _useState6 = _slicedToArray(_useState5, 2),
    discountMode = _useState6[0],
    setDiscountMode = _useState6[1];
  var _useState7 = useState(defaultValue ? String(defaultValue) : ''),
    _useState8 = _slicedToArray(_useState7, 2),
    internalValue = _useState8[0],
    setInternalValue = _useState8[1];
  var _useState9 = useState(''),
    _useState10 = _slicedToArray(_useState9, 2),
    discountValue = _useState10[0],
    setDiscountValue = _useState10[1];
  useEffect(function () {
    document.body.id = 'body';
  }, []);

  // 设置主题
  useEffect(function () {
    setKeyboardTheme(selectType);
  }, [selectType]);
  var _onReset = useCallback(function () {
    if (updateMode === 'priceOverride') {
      // 重置为最初价格
      setInternalValue(originalValue ? String(originalValue) : '');
      setIsFirstInput(true);
    } else {
      setDiscountValue('');
    }
    onReset === null || onReset === void 0 || onReset();
  }, [originalValue, onReset, updateMode]);
  var _handleChange = useCallback(function (val) {
    if (updateMode === 'priceOverride') {
      setIsFirstInput(false);
      setInternalValue(val);
    } else {
      setDiscountValue(val);
    }
  }, [updateMode]);

  // 计算折扣金额和符号
  var discountAmount = useMemo(function () {
    var originalPrice = new Decimal(originalValue || 0);
    var discountAmount = new Decimal(0);
    if (updateMode === 'priceOverride') {
      discountAmount = originalPrice.minus(new Decimal(internalValue || 0));
    } else {
      // discount 模式
      if (discountMode === 'amount') {
        discountAmount = new Decimal(discountValue || 0);
      } else {
        // percentage 模式
        var percentage = new Decimal(discountValue || 0);
        discountAmount = originalPrice.times(percentage.dividedBy(100));
      }
    }
    return discountAmount.toNumber();
  }, [updateMode, discountMode, internalValue, discountValue, originalValue]);
  var isDiscountOverflow = useMemo(function () {
    var _original = new Decimal(originalValue || 0);
    if (updateMode === 'priceOverride') {
      return new Decimal(internalValue || 0).greaterThan(_original);
    }
    if (discountMode === 'amount') {
      return new Decimal(discountValue || 0).greaterThan(_original);
    }
    return false;
  }, [updateMode, discountMode, internalValue, discountValue, originalValue]);
  var payableAmount = useMemo(function () {
    return new Decimal(originalValue || 0).minus(discountAmount).toNumber();
  }, [originalValue, discountAmount]);
  var handleEnter = function handleEnter() {
    // 改价模式下，且允许超出原价，那么直接返回
    if (updateMode === 'priceOverride' && enableExceedMaxAmount) {
      onEnter === null || onEnter === void 0 || onEnter(String(discountAmount));
      return;
    }
    // 折扣模式、或一口价有限额，则进行折扣值的校验
    if (isDiscountOverflow) {
      return;
    }
    onEnter === null || onEnter === void 0 || onEnter(String(discountAmount));
  };
  var _max = useMemo(function () {
    return updateMode === 'discount' && discountMode === 'percentage' ? 100 : undefined;
  }, [updateMode, discountMode]);
  var _useKeyActions = useKeyActions({
      onEnter: handleEnter,
      onReset: _onReset,
      onChange: _handleChange,
      value: updateMode === 'priceOverride' ? internalValue : discountValue,
      max: _max,
      mode: isFirstInput && updateMode === 'priceOverride' ? 'replace' : 'append',
      scale: 2
    }),
    handleChange = _useKeyActions.handleChange;
  var rightItems = useRightItems({
    rightItemsStyle: {
      doneButtonStyle: {
        boxShadow: '0px 0px 1px #898A8D',
        cursor: updateMode !== 'priceOverride' && isDiscountOverflow ? 'not-allowed' : undefined,
        backgroundColor: updateMode !== 'priceOverride' && isDiscountOverflow ? '#D0D5DD' : undefined
      }
    },
    doneText: doneText || locales.getText('discount-keyboard-done'),
    resetText: resetText || locales.getText('discount-keyboard-reset')
  });
  var formattedVal = useMemo(function () {
    if (updateMode === 'priceOverride') {
      return internalValue ? "".concat(amountSymbol).concat(internalValue) : '';
    }
    if (discountMode === 'amount') {
      return discountValue ? "".concat(amountSymbol).concat(discountValue) : '';
    } else {
      return discountValue ? "".concat(discountValue, "%") : '';
    }
  }, [updateMode, discountMode, internalValue, discountValue, amountSymbol]);
  var placeholder = useMemo(function () {
    if (updateMode === 'priceOverride') {
      return "".concat(amountSymbol, "0");
    } else {
      if (discountMode === 'amount') {
        return '0';
      }
      return '%';
    }
  }, [amountSymbol, updateMode, discountMode]);
  var renderBottomContent = function renderBottomContent() {
    // 没改价，则为空
    if (new Decimal(discountAmount).equals(0)) {
      return /*#__PURE__*/React.createElement("div", null, "\xA0");
    }
    if (updateMode === 'priceOverride' || discountMode === 'percentage') {
      var color;
      var sign = '';
      // 折扣为正值, 展示为负
      if (new Decimal(discountAmount).greaterThan(0)) {
        color = TIP_COLORS.negative;
        sign = '-';
      } else {
        sign = '+';
        color = TIP_COLORS.positive;
      }
      var style = {
        color: color
      };
      return /*#__PURE__*/React.createElement("div", {
        style: style,
        className: "ellipsis"
      }, /*#__PURE__*/React.createElement("span", null, sign, /*#__PURE__*/React.createElement(PisellText.Amount, {
        hideDecimalForWholeNumbers: false,
        precision: 2,
        value: Math.abs(discountAmount)
      })));
    }
    return /*#__PURE__*/React.createElement("div", {
      style: {
        color: isDiscountOverflow ? TIP_COLORS.overflow : ''
      },
      className: "ellipsis"
    }, locales.getText('discount-keyboard-max-discount'), ":", ' ', /*#__PURE__*/React.createElement(PisellText.Amount, {
      hideDecimalForWholeNumbers: false,
      precision: 2,
      value: originalValue
    }));
  };
  var customDisplay = function customDisplay() {
    var _color = updateMode === 'discount' && discountMode === 'amount' && isDiscountOverflow ? TIP_COLORS.overflow : undefined;
    return /*#__PURE__*/React.createElement("div", {
      style: {
        display: 'flex',
        gap: 8
      }
    }, /*#__PURE__*/React.createElement(VirtualInput, {
      focused: true,
      value: formattedVal,
      wrapperStyle: {
        padding: '12px 20px',
        borderRadius: '8px',
        backgroundColor: 'white',
        boxShadow: '0px 1px 2px rgba(16, 24, 40, 0.06)',
        flex: '2',
        overflow: 'hidden'
      },
      style: {
        color: _color
      },
      placeholder: placeholder,
      bottomContent: renderBottomContent()
    }), /*#__PURE__*/React.createElement("div", {
      style: {
        flex: '1',
        display: 'flex',
        flexDirection: 'column',
        borderRadius: '8px',
        backgroundColor: '#ffffff',
        padding: 8,
        boxShadow: '0px 1px 2px rgba(16, 24, 40, 0.06)',
        overflow: 'hidden'
      }
    }, /*#__PURE__*/React.createElement("div", {
      style: {
        flex: 1
      }
    }, /*#__PURE__*/React.createElement("div", {
      style: {
        color: '#667085',
        fontSize: 12,
        fontWeight: 500,
        wordWrap: 'break-word'
      }
    }, locales.getText('discount-keyboard-total')), /*#__PURE__*/React.createElement("div", {
      style: {
        color: '#475467',
        fontSize: 14,
        fontWeight: 700,
        wordWrap: 'break-word'
      }
    }, /*#__PURE__*/React.createElement(PisellText.Amount, {
      value: originalValue
    }))), /*#__PURE__*/React.createElement("div", {
      style: {
        flex: 1
      }
    }, /*#__PURE__*/React.createElement("div", {
      style: {
        color: '#667085',
        fontSize: 12,
        fontWeight: 500,
        wordWrap: 'break-word'
      }
    }, locales.getText('discount-keyboard-payable')), /*#__PURE__*/React.createElement("div", {
      style: {
        color: '#475467',
        fontSize: 14,
        fontWeight: 700,
        wordWrap: 'break-word'
      }
    }, /*#__PURE__*/React.createElement(PisellText.Amount, {
      value: payableAmount
    })))));
  };
  var renderTipsContent = function renderTipsContent() {
    if (tips) {
      return /*#__PURE__*/React.createElement("div", {
        className: "pisell-pro-price-keyboard-tips"
      }, tips);
    }
    return null;
  };
  return /*#__PURE__*/React.createElement("div", {
    className: "pisell-pro-price-keyboard-discount"
  }, renderTipsContent(), /*#__PURE__*/React.createElement(Segmented, {
    size: "large",
    style: {
      padding: 6
    },
    options: [{
      label: locales.getText('discount-keyboard-price-override'),
      value: 'priceOverride'
    }, {
      label: locales.getText('discount-keyboard-discount'),
      value: 'discount'
    }],
    value: updateMode,
    onChange: function onChange(val) {
      return setUpdateMode(val);
    },
    block: true
  }), updateMode === 'discount' && /*#__PURE__*/React.createElement(Segmented, {
    size: "large",
    style: {
      padding: 6
    },
    options: [{
      label: locales.getText('discount-keyboard-amount') + " (".concat(amountSymbol, ")"),
      value: 'amount'
    }, {
      label: locales.getText('discount-keyboard-percentage') + ' (%)',
      value: 'percentage'
    }],
    value: discountMode,
    onChange: function onChange(val) {
      setDiscountMode(val);
      setDiscountValue('');
    },
    block: true
  }), /*#__PURE__*/React.createElement("div", {
    className: "pisell-pro-price-keyboard-content"
  }, customDisplay(), /*#__PURE__*/React.createElement(Keyboard, {
    rightItems: rightItems,
    onChange: handleChange,
    id: uniqueKeyboardId
  })));
};
var DiscountKeyboard = function DiscountKeyboard(props) {
  var containerProps = props.containerProps,
    children = props.children,
    keyboardProps = _objectWithoutProperties(props, _excluded);
  if (!containerProps) {
    return /*#__PURE__*/React.createElement(DiscountKeyboardBase, keyboardProps);
  }
  var _ref = containerProps || {},
    renderType = _ref.renderType,
    open = _ref.open,
    restProps = _objectWithoutProperties(_ref, _excluded2);

  // 暂时只支持受控模式
  if (renderType === 'popover') {
    return /*#__PURE__*/React.createElement(Popover, _extends({
      key: "".concat(open),
      open: open,
      trigger: "click",
      className: "pisell-discount-keyboard-popover"
    }, restProps, {
      content: /*#__PURE__*/React.createElement(DiscountKeyboardBase, keyboardProps)
    }), children);
  }

  // 暂时只支持受控模式
  if (renderType === 'modal') {
    return open ? /*#__PURE__*/React.createElement(PisellModal, _extends({
      platform: 'pc',
      open: true,
      width: "unset",
      header: null,
      footer: false,
      mask: false,
      maskClosable: true,
      bodyStyle: {
        padding: '0px',
        backgroundColor: 'transparent'
      },
      closeIcon: null,
      className: "pisell-discount-keyboard-modal",
      destroyOnHidden: true
    }, restProps), /*#__PURE__*/React.createElement(DiscountKeyboardBase, keyboardProps)) : null;
  }
  return /*#__PURE__*/React.createElement(DiscountKeyboardBase, keyboardProps);
};
// 基于 DiscountKeyboard 的输入框组件
var DiscountKeyboardInputNumber = function DiscountKeyboardInputNumber(props) {
  var _keyboardProps$contai;
  var originalValue = props.originalValue,
    value = props.value,
    onChange = props.onChange,
    keyboardProps = props.keyboardProps,
    rest = _objectWithoutProperties(props, _excluded3);
  var _useControllableValue = useControllableValue(props),
    _useControllableValue2 = _slicedToArray(_useControllableValue, 2),
    internalValue = _useControllableValue2[0],
    setInternalValue = _useControllableValue2[1];
  var _useState11 = useState(false),
    _useState12 = _slicedToArray(_useState11, 2),
    isOpen = _useState12[0],
    setIsOpen = _useState12[1];
  var renderType = (keyboardProps === null || keyboardProps === void 0 || (_keyboardProps$contai = keyboardProps.containerProps) === null || _keyboardProps$contai === void 0 ? void 0 : _keyboardProps$contai.renderType) || 'popover';
  if (renderType === 'modal') {
    return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(InputNumber, _extends({
      value: value,
      readOnly: true
    }, rest, {
      onClick: function onClick() {
        return setIsOpen(true);
      }
    })), /*#__PURE__*/React.createElement(DiscountKeyboard, _extends({}, keyboardProps || {}, {
      containerProps: _objectSpread(_objectSpread({}, keyboardProps === null || keyboardProps === void 0 ? void 0 : keyboardProps.containerProps), {}, {
        open: isOpen,
        onCancel: function onCancel() {
          return setIsOpen(false);
        },
        renderType: 'modal'
      }),
      enableExceedMaxAmount: true,
      defaultValue: internalValue,
      onEnter: function onEnter(val) {
        setInternalValue(new Decimal(originalValue).minus(Number(val)).toNumber());
        setIsOpen(false);
      },
      originalValue: originalValue
    })));
  }
  return /*#__PURE__*/React.createElement(DiscountKeyboard, _extends({}, keyboardProps || {}, {
    containerProps: _objectSpread(_objectSpread({}, keyboardProps === null || keyboardProps === void 0 ? void 0 : keyboardProps.containerProps), {}, {
      open: isOpen,
      onOpenChange: function onOpenChange(val) {
        return setIsOpen(val);
      },
      renderType: 'popover'
    }),
    enableExceedMaxAmount: true,
    defaultValue: internalValue,
    onEnter: function onEnter(val) {
      setInternalValue(new Decimal(originalValue).minus(Number(val)).toNumber());
      setIsOpen(false);
    },
    originalValue: originalValue
  }), /*#__PURE__*/React.createElement(InputNumber, _extends({
    value: value,
    readOnly: true
  }, rest)));
};
DiscountKeyboard.InputNumber = DiscountKeyboardInputNumber;
export default DiscountKeyboard;