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

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fdkankan.platform.order.entity.DownloadOrder;
import com.fdkankan.platform.order.service.IDownloadOrderService;
import com.fdkankan.platform.user.entity.User;
import com.fdkankan.platform.user.service.IUserService;
import com.fdkankan.platform.user.strategy.OrderStrategy;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Log4j2
@Component
public class DownloadOrderImpl implements OrderStrategy {
    @Autowired
    private IDownloadOrderService downloadOrderService;
    @Autowired
    private IUserService userService;
    @Autowired
    private ObjectMapper mapper;

    @Override
    public void handleOrder(String orderSn, String tradeNo, String openId, int paymentTypeName, Long spaceId) throws Exception {
        DownloadOrder downloadOrder = downloadOrderService.getByOrderSn(orderSn);
        if (downloadOrder == null) {
            log.error("找不到订单：" + orderSn);
            throw new Exception("找不到订单，out_trade_no错误");
        }
        // 更新场景下载订单
        boolean result = downloadOrderService.paySuccessDownloadOrder(orderSn, tradeNo, paymentTypeName);
        if (!result){
            log.error("更新增值权益订单失败");
            throw new Exception("更新增值权益订单失败");
        }
        //更新用户下载次数
        User userEntity = userService.getById(downloadOrder.getUserId());
        userEntity.setDownloadNumTotal(userEntity.getDownloadNumTotal() + downloadOrder.getCount());
        userService.updateById(userEntity);
    }

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