package com.jeesharp.business.modules.mall.service.impl;

import cn.hutool.core.util.StrUtil;
import com.jeesharp.business.modules.mall.entity.MallPayBatch;
import com.jeesharp.business.modules.mall.enums.MallPayBatchStatusEnum;
import com.jeesharp.business.modules.mall.mapper.MallPayBatchMapper;
import com.jeesharp.business.modules.mall.service.MallPayBatchService;
import com.jeesharp.business.modules.mall.vo.MallPayBatchQueryVO;
import com.jeesharp.framework.exception.BizErrorException;
import com.jeesharp.framework.mybatis.core.service.CrudService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 商城合并支付批次领域服务实现。
 *
 * @author jeesharp
 * @since 2026-06-10
 */
@Service
@Transactional(readOnly = true)
public class MallPayBatchServiceImpl extends CrudService<MallPayBatchMapper, MallPayBatch, MallPayBatchQueryVO>
        implements MallPayBatchService {

    @Override
    @Transactional(readOnly = false)
    public MallPayBatch createPayBatch(MallPayBatch batch) {
        if (StrUtil.isNotBlank(batch.getId())) {
            throw new BizErrorException("新增支付批次不应预置主键");
        }
        if (batch.getStatus() == null) {
            batch.setStatus(MallPayBatchStatusEnum.PENDING_PAY.getCode());
        }
        getBaseMapper().insert(batch);
        return batch;
    }

    @Override
    @Transactional(readOnly = false)
    public void updatePayBatch(MallPayBatch batch) {
        if (StrUtil.isBlank(batch.getId())) {
            throw new BizErrorException("更新支付批次主键不能为空");
        }
        if (get(batch.getId()) == null) {
            throw new BizErrorException("支付批次不存在");
        }
        getBaseMapper().update(batch);
    }

    @Override
    public void assertPayPreparable(MallPayBatch batch, String memberId) {
        if (batch == null) {
            throw new BizErrorException("订单不存在");
        }
        if (!memberId.equals(batch.getMemberId())) {
            throw new BizErrorException("无权操作该订单");
        }
        if (!MallPayBatchStatusEnum.PENDING_PAY.getCode().equals(batch.getStatus())) {
            throw new BizErrorException("当前状态不可发起支付");
        }
    }

    @Override
    @Transactional(readOnly = false)
    public void markPayPreparing(MallPayBatch batch, String payChannel) {
        batch.setPayType(payChannel);
        updatePayBatch(batch);
    }
}
