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 _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 _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, useCallback, useState } from 'react';
import PisellHeader from "../../pisellLayout/header";
import PisellSteps from "../../PisellSteps";
import PisellModal from "../../pisellModal";
import { mergeClassNames } from "../utils";
import { getText } from "../../../locales";

/**
 * ProcedureHeader 子组件 Props
 */

/**
 * 确认弹窗类型
 */

/**
 * ProcedureHeader 头部区域组件
 * 
 * @description 包含左侧返回按钮、中间步骤条、右侧关闭按钮
 * @author Pisell Team
 */
var ProcedureHeader = function ProcedureHeader(_ref) {
  var _modalConfig$config2, _modalConfig$config3;
  var headerProps = _ref.headerProps,
    currentStep = _ref.currentStep,
    className = _ref.className,
    goPrev = _ref.goPrev,
    goToStep = _ref.goToStep,
    onClose = _ref.onClose,
    onFirstStepBack = _ref.onFirstStepBack,
    onBackConfirm = _ref.onBackConfirm,
    onCloseConfirm = _ref.onCloseConfirm;
  /** 确认弹窗类型（back: 返回确认，close: 关闭确认，null: 不显示） */
  var _useState = useState(null),
    _useState2 = _slicedToArray(_useState, 2),
    modalType = _useState2[0],
    setModalType = _useState2[1];
  /** 目标步骤索引（用于步骤跳转，-1 表示返回上一步） */
  var _useState3 = useState(-1),
    _useState4 = _slicedToArray(_useState3, 2),
    targetStep = _useState4[0],
    setTargetStep = _useState4[1];

  /** 头部区域类名 */
  var headerCls = useMemo(function () {
    return mergeClassNames('pisell-procedure-header', className, headerProps === null || headerProps === void 0 ? void 0 : headerProps.className);
  }, [className, headerProps === null || headerProps === void 0 ? void 0 : headerProps.className]);

  /** 插槽顺序，默认为默认顺序 */
  var slotOrder = (headerProps === null || headerProps === void 0 ? void 0 : headerProps.slotOrder) || 'default';

  /** 根据 slotOrder 决定实际显示的左右插槽 */
  var actualLeftSlot = useMemo(function () {
    return slotOrder === 'reverse' ? headerProps === null || headerProps === void 0 ? void 0 : headerProps.right : headerProps === null || headerProps === void 0 ? void 0 : headerProps.left;
  }, [slotOrder, headerProps === null || headerProps === void 0 ? void 0 : headerProps.left, headerProps === null || headerProps === void 0 ? void 0 : headerProps.right]);
  var actualRightSlot = useMemo(function () {
    return slotOrder === 'reverse' ? headerProps === null || headerProps === void 0 ? void 0 : headerProps.left : headerProps === null || headerProps === void 0 ? void 0 : headerProps.right;
  }, [slotOrder, headerProps === null || headerProps === void 0 ? void 0 : headerProps.left, headerProps === null || headerProps === void 0 ? void 0 : headerProps.right]);

  /** 是否显示左侧区域（考虑插槽顺序） */
  var showActualLeftArea = useMemo(function () {
    if (!actualLeftSlot) return false;
    // 第一步时根据配置决定是否显示，默认不显示
    // 注意：当 slotOrder='reverse' 时，actualLeftSlot 实际上是 right 插槽（关闭按钮），应该始终显示
    if (slotOrder === 'reverse') {
      return true; // 关闭按钮始终显示
    }
    if (currentStep === 0) {
      var _headerProps$showBack;
      return (_headerProps$showBack = headerProps === null || headerProps === void 0 ? void 0 : headerProps.showBackOnFirstStep) !== null && _headerProps$showBack !== void 0 ? _headerProps$showBack : false;
    }
    // 非第一步始终显示
    return true;
  }, [actualLeftSlot, slotOrder, currentStep, headerProps === null || headerProps === void 0 ? void 0 : headerProps.showBackOnFirstStep]);

  /** 是否显示右侧区域（考虑插槽顺序） */
  var showActualRightArea = useMemo(function () {
    return !!actualRightSlot;
  }, [actualRightSlot]);

  /**
   * 关闭确认弹窗
   */
  var closeModal = useCallback(function () {
    setModalType(null);
    setTargetStep(-1);
  }, []);

  /**
   * 统一处理返回和步骤跳转
   * @param step 目标步骤索引，如果未传递或 < 0 则表示返回上一步
   */
  var handleBackClick = useCallback(function (step) {
    // 第一步且显示返回按钮，触发首步返回回调（仅返回按钮触发，步骤跳转不受此限制）
    if (currentStep === 0 && headerProps !== null && headerProps !== void 0 && headerProps.showBackOnFirstStep && (step === undefined || step < 0)) {
      if (onFirstStepBack) {
        onFirstStepBack();
      } else {
        // 默认跳转到首页（仅在浏览器环境中执行）
        if (typeof window !== 'undefined' && window.location) {
          window.location.href = '/';
        }
      }
      return;
    }
    var modalConfig = headerProps === null || headerProps === void 0 ? void 0 : headerProps.backConfirmModal;
    var isStepJump = step !== undefined && step >= 0;

    // 保存目标步骤
    setTargetStep(isStepJump ? step : -1);

    // 未启用确认弹窗，直接执行操作
    if (!(modalConfig !== null && modalConfig !== void 0 && modalConfig.enabled)) {
      if (isStepJump) {
        goToStep === null || goToStep === void 0 || goToStep(step);
      } else {
        goPrev === null || goPrev === void 0 || goPrev();
      }
      return;
    }

    // 显示返回确认弹窗
    setModalType('back');
  }, [currentStep, headerProps, onFirstStepBack, goPrev, goToStep]);

  /**
   * 处理关闭按钮点击
   */
  var handleCloseClick = useCallback(function () {
    var modalConfig = headerProps === null || headerProps === void 0 ? void 0 : headerProps.closeConfirmModal;

    // 未启用确认弹窗，直接调用 onClose 回调
    if (!(modalConfig !== null && modalConfig !== void 0 && modalConfig.enabled)) {
      onClose === null || onClose === void 0 || onClose();
      return;
    }

    // 显示关闭确认弹窗
    setModalType('close');
  }, [headerProps, onClose]);

  /**
   * 处理确认操作
   */
  var handleConfirm = useCallback(function (action) {
    var isConfirm = action === 'ok' || action === 'confirm';
    if (modalType === 'back') {
      // 返回确认或步骤跳转确认
      if (isConfirm) {
        onBackConfirm === null || onBackConfirm === void 0 || onBackConfirm(action);
        // 根据目标步骤决定调用 goToStep 还是 goPrev
        if (targetStep >= 0) {
          goToStep === null || goToStep === void 0 || goToStep(targetStep);
        } else {
          goPrev === null || goPrev === void 0 || goPrev();
        }
      }
    } else if (modalType === 'close') {
      // 关闭确认
      if (isConfirm) {
        onCloseConfirm === null || onCloseConfirm === void 0 || onCloseConfirm(action);
        onClose === null || onClose === void 0 || onClose();
      }
    }
    closeModal();
  }, [modalType, targetStep, onBackConfirm, onCloseConfirm, goPrev, goToStep, onClose, closeModal]);

  /**
   * 获取当前弹窗的配置
   */
  var modalConfig = useMemo(function () {
    if (modalType === 'back') {
      return {
        config: headerProps === null || headerProps === void 0 ? void 0 : headerProps.backConfirmModal,
        titleKey: 'pisell-procedure-header-back-confirm-title',
        descKey: 'pisell-procedure-header-back-confirm-desc',
        okTextKey: 'pisell-procedure-header-back-confirm-yes',
        cancelTextKey: 'pisell-procedure-header-back-confirm-no'
      };
    } else if (modalType === 'close') {
      return {
        config: headerProps === null || headerProps === void 0 ? void 0 : headerProps.closeConfirmModal,
        titleKey: 'pisell-procedure-header-close-confirm-title',
        descKey: 'pisell-procedure-header-close-confirm-desc',
        okTextKey: 'pisell-procedure-header-close-confirm-yes',
        cancelTextKey: 'pisell-procedure-header-close-confirm-no'
      };
    }
    return null;
  }, [modalType, headerProps]);

  /**
   * 处理 footer 按钮配置
   */
  var processedFooter = useMemo(function () {
    var _modalConfig$config;
    if (!modalConfig) return undefined;
    var footer = (_modalConfig$config = modalConfig.config) === null || _modalConfig$config === void 0 ? void 0 : _modalConfig$config.footer;
    // 确保 footer 是数组
    if (!footer || !Array.isArray(footer) || footer.length === 0) return undefined;
    return footer.map(function (btn) {
      // 确保 btn 是有效对象
      if (!btn || _typeof(btn) !== 'object' || !btn.action) return btn;
      var processedBtn = _objectSpread({}, btn);
      var originalOnClick = processedBtn.onClick;
      processedBtn.onClick = function () {
        for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
          args[_key] = arguments[_key];
        }
        originalOnClick === null || originalOnClick === void 0 || originalOnClick.apply(void 0, args);
        handleConfirm(btn.action);
      };
      return processedBtn;
    });
  }, [modalConfig, handleConfirm]);

  /** 合并步骤条配置 */
  var mergedStepsProps = useMemo(function () {
    return _objectSpread(_objectSpread({}, headerProps === null || headerProps === void 0 ? void 0 : headerProps.stepsProps), {}, {
      current: currentStep,
      onChange: function onChange(step) {
        var _headerProps$stepsPro, _headerProps$stepsPro2;
        // 先调用外部传入的 onChange（如果有）
        headerProps === null || headerProps === void 0 || (_headerProps$stepsPro = headerProps.stepsProps) === null || _headerProps$stepsPro === void 0 || (_headerProps$stepsPro2 = _headerProps$stepsPro.onChange) === null || _headerProps$stepsPro2 === void 0 || _headerProps$stepsPro2.call(_headerProps$stepsPro, step);
        // 统一走 handleBackClick 处理逻辑
        handleBackClick(step);
      }
    });
  }, [headerProps === null || headerProps === void 0 ? void 0 : headerProps.stepsProps, currentStep, handleBackClick]);
  return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(PisellHeader, {
    className: headerCls,
    style: headerProps === null || headerProps === void 0 ? void 0 : headerProps.style
  }, showActualLeftArea && /*#__PURE__*/React.createElement("div", {
    className: "pisell-procedure-header__left",
    onClick: function onClick() {
      // 根据 slotOrder 决定点击事件：reverse 时左侧是关闭按钮，default 时左侧是返回按钮
      if (slotOrder === 'reverse') {
        handleCloseClick();
      } else {
        handleBackClick();
      }
    }
  }, actualLeftSlot), (headerProps === null || headerProps === void 0 ? void 0 : headerProps.showSteps) !== false && /*#__PURE__*/React.createElement("div", {
    className: "pisell-procedure-header__center"
  }, /*#__PURE__*/React.createElement(PisellSteps, _extends({}, mergedStepsProps, {
    mobileMode: "auto",
    mobileBreakpoint: 744
  }))), showActualRightArea && /*#__PURE__*/React.createElement("div", {
    className: "pisell-procedure-header__right",
    onClick: function onClick() {
      // 根据 slotOrder 决定点击事件：reverse 时右侧是返回按钮，default 时右侧是关闭按钮
      if (slotOrder === 'reverse') {
        handleBackClick();
      } else {
        handleCloseClick();
      }
    }
  }, actualRightSlot)), modalType && modalConfig && /*#__PURE__*/React.createElement(PisellModal.Information, {
    open: true,
    title: ((_modalConfig$config2 = modalConfig.config) === null || _modalConfig$config2 === void 0 ? void 0 : _modalConfig$config2.title) || getText(modalConfig.titleKey) || '',
    describe: ((_modalConfig$config3 = modalConfig.config) === null || _modalConfig$config3 === void 0 ? void 0 : _modalConfig$config3.describe) || getText(modalConfig.descKey) || '',
    footer: processedFooter,
    okText: getText(modalConfig.okTextKey) || '',
    cancelText: getText(modalConfig.cancelTextKey) || '',
    closable: true,
    onCancel: closeModal,
    onOk: function onOk() {
      return handleConfirm('ok');
    }
  }));
};
ProcedureHeader.displayName = 'ProcedureHeader';
export default ProcedureHeader;