package com.fdkankan.platform.user.strategy.impl;

import com.fdkankan.platform.order.entity.Order;
import com.fdkankan.platform.order.service.IOrderItemService;
import com.fdkankan.platform.order.service.IOrderService;
import com.fdkankan.platform.user.strategy.OrderStrategy;
import com.fdkankan.platform.user.strategy.OrderStrategyFactory;
import com.fdkankan.platform.user.vo.ResponseOrderItem;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Log4j2
@Component
public class EntityOrderImpl implements OrderStrategy {
    @Autowired
    private IOrderService orderService;
    @Autowired
    private OrderStrategyFactory orderStrategyFactory;
    @Autowired
    private IOrderItemService orderItemService;

    @Override
    public void handleOrder(String orderSn, String tradeNo, String openId, int paymentTypeName, Long spaceId) throws Exception {
        log.warn("购物支付处理....");
        Order orderEntity = orderService.getByOrderSn(orderSn);
        if (orderEntity == null) {
            log.error("找不到订单：" + orderSn);
            throw new Exception("找不到订单，out_trade_no错误");
        }
        boolean result = orderService.paySuccessEntityOrder(orderSn, tradeNo, paymentTypeName);
        if (!result){
            log.error("更新订单失败");
            throw new Exception("更新订单失败");
        }

        List<ResponseOrderItem> responseOrderItems = orderItemService.getByOrderId(orderEntity.getId());
        for (ResponseOrderItem orderItem : responseOrderItems){
            orderItem.setOpenid(openId);
            log.warn("orderStrategyFactory："+orderStrategyFactory);
            orderStrategyFactory.doHandler(orderEntity.getUserId(), orderItem);
        }
    }

    @Override
    public String getType() {
        return "entity";
    }
}
