package edu.whut.domain.trade.service.refund;

import edu.whut.domain.activity.model.entity.UserGroupBuyOrderDetailEntity;
import edu.whut.domain.trade.adapter.repository.ITradeRepository;
import edu.whut.domain.trade.model.entity.*;
import edu.whut.domain.trade.model.valobj.RefundTypeEnumVO;
import edu.whut.domain.trade.model.valobj.TeamRefundSuccess;
import edu.whut.domain.trade.model.valobj.TradeOrderStatusEnumVO;
import edu.whut.domain.trade.service.ITradeRefundOrderService;
import edu.whut.domain.trade.service.refund.business.IRefundOrderStrategy;
import edu.whut.domain.trade.service.refund.factory.TradeRefundRuleFilterFactory;
import edu.whut.types.design.framework.link.model2.chain.BusinessLinkedList;
import edu.whut.types.enums.GroupBuyOrderStatusEnumVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * 退单，逆向流程服务
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class TradeRefundOrderService implements ITradeRefundOrderService {

    //注入策略Map
    private final Map<String, IRefundOrderStrategy> refundOrderStrategyMap;

    private final BusinessLinkedList<TradeRefundCommandEntity, TradeRefundRuleFilterFactory.DynamicContext, TradeRefundBehaviorEntity> tradeRefundRuleFilter;

    private final ITradeRepository repository;


    /**
     * 用户点击退单主动触发=》更新数据库操（锁单量、完成量、退款、拼团状态、订单状态...）
     */
    @Override
    public TradeRefundBehaviorEntity refundOrder(TradeRefundCommandEntity tradeRefundCommandEntity) throws Exception {
        log.info("逆向流程，退单操作 userId:{} outTradeNo:{}", tradeRefundCommandEntity.getUserId(), tradeRefundCommandEntity.getOutTradeNo());
        return tradeRefundRuleFilter.apply(tradeRefundCommandEntity, new TradeRefundRuleFilterFactory.DynamicContext());
    }

    /**
     * 退单成功后，消息监听触发-》恢复锁单量
     */
    @Override
    public void restoreTeamLockStock(TeamRefundSuccess teamRefundSuccess) throws Exception {
        log.info("逆向流程，恢复锁单量 userId:{} activityId:{} teamId:{}", teamRefundSuccess.getUserId(), teamRefundSuccess.getActivityId(), teamRefundSuccess.getTeamId());
        String type = teamRefundSuccess.getType();

        // 根据枚举值获取对应的退单类型
        RefundTypeEnumVO refundTypeEnumVO = RefundTypeEnumVO.getRefundTypeEnumVOByCode(type);
        IRefundOrderStrategy refundOrderStrategy = refundOrderStrategyMap.get(refundTypeEnumVO.getStrategy());

        // 逆向库存操作，恢复锁单量
        refundOrderStrategy.reverseStock(teamRefundSuccess);
    }

    /**
     * 扫描数据，超时组队未支付订单
     */
    @Override
    public List<UserGroupBuyOrderDetailEntity> queryTimeoutUnpaidOrderList() {
        log.info("扫描数据，超时组队未支付订单");
        return repository.queryTimeoutUnpaidOrderList();
    }

}
