package com.jeesharp.business.modules.finance.payorder.service.impl;

import cn.hutool.core.util.StrUtil;
import com.jeesharp.business.modules.finance.payorder.entity.PayOrder;
import com.jeesharp.business.modules.finance.payorder.mapper.PayOrderMapper;
import com.jeesharp.business.modules.finance.payorder.service.PayOrderService;
import com.jeesharp.business.modules.finance.payorder.vo.PayOrderQueryVO;
import com.jeesharp.framework.mybatis.core.service.CrudService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 支付单领域服务实现，继承 {@link CrudService} 并提供按 out_trade_no 查询等能力。
 *
 * @author jeesharp
 * @since 2026-05-08
 */
@Service
@Transactional(readOnly = true)
public class PayOrderServiceImpl extends CrudService<PayOrderMapper, PayOrder, PayOrderQueryVO> implements PayOrderService {

    @Override
    public PayOrder getByOutTradeNo(String outTradeNo) {
        PayOrderQueryVO q = new PayOrderQueryVO();
        q.setOutTradeNo(outTradeNo);
        List<PayOrder> list = findList(q);
        return list == null || list.isEmpty() ? null : list.get(0);
    }

    @Override
    @Transactional(readOnly = false)
    public void closePendingByBiz(String bizOrderId, String bizScene) {
        getBaseMapper().closePendingByBiz(bizOrderId, bizScene);
    }

    @Override
    public PayOrder findLatestPendingForBiz(String bizOrderId, String bizScene) {
        return getBaseMapper().findLatestPendingForBiz(bizOrderId, bizScene);
    }

    @Override
    public PayOrder findLatestSuccessByBiz(String bizOrderId, String bizScene) {
        return getBaseMapper().findLatestSuccessByBiz(bizOrderId, bizScene);
    }

    @Override
    public PayOrder getByCombineOutTradeNo(String combineOutTradeNo) {
        if (StrUtil.isBlank(combineOutTradeNo)) {
            return null;
        }
        return getBaseMapper().getByCombineOutTradeNo(combineOutTradeNo.trim());
    }

    @Override
    public List<PayOrder> findPendingListByBiz(String bizOrderId, String bizScene) {
        return getBaseMapper().findPendingListByBiz(bizOrderId, bizScene);
    }

    @Override
    @Transactional(readOnly = false)
    public void insertPayOrder(PayOrder entity) {
        if (StrUtil.isNotBlank(entity.getId())) {
            entity.setIsNewRecord(true);
        }
        entity.preInsert();
        if (StrUtil.isBlank(entity.getDelFlag())) {
            entity.setDelFlag("0");
        }
        getBaseMapper().insert(entity);
    }
}
