package com.ruoyi.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.system.domain.PosOrderPayment;
import com.ruoyi.system.mapper.PosOrderPaymentMapper;
import com.ruoyi.system.service.IPosOrderPaymentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * 蓝新支付交易流水 Service 实现。
 *
 * @author ruoyi
 * @date 2026-06-22
 */
@Service
public class PosOrderPaymentServiceImpl implements IPosOrderPaymentService {

    @Autowired
    private PosOrderPaymentMapper posOrderPaymentMapper;

    private static final int PAY_STATUS_UNPAID = 0;
    private static final int PAY_STATUS_SUCCESS = 1;
    private static final int PAY_STATUS_FAIL = 2;

    @Override
    public int createPayment(String ddId, String merchantOrderNo, Long storeId, String merchantId, Integer amount) {
        PosOrderPayment exist = getByMerchantOrderNo(merchantOrderNo);
        Date now = new Date();
        if (exist != null) {
            // 重新发起：更新金额/门店（保留 id），pay_status 重置为未支付
            exist.setDdId(ddId);
            exist.setStoreId(storeId);
            exist.setMerchantId(merchantId);
            exist.setAmount(amount);
            exist.setPayStatus(PAY_STATUS_UNPAID);
            exist.setUpdateTime(now);
            return posOrderPaymentMapper.updateById(exist);
        }
        PosOrderPayment p = new PosOrderPayment();
        p.setDdId(ddId);
        p.setMerchantOrderNo(merchantOrderNo);
        p.setStoreId(storeId);
        p.setMerchantId(merchantId);
        p.setAmount(amount);
        p.setPayStatus(PAY_STATUS_UNPAID);
        p.setCreateTime(now);
        p.setUpdateTime(now);
        return posOrderPaymentMapper.insert(p);
    }

    @Override
    public PosOrderPayment getByTradeNo(String tradeNo) {
        if (tradeNo == null || tradeNo.isEmpty()) {
            return null;
        }
        return posOrderPaymentMapper.selectOne(
                new LambdaQueryWrapper<PosOrderPayment>().eq(PosOrderPayment::getTradeNo, tradeNo));
    }

    @Override
    public PosOrderPayment getByMerchantOrderNo(String merchantOrderNo) {
        if (merchantOrderNo == null || merchantOrderNo.isEmpty()) {
            return null;
        }
        return posOrderPaymentMapper.selectOne(
                new LambdaQueryWrapper<PosOrderPayment>().eq(PosOrderPayment::getMerchantOrderNo, merchantOrderNo));
    }

    @Override
    public PosOrderPayment getLatestByDdId(String ddId) {
        if (ddId == null || ddId.isEmpty()) {
            return null;
        }
        return posOrderPaymentMapper.selectOne(
                new LambdaQueryWrapper<PosOrderPayment>()
                        .eq(PosOrderPayment::getDdId, ddId)
                        .orderByDesc(PosOrderPayment::getId)
                        .last("LIMIT 1"));
    }

    @Override
    public int markSuccess(String ddId, String merchantOrderNo, Long storeId, String merchantId, Integer amount,
                            String tradeNo, String payType, String authCode, Date payTime, String callbackRaw) {
        // 幂等：同 tradeNo 已成功则跳过
        PosOrderPayment byTrade = getByTradeNo(tradeNo);
        if (byTrade != null && Integer.valueOf(PAY_STATUS_SUCCESS).equals(byTrade.getPayStatus())) {
            return 0;
        }
        PosOrderPayment row = byTrade != null ? byTrade : getByMerchantOrderNo(merchantOrderNo);
        boolean isNew = false;
        if (row == null) {
            row = new PosOrderPayment();
            isNew = true;
        }
        row.setDdId(ddId);
        row.setMerchantOrderNo(merchantOrderNo);
        row.setStoreId(storeId);
        row.setMerchantId(merchantId);
        row.setAmount(amount);
        row.setTradeNo(tradeNo);
        row.setPayType(payType);
        row.setAuthCode(authCode);
        row.setPayTime(payTime);
        row.setCallbackRaw(callbackRaw);
        row.setPayStatus(PAY_STATUS_SUCCESS);
        Date now = new Date();
        if (isNew) {
            row.setCreateTime(now);
            row.setUpdateTime(now);
            return posOrderPaymentMapper.insert(row);
        }
        row.setUpdateTime(now);
        return posOrderPaymentMapper.updateById(row);
    }

    @Override
    public int markFail(String merchantOrderNo, String tradeNo, String payType, String callbackRaw) {
        PosOrderPayment row = getByMerchantOrderNo(merchantOrderNo);
        if (row == null) {
            return 0; // 无发起记录，忽略
        }
        row.setTradeNo(tradeNo);
        row.setPayType(payType);
        row.setCallbackRaw(callbackRaw);
        row.setPayStatus(PAY_STATUS_FAIL);
        row.setUpdateTime(new Date());
        return posOrderPaymentMapper.updateById(row);
    }
}
