"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

var _typeof = require("@babel/runtime/helpers/typeof");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;

var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));

require("maycur-antd/lib/input/style/css");

var _input = _interopRequireDefault(require("maycur-antd/lib/input"));

require("maycur-antd/lib/icon/style/css");

var _icon = _interopRequireDefault(require("maycur-antd/lib/icon"));

require("maycur-antd/lib/modal/style/css");

var _modal = _interopRequireDefault(require("maycur-antd/lib/modal"));

var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));

var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));

var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));

var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits"));

var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));

var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));

var _react = _interopRequireWildcard(require("react"));

var _numeral = _interopRequireDefault(require("numeral"));

var _lodash = _interopRequireDefault(require("lodash"));

var _classnames = _interopRequireDefault(require("classnames"));

var _CurrencySelector = _interopRequireDefault(require("../../CurrencySelector"));

var _cookie = _interopRequireDefault(require("../../utils/cookie"));

var _utils = _interopRequireDefault(require("../../utils/utils"));

var _mkTranslate = _interopRequireDefault(require("../../utils/mkTranslate"));

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0, _getPrototypeOf2.default)(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0, _getPrototypeOf2.default)(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0, _possibleConstructorReturn2.default)(this, result); }; }

function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }

var prefix = _utils.default.prefixCls;

function filterAmount() {
  var mode = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'currency';
  var moneySet = arguments.length > 1 ? arguments[1] : undefined;
  if (!moneySet && moneySet !== 0) return;
  var result;

  if (mode === 'currency' || mode === 'hidecurrency') {
    result = moneySet && moneySet.amount;
  } else {
    result = _lodash.default.isObject(moneySet) ? moneySet.amount : moneySet;
  }

  return result;
}
/**extraProps说明
 * @param {boolean} currencyVailable 主金额币种可编辑性
 * @param {boolean} showExchangeRate 展示汇率信息
 * @param {boolean} exchangeRateEditAble 汇率转换可编辑性
 *  */


var MoneyField = /*#__PURE__*/function (_Component) {
  (0, _inherits2.default)(MoneyField, _Component);

  var _super = _createSuper(MoneyField);

  function MoneyField(_props) {
    var _this;

    (0, _classCallCheck2.default)(this, MoneyField);
    _this = _super.call(this, _props);

    _this.localeProcess = function () {
      _mkTranslate.default.getNameSpace('MK_MoneyField').then(function (t) {
        _this.setState({
          t: t
        });
      });
    };

    _this.handleChange = function (e) {
      var thisValue = e.target.value;

      if (thisValue.startsWith('0') && !thisValue.startsWith('0.')) {
        thisValue = thisValue.slice(thisValue.length - 1);
      }

      ; //不能输入大于1e12的值

      if (_lodash.default.toNumber(thisValue) >= 1e12) return;
      _this.status = 'CHANGING';

      _this.setState({
        value: thisValue
      });
    };

    _this.handleParentChange = function (val) {
      var changeType = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'both';
      var _this$props = _this.props,
          onChange = _this$props.onChange,
          _this$props$fieldProp = _this$props.fieldProperties.mode,
          mode = _this$props$fieldProp === void 0 ? 'currency' : _this$props$fieldProp,
          value = _this$props.value;
      var changeValue;

      if (mode === 'currency' || mode === 'hidecurrency') {
        changeValue = val;
      } else {
        if (_lodash.default.isObject(val)) {
          changeValue = val.amount;
        } else {
          changeValue = val;
        }
      }

      if (['onChange', 'both'].includes(changeType)) {
        if (!_lodash.default.isEqual(changeValue, value)) {
          onChange && onChange(changeValue);
        }
      }
    };

    _this.handleCurrencyChange = function (currency) {
      var key = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'currentCurrency';
      var _this$state = _this.state,
          value = _this$state.value,
          currentCurrency = _this$state.currentCurrency,
          toCurrency = _this$state.toCurrency;

      _utils.default.handleCurrencyOperation(currency.code); //cookie中cache操作记录


      var changedValue = key === 'currentCurrency' ? {
        currency: currency.code,
        amount: (0, _numeral.default)(value).value(),
        toCurrency: toCurrency.code,
        customExchangeRate: undefined
      } : {
        currency: currentCurrency.code,
        amount: (0, _numeral.default)(value).value(),
        toCurrency: currency.code,
        customExchangeRate: undefined
      };

      _this.handleParentChange(changedValue);

      _this.setState((0, _defineProperty2.default)({}, key, currency));
    };

    _this.handleFocus = function (e) {
      var value = (0, _numeral.default)(e.target.value).value();
      _this.status = 'FOCUS';

      _this.setState({
        value: value
      });
    };

    _this.handleBlur = function (e) {
      var _this$state2 = _this.state,
          currentCurrency = _this$state2.currentCurrency,
          customExchangeRate = _this$state2.customExchangeRate,
          originValue = _this$state2.originValue,
          toCurrency = _this$state2.toCurrency;
      var _this$props2 = _this.props,
          _this$props2$fieldPro = _this$props2.fieldProperties.mode,
          mode = _this$props2$fieldPro === void 0 ? 'currency' : _this$props2$fieldPro,
          specialFieldPerm = _this$props2.fieldProperties.specialFieldPerm,
          oldValue = _this$props2.value;
      var value = parseFloat(e.target.value);
      _this.status = 'BLUR';

      if (specialFieldPerm) {
        if (_lodash.default.subtract(value, originValue) > 0 && !specialFieldPerm.increase) {
          _this.setState({
            value: filterAmount(mode, oldValue)
          });

          _modal.default.warning({
            content: "\u8BE5\u5B57\u6BB5\u53EA\u80FD\u8C03\u6574\u4E3A\u5C0F\u4E8E".concat(originValue, "\u7684\u503C"),
            okText: '确定'
          });

          return;
        } else if (_lodash.default.subtract(value, originValue) < 0 && !specialFieldPerm.reduce) {
          _this.setState({
            value: filterAmount(mode, oldValue)
          });

          _modal.default.warning({
            content: "\u8BE5\u5B57\u6BB5\u53EA\u80FD\u8C03\u6574\u4E3A\u5927\u4E8E".concat(originValue, "\u7684\u503C"),
            okText: '确定'
          });

          return;
        }
      }

      var value1 = null,
          value2 = null; // 截取到小数点后2位(不做四舍五入)
      // value = Math.floor(value * 100) / 100;

      value = (0, _numeral.default)(value).format('0.00', Math.floor);

      if (!isNaN(value)) {
        value1 = _utils.default.formatCurrency(value, _this.valueFormat, '');
        value2 = _utils.default.formatCurrency(value, _this.numberformat, '');
      }

      value2 = {
        currency: currentCurrency.code,
        toCurrency: toCurrency.code,
        amount: isNaN(parseFloat(value2)) ? undefined : parseFloat(value2),
        customExchangeRate: customExchangeRate
      };

      _this.setState({
        value: value1
      });

      _this.handleParentChange(value2);
    };

    _this.init = function (props) {
      var money = props.value,
          readOnly = props.readOnly,
          _props$extraProps = props.extraProps,
          amount = _props$extraProps.amount,
          defaultCurrency = _props$extraProps.defaultCurrency,
          _props$fieldPropertie = props.fieldProperties,
          _props$fieldPropertie2 = _props$fieldPropertie.mode,
          mode = _props$fieldPropertie2 === void 0 ? 'currency' : _props$fieldPropertie2,
          _props$fieldPropertie3 = _props$fieldPropertie.valueFormat,
          valueFormat = _props$fieldPropertie3 === void 0 ? '0,0.00' : _props$fieldPropertie3;
      _this.valueFormat = valueFormat;
      var value = filterAmount(mode, money);
      var customExchangeRate = money.customExchangeRate,
          toCurrency = money.toCurrency;
      var currentCurrency = mode === 'currency' ? {
        code: defaultCurrency || money && money.currency
      } : {
        code: defaultCurrency || 'CNY'
      }; // 显示批准金额

      if (amount && value && 'amount' in props && value !== amount.amount && readOnly) {
        value = /*#__PURE__*/_react.default.createElement("span", null, _utils.default.formatCurrency(value, _this.valueFormat, ''), /*#__PURE__*/_react.default.createElement("span", {
          className: "org-amount"
        }, _utils.default.formatCurrency(amount.amount, _this.valueFormat, '')));
      } else if (value || value === 0) {
        value = _utils.default.formatCurrency(value, _this.valueFormat, '');
      }

      _this.setState({
        value: value,
        currentCurrency: currentCurrency,
        customExchangeRate: customExchangeRate,
        toCurrency: {
          code: toCurrency || 'CNY'
        }
      });

      if (defaultCurrency) {
        _this.handleParentChange({
          currency: currentCurrency.code,
          amount: (0, _numeral.default)(value).value()
        });
      }
    };

    _this.getAllCurrencys = function () {
      var _this$props3 = _this.props,
          getAllCurrencys = _this$props3.getAllCurrencys,
          selectedCurrencys = _this$props3.selectedCurrencys;

      _this.setState({
        currencyLoading: true
      });

      if (selectedCurrencys.length > 0) {
        _this.setState({
          selectedCurrencys: selectedCurrencys,
          currencyLoading: false
        });
      } else {
        _this.setState({
          currencyLoading: false
        });
      }

      if (typeof getAllCurrencys === 'function') {
        return getAllCurrencys().then(function (data) {
          _this.setState({
            allCurrencys: data,
            currencyLoading: false
          });
        }).catch(function () {
          _this.setState({
            currencyLoading: false
          });
        });
      }
    };

    _this.getSystemRate = function () {
      if (!_this.props.value) return;
      var _this$props4 = _this.props,
          _this$props4$value = _this$props4.value,
          currency = _this$props4$value.currency,
          customExchangeRate = _this$props4$value.customExchangeRate,
          _this$props4$extraPro = _this$props4.extraProps,
          consumeTime = _this$props4$extraPro.consumeTime,
          showExchangeRate = _this$props4$extraPro.showExchangeRate,
          getExhangeRate = _this$props4.getExhangeRate;
      if (!showExchangeRate) return;
      var toCurrency = _this.state.toCurrency;

      if (consumeTime && (consumeTime.currentTime || consumeTime.timeRange) && currency) {
        var targetDate;

        if (consumeTime.currentTime) {
          targetDate = consumeTime.currentTime;
        } else if (consumeTime.timeRange) {
          targetDate = consumeTime.timeRange.startDate;
        }

        var param = {
          targetDate: targetDate,
          fromCurrency: currency,
          toCurrency: toCurrency.code
        };

        if (typeof getExhangeRate === 'function') {
          getExhangeRate(param).then(function (rate) {
            _this.setState({
              systemRate: rate,
              customExchangeRate: customExchangeRate ? customExchangeRate : rate
            });
          });
        }
      }
    };

    _this.exchangeRateChange = function (e) {
      var thisValue = e.target.value;

      if (thisValue.startsWith('0') && !thisValue.startsWith('0.')) {
        thisValue = thisValue.slice(thisValue.length - 1);
      }

      if (isNaN(thisValue)) {
        thisValue = _this.state.customExchangeRate;
      } //不能输入大于1e12的值


      if (_lodash.default.toNumber(thisValue) >= 1e12) return;

      _this.setState({
        customExchangeRate: thisValue
      });
    };

    _this.exchangeRateBlur = function (e) {
      var _this$state3 = _this.state,
          currentCurrency = _this$state3.currentCurrency,
          value = _this$state3.value,
          toCurrency = _this$state3.toCurrency;
      var thisValue = e.target.value;

      _this.setState({
        customExchangeRate: thisValue
      });

      var value2 = {
        currency: currentCurrency.code,
        toCurrency: toCurrency.code,
        amount: (0, _numeral.default)(value).value(),
        customExchangeRate: thisValue
      };

      _this.handleParentChange(value2);
    };

    var fieldProperties = _props.fieldProperties;
    _this.valueFormat = fieldProperties.valueFormat || '0,0.00';
    _this.numberformat = _this.valueFormat === '0,0.00' ? '0.00' : '0';
    _this.formatFlag = true;
    _this.status = 'BLUR';
    _this.state = {
      value: filterAmount(fieldProperties.mode, _props.value),
      originValue: filterAmount(fieldProperties.mode, _props.value) || 0,
      latestCurrencys: _cookie.default.get('latestCurrencys') || [],
      allCurrencys: [],
      selectedCurrencys: [],
      currentCurrency: {
        code: 'CNY'
      },
      toCurrency: {
        code: 'CNY'
      },
      customExchangeRate: undefined,
      systemRate: undefined,
      currencyLoading: false,
      t: _mkTranslate.default.noop(),
      currencySelectorShow: false,
      erCurrencySelectorShow: false
    };

    _this.localeProcess();

    return _this;
  }

  (0, _createClass2.default)(MoneyField, [{
    key: "componentDidUpdate",
    value: function componentDidUpdate(prevProps, prevState) {
      var prevExtraProps = prevProps.extraProps;
      var _this$props5 = this.props,
          onChange = _this$props5.onChange,
          value = _this$props5.value,
          extraProps = _this$props5.extraProps;
      var prevAmount = prevExtraProps.amount;
      var amount = extraProps.amount;

      if (!_lodash.default.isEqual(prevProps.value, value) || !_lodash.default.isEqual(prevAmount, amount)) {
        if (this.formatFlag) {
          if (this.status === 'BLUR') {
            this.init(this.props);
            this.formatFlag = false;
          }
        } else if (this.status === 'BLUR') {
          this.init(this.props);
        }

        if (typeof onChange === 'function') {
          this.handleParentChange(value);
        }
      }

      if (prevProps && this.props && (!_lodash.default.isEqual(prevExtraProps.consumeTime, extraProps.consumeTime) || !_lodash.default.isEqual(prevProps.value.currency, value.currency) || !_lodash.default.isEqual(prevProps.value.toCurrency, value.toCurrency))) {
        this.getSystemRate();
      }
    }
  }, {
    key: "componentDidMount",
    value: function componentDidMount() {
      var value = this.props.value;

      if (value) {
        this.init(this.props);
        this.formatFlag = false;
        this.getSystemRate();
      }
    }
  }, {
    key: "render",
    value: function render() {
      var _this2 = this;

      var _this$state4 = this.state,
          value = _this$state4.value,
          toCurrency = _this$state4.toCurrency,
          currencySelectorShow = _this$state4.currencySelectorShow,
          erCurrencySelectorShow = _this$state4.erCurrencySelectorShow,
          t = _this$state4.t;
      var _this$props6 = this.props,
          readOnly = _this$props6.readOnly,
          _this$props6$fieldPro = _this$props6.fieldProperties,
          _this$props6$fieldPro2 = _this$props6$fieldPro.placeholder,
          placeholder = _this$props6$fieldPro2 === void 0 ? this.state.t('enterAmount') : _this$props6$fieldPro2,
          _this$props6$fieldPro3 = _this$props6$fieldPro.mode,
          mode = _this$props6$fieldPro3 === void 0 ? 'currency' : _this$props6$fieldPro3,
          Ismodify = _this$props6$fieldPro.Ismodify,
          _this$props6$extraPro = _this$props6.extraProps,
          currencyVailable = _this$props6$extraPro.currencyVailable,
          showExchangeRate = _this$props6$extraPro.showExchangeRate,
          exchangeRateEditAble = _this$props6$extraPro.exchangeRateEditAble,
          deliverySystemrate = _this$props6$extraPro.deliverySystemrate,
          isInTable = _this$props6$extraPro.isInTable,
          fieldStyleCategory = _this$props6$extraPro.fieldStyleCategory;
      var _this$state5 = this.state,
          latestCurrencys = _this$state5.latestCurrencys,
          allCurrencys = _this$state5.allCurrencys,
          selectedCurrencys = _this$state5.selectedCurrencys,
          currentCurrency = _this$state5.currentCurrency,
          currencyLoading = _this$state5.currencyLoading,
          customExchangeRate = _this$state5.customExchangeRate,
          systemRate = _this$state5.systemRate;
      var currencyDisable = !currencyVailable || readOnly;
      var toCurrencyDisable = !exchangeRateEditAble ? true : false;
      var cnyClz = (0, _classnames.default)('currency-dropdown', {
        'readonly': readOnly,
        'disabled': currencyDisable
      });
      return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement("div", {
        className: "".concat(prefix, "-money-wrapper ").concat(isInTable ? 'in-table' : '')
      }, mode === 'currency' ? /*#__PURE__*/_react.default.createElement(_CurrencySelector.default, {
        latestCurrencys: latestCurrencys,
        data: allCurrencys,
        loading: currencyLoading,
        onChange: this.handleCurrencyChange,
        disabled: currencyDisable,
        visibleChange: function visibleChange(visible) {
          if (visible) _this2.getAllCurrencys();

          _this2.setState({
            currencySelectorShow: visible
          });
        }
      }, /*#__PURE__*/_react.default.createElement("div", {
        className: cnyClz
      }, /*#__PURE__*/_react.default.createElement("span", {
        style: {
          marginRight: 4,
          lineHeight: 'normal'
        }
      }, currentCurrency.code), !currencyDisable ? /*#__PURE__*/_react.default.createElement(_icon.default, {
        type: "down",
        className: "money-currency-down ".concat(currencySelectorShow ? 'money-currency-up' : '')
      }) : null)) : null, /*#__PURE__*/_react.default.createElement(_input.default, {
        ref: this.props.forwardedRef,
        value: value,
        placeholder: placeholder,
        onChange: this.handleChange,
        onFocus: this.handleFocus,
        onBlur: this.handleBlur,
        disabled: readOnly,
        category: fieldStyleCategory
      })), Ismodify ? /*#__PURE__*/_react.default.createElement("span", {
        className: "fm fm-revised"
      }) : null, showExchangeRate && /*#__PURE__*/_react.default.createElement("div", {
        className: "".concat(prefix, "-exchange-wrapper")
      }, /*#__PURE__*/_react.default.createElement("div", {
        className: "exchange-collection"
      }, !readOnly || exchangeRateEditAble ? /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement("span", {
        className: "exchange-collection-title"
      }, t('CollectionAmount')), /*#__PURE__*/_react.default.createElement(_CurrencySelector.default, {
        latestCurrencys: latestCurrencys,
        data: selectedCurrencys,
        loading: currencyLoading,
        onChange: function onChange(currency) {
          _this2.handleCurrencyChange(currency, 'toCurrency');
        },
        disabled: toCurrencyDisable,
        visibleChange: function visibleChange(visible) {
          if (visible) _this2.getAllCurrencys();

          _this2.setState({
            erCurrencySelectorShow: visible
          });
        }
      }, /*#__PURE__*/_react.default.createElement("div", {
        className: cnyClz
      }, /*#__PURE__*/_react.default.createElement("span", {
        style: {
          marginRight: 4,
          lineHeight: 'normal'
        }
      }, toCurrency.code), !toCurrencyDisable ? /*#__PURE__*/_react.default.createElement(_icon.default, {
        type: "down",
        className: "money-currency-down ".concat(erCurrencySelectorShow ? 'money-currency-up' : '')
      }) : null)), /*#__PURE__*/_react.default.createElement("span", {
        className: 'exchange-amount-value'
      }, this.props.value ? (0, _numeral.default)(this.props.value.amount * Number(customExchangeRate)).format('0,0.00') : 0)) : null), /*#__PURE__*/_react.default.createElement("div", {
        className: "exchange-rate"
      }, /*#__PURE__*/_react.default.createElement("div", {
        className: "coustom-rate"
      }, /*#__PURE__*/_react.default.createElement("span", {
        className: "rate"
      }, t('ExchangeRate')), /*#__PURE__*/_react.default.createElement(_input.default, {
        disabled: toCurrency.code === currentCurrency.code || toCurrencyDisable,
        value: customExchangeRate,
        onChange: this.exchangeRateChange,
        onBlur: this.exchangeRateBlur,
        style: {
          height: '20px',
          fontSize: '12px'
        }
      })), /*#__PURE__*/_react.default.createElement("div", {
        className: "system-rate"
      }, /*#__PURE__*/_react.default.createElement("span", {
        className: "rate-title"
      }, t('ReferenceRate')), /*#__PURE__*/_react.default.createElement("span", {
        className: "value"
      }, deliverySystemrate ? deliverySystemrate : systemRate || t('NA'))))));
    }
  }]);
  return MoneyField;
}(_react.Component);

MoneyField.defaultProps = {
  value: {
    currency: 'CNY',
    toCurrency: 'CNY',
    amount: undefined,
    customExchangeRate: undefined
  }
};

var _default = /*#__PURE__*/_react.default.forwardRef(function (props, ref) {
  var mode = props.fieldProperties.mode,
      value = props.value;
  var convertValue;

  if (value !== undefined) {
    if (_lodash.default.isObject(value)) {
      convertValue = value;
    } else if (_lodash.default.isNumber(value)) {
      if (mode === 'money') {
        convertValue = value;
      } else {
        convertValue = {
          currency: 'CNY',
          amount: value
        };
      }
    }
  } else {
    convertValue = value;
  }

  return /*#__PURE__*/_react.default.createElement(MoneyField, (0, _extends2.default)({}, props, {
    value: convertValue,
    ref: ref
  }));
});

exports.default = _default;