package com.kym.service.awoara.entity.event.handle;

import com.kym.entity.miniapp.Account;
import com.kym.entity.miniapp.WalletDetail;
import com.kym.entity.miniapp.WashOrder;
import com.kym.service.awoara.entity.event.MessageBody;
import com.kym.service.awoara.entity.event.OrderInfoObject;
import com.kym.service.miniapp.AccountService;
import com.kym.service.miniapp.WalletDetailService;
import com.kym.service.miniapp.WashOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * 关闭订单事件（订单结算）
 *
 * @author skyline
 */
@Slf4j
@Component
public class OrderCloseEventHandler implements AwoaraEventHandler<OrderInfoObject> {
    private final WashOrderService washOrderService;
    private final WalletDetailService walletDetailService;
    private final AccountService accountService;

    public OrderCloseEventHandler(WashOrderService washOrderService, WalletDetailService walletDetailService, AccountService accountService) {
        this.washOrderService = washOrderService;
        this.walletDetailService = walletDetailService;
        this.accountService = accountService;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void handle(MessageBody<OrderInfoObject> message) {
        log.info("收到订单关闭事件");

        // 订单结算
        var orderInfo = message.getPayload().getData().getOrder_info();
        log.info("订单：{}，结算信息：{}", orderInfo.getOrder_id(), orderInfo);

        // 订单状态、支付状态
        var washOrder = washOrderService.lambdaQuery()
                .eq(WashOrder::getOrderId, orderInfo.getOrder_id())
//                .eq(WashOrder::getOrderIdLocal, orderInfo.getOrder_id_local())
                .one();
        washOrder.setAmount(orderInfo.getAmount())
                .setAmountReceivable(orderInfo.getAmount_receivable())
                .setAmountReceived(orderInfo.getAmount_received())
                .setAmountReceived(orderInfo.getAmount_received())
                .setDiscountMoney(orderInfo.getDiscount_money())
                .setDetail(orderInfo.getDetail().toString())
                .setEndTime(LocalDateTime.now())
                .setOrderStatus(WashOrder.ORDER_STATUS_成功)
                .setPayStatus(WashOrder.PAY_STATUS_已支付)
                .setStopReason(orderInfo.getClose_type());
        washOrderService.updateById(washOrder);

        // 扣款更新余额，新增资金流水 TODO 【存在优惠情况下校验优惠，更新优惠使用情况等】
        var account = accountService.getAccountByUserId(washOrder.getUserId());
        accountService.lambdaUpdate().setSql("balance=balance-{0}", orderInfo.getAmount())
                .eq(Account::getUserId, washOrder.getUserId()).update();

        var walletDetail = new WalletDetail();
        walletDetail.setUserId(washOrder.getUserId());
        walletDetail.setType(WalletDetail.TYPE_消费);
        walletDetail.setOrderNo(washOrder.getOrderId());
        walletDetail.setAmount(orderInfo.getAmount());
        walletDetail.setBeforeBalance(account.getBalance());
        walletDetail.setAfterBalance(account.getBalance() - orderInfo.getAmount());
        walletDetail.setTransactionId(washOrder.getId().toString());
        walletDetail.setTransactionTime(LocalDateTime.now());
        walletDetail.setStatus(WalletDetail.STATUS_已确认);
        walletDetailService.save(walletDetail);

    }
}
