package com.fdkankan.ucenter.pay.strategy.impl;

import com.fdkankan.ucenter.entity.Order;
import com.fdkankan.ucenter.entity.OrderItem;
import com.fdkankan.ucenter.pay.strategy.OrderStrategy;
import com.fdkankan.ucenter.pay.strategy.OrderStrategyFactory;
import com.fdkankan.ucenter.service.IOrderItemService;
import com.fdkankan.ucenter.service.IOrderService;
import com.fdkankan.ucenter.vo.response.OrderItemVo;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.BeanUtils;
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.getByOrderSnNoPay(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<OrderItem> byOrderId = orderItemService.getByOrderId(orderEntity.getId());
        for (OrderItem orderItem : byOrderId){
            OrderItemVo orderItemVo = new OrderItemVo();
            BeanUtils.copyProperties(orderItem,orderItemVo);
            orderItemVo.setOpenid(openId);
            log.warn("orderStrategyFactory："+orderStrategyFactory);
            orderStrategyFactory.doHandler(orderEntity.getUserId(), orderItemVo);
        }
    }

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