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 _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 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, { useMemo, useRef, useState } from 'react';
import { formatAmount, locales } from '@pisell/utils';
import EmptyBooking from "../components/emptyBooking";
import TabPane from "../components/tabPane";
import DepositItem from "./DepositItem";
import EditDepositModal from "./EditDepositModal";
import { Button, Modal } from 'antd';
import { getSumTotal } from "../components/footer/amount";
import useEngineContext from "../../../hooks/useEngineContext";
import { request } from "../utils";
import { editDepositAmount } from "./serve";
import dayjs from 'dayjs';
var Deposit = function Deposit(props) {
  var _context$appHelper, _bookingDetail$bookin;
  var globalState = props.globalState,
    setState = props.setState;
  var _useState = useState(false),
    _useState2 = _slicedToArray(_useState, 2),
    loading = _useState2[0],
    setLoading = _useState2[1];
  var _Modal$useModal = Modal.useModal(),
    _Modal$useModal2 = _slicedToArray(_Modal$useModal, 2),
    modal = _Modal$useModal2[0],
    contextHolder = _Modal$useModal2[1];
  var editDepositModalRef = useRef();
  var context = useEngineContext();
  var _ref = ((_context$appHelper = context.appHelper) === null || _context$appHelper === void 0 ? void 0 : _context$appHelper.utils) || {},
    isTerminal = _ref.isTerminal,
    interaction = _ref.interaction,
    action = _ref.action,
    storage = _ref.storage;
  var isTeam = useMemo(function () {
    return storage.get('channel') === 'android_team_portal' || storage.get('channel') === 'ios_team_portal';
  }, []);
  request.setRequest(context.appHelper.utils.request);
  var bookingDetail = globalState.bookingDetail,
    bookingId = globalState.bookingId,
    amountSymbol = globalState.amountSymbol,
    generatePaymentLink = globalState.generatePaymentLink,
    locale = globalState.locale,
    callback = globalState.callback;
  var sendEmail = function sendEmail(id) {
    action({
      type: 'pisell1.sendPayLinkEmail',
      data: {
        id: id,
        is_deposit: 1,
        deposit_payment_time: bookingDetail.deposit_payment_time,
        customer: bookingDetail.customer,
        contacts: bookingDetail === null || bookingDetail === void 0 ? void 0 : bookingDetail.contacts
      },
      callback: function callback() {}
    });
  };
  var create = function create() {
    var _editDepositModalRef$, _editDepositModalRef$2;
    (_editDepositModalRef$ = editDepositModalRef.current) === null || _editDepositModalRef$ === void 0 || (_editDepositModalRef$2 = _editDepositModalRef$.handleOpen) === null || _editDepositModalRef$2 === void 0 || _editDepositModalRef$2.call(_editDepositModalRef$);
  };
  var deleteDeposit = function deleteDeposit() {
    modal.confirm({
      title: locales.getText('pisell2.text.deposit-delete-message-title'),
      content: locales.getText('pisell2.text.deposit-delete-message'),
      onOk: function onOk() {
        editDepositAmount(bookingDetail.id, {
          deposit_amount: 0
        }).then(function (res) {
          setState({
            bookingDetail: _objectSpread(_objectSpread({}, bookingDetail), {}, {
              deposit_amount: 0,
              is_deposit: 0
            })
          });
          callback === null || callback === void 0 || callback({
            order_id: bookingId,
            afterCloseUpdate: true
          });
        });
      }
    });
  };

  // 订单金额计算
  var total = useMemo(function () {
    return getSumTotal(globalState, false);
  }, [globalState]);
  var depositList = useMemo(function () {
    if (!bookingId) return [];
    if ((bookingDetail === null || bookingDetail === void 0 ? void 0 : bookingDetail.is_deposit) === 0) return [];
    return [{
      customer: bookingDetail === null || bookingDetail === void 0 ? void 0 : bookingDetail.customer,
      status: bookingDetail === null || bookingDetail === void 0 ? void 0 : bookingDetail.deposit_payment_status,
      totalAmount: total.expectAmount,
      depositAmount: bookingDetail === null || bookingDetail === void 0 ? void 0 : bookingDetail.deposit_amount,
      depositUnPaidAmount: bookingDetail === null || bookingDetail === void 0 ? void 0 : bookingDetail.deposit_unpaid_amount,
      depositOriginPaidAmount: bookingDetail === null || bookingDetail === void 0 ? void 0 : bookingDetail.deposit_origin_paid_amount,
      depositPaidAmount: bookingDetail === null || bookingDetail === void 0 ? void 0 : bookingDetail.deposit_paid_amount,
      createdTime: dayjs(bookingDetail === null || bookingDetail === void 0 ? void 0 : bookingDetail.created_at).format(locale === 'en' ? 'dddd, D MMMM YYYY HH:mm' : 'YYYY-MM-DD HH:mm'),
      orderId: bookingDetail === null || bookingDetail === void 0 ? void 0 : bookingDetail.id,
      orderNumber: bookingDetail === null || bookingDetail === void 0 ? void 0 : bookingDetail.shop_full_order_number,
      amountSymbol: (globalState === null || globalState === void 0 ? void 0 : globalState.amountSymbol) || '$',
      totalAmountStr: formatAmount(total.expectAmount, 2, (globalState === null || globalState === void 0 ? void 0 : globalState.amountSymbol) || '$')
    }];
  }, [bookingDetail, total === null || total === void 0 ? void 0 : total.expectAmount, globalState === null || globalState === void 0 ? void 0 : globalState.amountSymbol, bookingDetail === null || bookingDetail === void 0 ? void 0 : bookingDetail.deposit_amount]);
  var isBookingCancelled = (bookingDetail === null || bookingDetail === void 0 || (_bookingDetail$bookin = bookingDetail.bookings) === null || _bookingDetail$bookin === void 0 ? void 0 : _bookingDetail$bookin.appointment_status) === 'cancelled';
  var isPaid = (bookingDetail === null || bookingDetail === void 0 ? void 0 : bookingDetail.deposit_payment_status) === 'paid';
  var footer = useMemo(function () {
    if (!bookingId) return null;
    // 预约状态取消时不展示添加按钮
    if (isBookingCancelled) return null;
    // 已经支付过的不展示添加按钮
    if (isPaid) return null;
    return /*#__PURE__*/React.createElement("div", {
      className: "pisell-lowcode__booking-deposit-footer"
    }, /*#__PURE__*/React.createElement(Button, {
      size: "large",
      block: true,
      onClick: depositList.length > 0 ? deleteDeposit : create
    }, depositList.length > 0 ? locales.getText('pisell2.text.deposit-delete') : locales.getText('pisell2.text.add')));
  }, [depositList, isBookingCancelled, isPaid]);
  var handleEdit = function handleEdit(e, item) {
    var _editDepositModalRef$3, _editDepositModalRef$4;
    (_editDepositModalRef$3 = editDepositModalRef.current) === null || _editDepositModalRef$3 === void 0 || (_editDepositModalRef$4 = _editDepositModalRef$3.handleOpen) === null || _editDepositModalRef$4 === void 0 || _editDepositModalRef$4.call(_editDepositModalRef$3, item.depositAmount);
  };
  var handleChange = function handleChange(amount) {
    editDepositAmount(bookingDetail.id, {
      deposit_amount: amount
    }).then(function (res) {
      setState({
        bookingDetail: _objectSpread(_objectSpread({}, bookingDetail), {}, {
          deposit_amount: amount,
          is_deposit: 1
        })
      });
      callback === null || callback === void 0 || callback({
        order_id: bookingId,
        afterCloseUpdate: true
      });
    });
  };
  var handleGoOrderDetail = function handleGoOrderDetail() {
    if (isTerminal !== null && isTerminal !== void 0 && isTerminal()) {
      var _interaction$utils, _interaction$utils$po;
      return interaction === null || interaction === void 0 || (_interaction$utils = interaction.utils) === null || _interaction$utils === void 0 || (_interaction$utils$po = _interaction$utils.postMessageToApp) === null || _interaction$utils$po === void 0 ? void 0 : _interaction$utils$po.call(_interaction$utils, {
        module: 'booking',
        key: 'edit_order',
        data: {
          order_id: bookingDetail.id
        }
      });
    }
    globalState.action({
      type: 'pisell1.goOrderDetail',
      data: {
        '[unique_order_id]': bookingDetail.id
      }
    });
  };
  return /*#__PURE__*/React.createElement(TabPane, {
    loading: loading,
    header: locales.getText('pisell2.text.deposit-list'),
    footer: footer
  }, !bookingId || !depositList.length ? /*#__PURE__*/React.createElement(EmptyBooking, {
    description: !bookingId ? undefined : locales.getText('pisell2.text.deposit-list-empty')
  }) : depositList.map(function (item) {
    return /*#__PURE__*/React.createElement(DepositItem, _extends({
      key: item.status
    }, item, {
      generatePaymentLink: generatePaymentLink,
      sendEmail: sendEmail,
      handleGoOrderDetail: handleGoOrderDetail,
      onEdit: function onEdit(e) {
        return handleEdit(e, item);
      },
      isPaid: isPaid,
      isBookingCancelled: isBookingCancelled,
      hideOrderDetail: isTeam
    }));
  }), /*#__PURE__*/React.createElement(EditDepositModal, {
    totalAmount: total.expectAmount,
    ref: editDepositModalRef,
    amountSymbol: amountSymbol,
    onChange: handleChange
  }), contextHolder);
};
export default Deposit;