package com.ruoyi.bst.order.service.impl;

import com.ruoyi.bst.bonus.domain.enums.BonusBstType;
import com.ruoyi.bst.changeRecord.domain.ChangeRecord;
import com.ruoyi.bst.lightingNum.domain.LightingNum;
import com.ruoyi.bst.order.domain.Order;
import com.ruoyi.bst.order.domain.OrderQuery;
import com.ruoyi.bst.order.domain.OrderVO;
import com.ruoyi.bst.order.domain.enums.OrderStatus;
import com.ruoyi.bst.order.mapper.OrderMapper;
import com.ruoyi.bst.order.service.OrderService;
import com.ruoyi.bst.pay.domain.PayVO;
import com.ruoyi.bst.pay.domain.enums.PayBstType;
import com.ruoyi.bst.pay.interfaces.PayHandler;
import com.ruoyi.bst.refund.domain.RefundVO;
import com.ruoyi.common.utils.ServiceUtil;
import com.ruoyi.system.user.service.UserService;
import org.geotools.data.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

import java.time.LocalDateTime;

@Service
public class OrderPayHandler implements PayHandler {

    @Autowired
    private OrderService orderService;
    @Autowired
    private TransactionTemplate transactionTemplate;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserService userService;

    @Override
    public boolean onPaySuccess(PayVO pay) {

        ServiceUtil.assertion(pay == null, "支付信息不能为空");
        ServiceUtil.assertion(pay.getBstId() == null, "订单ID不能为空");
        ServiceUtil.assertion(!PayBstType.ORDER.getType().equals(pay.getBstType()), "订单支付类型错误");

        // 查询订单
        OrderVO order = orderService.selectOrderById(pay.getBstId());
        ServiceUtil.assertion(order == null, "ID为%s的订单不存在", pay.getBstId());

        Integer result = transactionTemplate.execute(status -> {
            // 修改订单状态
            Order data = new Order();
            data.setStatus(OrderStatus.FINISHED.getCode());
            data.setPayId(pay.getId());
            OrderQuery query = new OrderQuery();
            query.setId(order.getId());
            query.setStatusList(OrderStatus.canPaySuccess());
            int rows = orderMapper.updateByQuery(data, query);
            ServiceUtil.assertion(rows != 1, "更新ID为%s的订单失败", order.getId());
            // 增加用户爆灯次数(余额)
            userService.addLightingNum(order);
            return rows;
        });
        return result != null && result == 1;
    }

}
