// 10、9、2、20，
import { checkEqualZero } from '@/service/utils.service';
import { COMB_ACTIVITY, HAS_DISCOUNT, INVALID_DISCOUNT } from '@/constants/order';

// 对优惠券的顺序进行人为的调整
export const handlerCouponActivityInfoList = data => {
  let { couponActivityInfoList: couponList, calcFeeInfo, addrReceiverInfo } = data;
  const activityMap = handlerCouponActivityInfoToMap(couponList);
  couponList = couponList
    .reduce((result, item) => {
      const sortItem = SortMap[item.couponActivityType];
      // couponActivityType只处理10、9、2、20，按照这个顺序排序
      if (sortItem?.sortKey) {
        item['title'] = sortItem.title;
        item['popTitle'] = sortItem.popTitle || sortItem.title;
        item['sortKey'] = sortItem.sortKey;
        item['descObj'] = sortItem.descObj(item, sortItem.title, calcFeeInfo);
        item['orangeType'] = sortItem.isVisibleIcon(item);
        // 活动类型给后端传值的时候使用
        item['targetActivityType'] = sortItem.targetActivityType;
        item['targetKeys'] = sortItem.keys;
        // 选中的券或者活动的id集合
        item['targetActivityUseIds'] = sortItem.keys.reduce((result, item) => {
          if (activityMap[item] && activityMap[item].length > 0) {
            result.push(...activityMap[item]);
          }
          return result;
        }, []);

        let isVisibleIcon = sortItem.isVisibleIcon(item, calcFeeInfo);
        // 没有收货地址的时候，默认展示已免邮
        if (item.couponActivityType === 2 && !addrReceiverInfo?.addrReceiverId) {
          isVisibleIcon = false;
        }

        item['isVisibleIcon'] = isVisibleIcon;
        result.push(item);
      } else {
        result.push(item);
      }
      return result;
    }, [])
    .sort((a, b) => (a.sortKey > b.sortKey ? 1 : -1));
  console.log('jhb couponList', couponList);
  return couponList;
};
// 将所有的活动转为map
export const handlerCouponActivityInfoToMap = couponList => {
  return couponList.reduce((result, item) => {
    if (item?.couponActivityUseId) {
      if (result[item.couponActivityType]?.length) {
        result[item.couponActivityType].push(item.couponActivityUseId);
      } else {
        result[item.couponActivityType] = [item.couponActivityUseId];
      }
    }
    return result;
  }, {});
};
// 9或者10为聚合信息,不作为用户选过的活动，直接过滤掉
export const handlerSelectActivityInfo = couponList => {
  return couponList.reduce((result, item) => {
    const { couponActivityType, couponActivityUseId = '' } = item;

    if (![COMB_ACTIVITY].includes(item.couponActivityType) && couponActivityUseId) {
      result.push({
        couponActivityType,
        couponActivityUseId
      });
    }
    return result;
  }, []);
};

function formalDesc(item, title) {
  let desc = '暂无可使用优惠';
  let className = 'free-ship';
  if (item.hasCouponActivity === HAS_DISCOUNT) {
    className = 'has-coupon';
    // 有折扣信息
    if (item.couponActivityAmt) {
      desc = `-¥${(+item.couponActivityAmt).toFixed(2)}`;
      className = 'fee-statistic__bold';
    } else {
      desc = `选择可用${title}`;
    }
  }
  //'has-coupon fee-statistic__bold' : 'free-ship'
  return {
    desc,
    className
  };
}
// 差异化自己磨平
const SortMap = {
  10: {
    sortKey: 1,
    title: '活动优惠',
    popTitle: '活动优惠',
    isVisibleIcon: item => {
      return [HAS_DISCOUNT].includes(item.hasCouponActivity);
    },
    descObj: formalDesc,
    targetActivityType: 4,
    keys: [4]
  },
  9: {
    sortKey: 2,
    title: '优惠券',
    popTitle: '选择优惠券',
    isVisibleIcon: item => {
      return [INVALID_DISCOUNT, HAS_DISCOUNT].includes(item.hasCouponActivity);
    },
    descObj: formalDesc,
    targetActivityType: 9,
    keys: [1, 3]
  },
  2: {
    sortKey: 3,
    title: '运费优惠', // 运费优惠券
    popTitle: '选择优惠券',
    isVisibleIcon: (item, calcFeeInfo) => {
      return (
        !checkEqualZero(calcFeeInfo?.totalFreightFee) && item.hasCouponActivity === HAS_DISCOUNT
      );
    },
    descObj: (item, title, calcFeeInfo) => {
      if (checkEqualZero(calcFeeInfo.totalFreightFee) && item.hasCouponActivity === HAS_DISCOUNT) {
        return {
          desc: '已免邮',
          className: 'free-ship'
        };
      } else {
        return formalDesc(item, title, calcFeeInfo);
      }
    },
    targetActivityType: 2,
    keys: [2]
  },
  20: {
    sortKey: 4,
    title: '礼品卡',
    popTitle: '选择礼品券',
    isVisibleIcon: item => {
      return [HAS_DISCOUNT].includes(item.hasCouponActivity);
    },
    descObj: (item, title, calcFeeInfo) => {
      if (checkEqualZero(item.couponActivityAmt)) {
        return {
          desc: '已抵扣￥0.00',
          className: ''
        };
      } else {
        if (item?.couponActivityAmt) {
          return {
            desc: `已抵扣￥${item.couponActivityAmt}`,
            className: ''
          };
        } else {
          return formalDesc(item, title, calcFeeInfo);
        }
      }
    },
    targetActivityType: 20,
    keys: [20]
  }
};

// 优惠选择列表接口数据适配
/**
 * 优惠选择列表接口数据适配
 * @param data
 * @param couponType 优惠券类型
 * @param selectIds 选中的优惠券id
 * @returns {*}
 */
export const handlerSelectApi = (data, couponType, selectIds = []) => {
  let res = data.reduce((result, item) => {
    const couponActivityUseId = item?.pickupId || item?.activityId || item?.id; // id 礼品卡 pickupId 优惠券 activityId 活动
    result.push({
      couponActivityType: item?.couponActivityType || item?.couponCategory || couponType, // 礼品卡没有类型，需要补充
      ...item,
      //  补充业务属性
      couponActivityUseId,
      overlying: false, // 是否可叠加
      isSelect: selectIds.includes(couponActivityUseId) // 是否选中
    });
    return result;
  }, []);
  // 券的组合活动选中状态处理逻辑特殊，为了实现逻辑复用，这里进行二次循环
  if (couponType === 9 && selectIds.length === 1) {
    const stackableCouponIds = res.find(item => item.isSelect)?.stackableCouponIds || [];
    res.forEach(item => {
      // 添加叠加标签
      if (stackableCouponIds.includes(item.couponActivityUseId)) {
        item.overlying = true;
      }
    });
  }

  return res;
};
