package com.seer.teach.pay.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.seer.teach.common.enums.pay.PayStatusEnum;
import com.seer.teach.common.utils.MoneyUtil;
import com.seer.teach.common.utils.OrderIdGenerator;
import com.seer.teach.pay.entity.CoinConfigEntity;
import com.seer.teach.pay.entity.PayOrderEntity;
import com.seer.teach.pay.mapper.PayOrderMapper;
import com.seer.teach.pay.service.ICoinConfigService;
import com.seer.teach.pay.service.IPayOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Objects;

/**
 * <p>
 * 支付订单 服务实现类
 * </p>
 *
 * @author Wang
 * @since 2025-09-11 14:04:02
 */
@Slf4j
@Service
public class PayOrderServiceImpl extends ServiceImpl<PayOrderMapper, PayOrderEntity> implements IPayOrderService {


    @Autowired
    private ICoinConfigService coinConfigService;

    @Override
    public Integer createOrder(PayOrderEntity payOrder) {
        log.info("开始创建支付订单，创建参数: {}", payOrder);

        PayOrderEntity order = getOrderByMerchantOrderSn(payOrder.getMerchantOrderSn());
        if (Objects.nonNull(order)) {
            log.info("订单[{}]已存在", payOrder.getMerchantOrderSn());
            return order.getId();
        }
        payOrder.setStatus(PayStatusEnum.PENDING.getCode());
        payOrder.setOrderSn(OrderIdGenerator.generateOrderId(OrderIdGenerator.PAY_ORDER_PREFIX));

        CoinConfigEntity coinConfig = coinConfigService.getActiveAndLatestCoinConfig();
        payOrder.setCoinConfigId(coinConfig.getId());
        payOrder.setExchangeRatio(coinConfig.getExchangeRatio());
        log.info("准备保存支付订单，channelId: {}, channelCode: {}", payOrder.getChannelId(), payOrder.getChannelCode());
        boolean saved = super.save(payOrder);
        log.info("保存订单结果：{}", saved);
        return payOrder.getId();
    }

    @Override
    public PayOrderEntity getOrderByMerchantOrderSn(String merchantOrderSn) {
        return super.getOne(new LambdaQueryWrapper<>(PayOrderEntity.class).eq(PayOrderEntity::getMerchantOrderSn, merchantOrderSn));
    }

    @Override
    public PayOrderEntity getOrderByOrderSn(String orderSn) {
        return super.getOne(new LambdaQueryWrapper<>(PayOrderEntity.class).eq(PayOrderEntity::getOrderSn, orderSn));
    }

}