import dayjs from 'dayjs';
import { formatProductsByVariant } from "../../../components/shoppingCart/utils";
/**
 * 生成赠品弹窗 context 的稳定 key，用于避免同一 pending 重复 openModal。
 *
 * @example
 * const key = buildGiftSelectContextKey(ctx);
 */
export function buildGiftSelectContextKey(ctx) {
  var optionKey = (ctx.giftOptions || []).map(function (o) {
    var _o$product_variant_id;
    return "".concat(o.product_id, ":").concat((_o$product_variant_id = o.product_variant_id) !== null && _o$product_variant_id !== void 0 ? _o$product_variant_id : 0);
  }).join('|');
  return [ctx.strategyId, ctx.mode || 'add', ctx.giftCount, (ctx.sourceProductIds || []).join(','), optionKey].join('#');
}

/**
 * 判断当前 context 是否应打开赠品弹窗。
 * - 首次加购：候选 ≥ 2
 * - 购物车重选（mode=edit）：候选 ≥ 1 即可
 *
 * @example
 * if (shouldOpenGiftSelectModal(ctx)) openModal(mapGiftSelectContextToLegacyItem(ctx));
 */
export function shouldOpenGiftSelectModal(ctx) {
  if (!ctx || !ctx.giftCount || ctx.giftCount <= 0) return false;
  if (!Array.isArray(ctx.giftOptions) || ctx.giftOptions.length === 0) return false;
  if (ctx.mode === 'edit') return true;
  return ctx.giftOptions.length >= 2;
}

/**
 * SalesSdk GiftSelect context → legacy usePromotionModal item 结构。
 *
 * @example
 * openModal(mapGiftSelectContextToLegacyItem(ctx));
 */
export function mapGiftSelectContextToLegacyItem(ctx, options) {
  var _ctx$initialChoices, _ctx$sourceProductIds;
  var giftOptions = ctx.giftOptions || [];
  var products = formatProductsByVariant(giftOptions);
  var isMultiple = ctx.giftCount > 1;
  var selectedOrigin = ctx._selectedOriginGifts || [];
  var selected = isMultiple ? [] : '';
  if ((_ctx$initialChoices = ctx.initialChoices) !== null && _ctx$initialChoices !== void 0 && _ctx$initialChoices.length) {
    if (isMultiple) {
      selected = ctx.initialChoices.map(function (c) {
        return {
          value: c.product_id,
          quantity: c.quantity
        };
      });
    } else {
      var _ctx$initialChoices$;
      selected = ((_ctx$initialChoices$ = ctx.initialChoices[0]) === null || _ctx$initialChoices$ === void 0 ? void 0 : _ctx$initialChoices$.product_id) || '';
    }
  } else if (selectedOrigin.length) {
    if (isMultiple) {
      selected = selectedOrigin.map(function (item) {
        var _ref, _item$num;
        return {
          value: item.product_id || item.id,
          quantity: Number((_ref = (_item$num = item.num) !== null && _item$num !== void 0 ? _item$num : item.quantity) !== null && _ref !== void 0 ? _ref : 1) || 1
        };
      });
    } else {
      var _selectedOrigin$, _selectedOrigin$2;
      selected = ((_selectedOrigin$ = selectedOrigin[0]) === null || _selectedOrigin$ === void 0 ? void 0 : _selectedOrigin$.product_id) || ((_selectedOrigin$2 = selectedOrigin[0]) === null || _selectedOrigin$2 === void 0 ? void 0 : _selectedOrigin$2.id) || '';
    }
  }
  var giftInfo = {
    giftOptions: giftOptions,
    giftCount: ctx.giftCount
  };
  var scheduleDate = options === null || options === void 0 ? void 0 : options.scheduleDate;
  var legacyState = scheduleDate ? {
    date: {
      value: dayjs(scheduleDate)
    }
  } : undefined;
  return {
    giftInfo: giftInfo,
    strategyId: ctx.strategyId,
    strategyName: ctx.strategyName,
    sourceProductId: (_ctx$sourceProductIds = ctx.sourceProductIds) === null || _ctx$sourceProductIds === void 0 ? void 0 : _ctx$sourceProductIds[0],
    sourceProductIds: ctx.sourceProductIds,
    products: products,
    isMultiple: isMultiple,
    isGift: true,
    selected: selected,
    selectedProducts: selectedOrigin,
    isEdit: ctx.mode === 'edit' || selectedOrigin.length > 0,
    _selectedOriginGifts: selectedOrigin,
    promotionInfo: {
      strategyId: ctx.strategyId,
      strategyName: ctx.strategyName,
      giftInfo: giftInfo
    },
    /** legacy usePromotionModal 读取 schedule_date 用 */
    state: legacyState
  };
}

/**
 * legacy usePromotionModal 选中商品 → SalesSdkGiftSelectChoice[]。
 *
 * @example
 * const choices = convertLegacySelectedToChoices(selectedProducts);
 */
export function convertLegacySelectedToChoices(selectedProducts) {
  if (!Array.isArray(selectedProducts) || !selectedProducts.length) return [];
  return selectedProducts.map(function (product) {
    var _product$product_id, _ref2, _ref3, _product$product_vari, _product$_extend, _product$_extend2, _ref4, _ref5, _product$_extend$quan, _product$_extend3;
    var productId = Number((_product$product_id = product === null || product === void 0 ? void 0 : product.product_id) !== null && _product$product_id !== void 0 ? _product$product_id : product === null || product === void 0 ? void 0 : product.id);
    var variantId = Number((_ref2 = (_ref3 = (_product$product_vari = product === null || product === void 0 ? void 0 : product.product_variant_id) !== null && _product$product_vari !== void 0 ? _product$product_vari : product === null || product === void 0 || (_product$_extend = product._extend) === null || _product$_extend === void 0 || (_product$_extend = _product$_extend.other) === null || _product$_extend === void 0 ? void 0 : _product$_extend.product_variant_id) !== null && _ref3 !== void 0 ? _ref3 : product === null || product === void 0 || (_product$_extend2 = product._extend) === null || _product$_extend2 === void 0 || (_product$_extend2 = _product$_extend2._skuValue) === null || _product$_extend2 === void 0 ? void 0 : _product$_extend2.product_variant_id) !== null && _ref2 !== void 0 ? _ref2 : 0);
    var quantity = Number((_ref4 = (_ref5 = (_product$_extend$quan = product === null || product === void 0 || (_product$_extend3 = product._extend) === null || _product$_extend3 === void 0 ? void 0 : _product$_extend3.quantity) !== null && _product$_extend$quan !== void 0 ? _product$_extend$quan : product === null || product === void 0 ? void 0 : product.num) !== null && _ref5 !== void 0 ? _ref5 : product === null || product === void 0 ? void 0 : product.quantity) !== null && _ref4 !== void 0 ? _ref4 : 1) || 1;
    if (!productId) return null;
    return {
      product_id: productId,
      product_variant_id: variantId,
      quantity: quantity,
      // confirm 后 buildGiftOrderProductsFromChoices 优先复用，避免二次打接口
      _productSnapshot: product
    };
  }).filter(Boolean);
}