package com.czg.service.market.service.impl;

import com.czg.market.dto.SmsMoneyDetailDto;
import com.czg.market.dto.SmsShopMoneyDetailDTO;
import com.czg.market.entity.SmsShopMoneyDetail;
import com.czg.market.service.SmsShopMoneyDetailService;
import com.czg.service.market.mapper.SmsShopMoneyDetailMapper;
import com.czg.utils.CzgStrUtils;
import com.czg.utils.PageUtil;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

/**
 * 短信余额明细 服务层实现。
 *
 * @author ww
 * @since 2025-10-16
 */
@Service
public class SmsShopMoneyDetailServiceImpl extends ServiceImpl<SmsShopMoneyDetailMapper, SmsShopMoneyDetail> implements SmsShopMoneyDetailService {

    @Override
    public Page<SmsShopMoneyDetailDTO> getSmsMoneyDetailPage(Long shopId) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(SmsShopMoneyDetail::getShopId, shopId)
                .eq(SmsShopMoneyDetail::getIsDel, 0)
                .orderBy(SmsShopMoneyDetail::getCreateTime).desc();
        return pageAs(PageUtil.buildPage(), queryWrapper, SmsShopMoneyDetailDTO.class);
    }

    @Override
    public Page<SmsShopMoneyDetailDTO> getSmsMoneyDetail2(SmsMoneyDetailDto param) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(SmsShopMoneyDetail::getShopId, param.getShopId())
                .eq(SmsShopMoneyDetail::getIsDel, 0)
                .ge(SmsShopMoneyDetail::getCreateTime, CzgStrUtils.getStrOrNull(param.getStartTime()))
                .le(SmsShopMoneyDetail::getCreateTime, CzgStrUtils.getStrOrNull(param.getEndTime()))
                .eq(SmsShopMoneyDetail::getType, param.getType())
                .orderBy(SmsShopMoneyDetail::getCreateTime).desc();
        return pageAs(PageUtil.buildPage(), queryWrapper, SmsShopMoneyDetailDTO.class);
    }

    @Override
    public Long countSendTotal(Long shopId) {
        QueryWrapper queryWrapper = new QueryWrapper()
                .eq(SmsShopMoneyDetail::getShopId, shopId)
                .gt(SmsShopMoneyDetail::getSendRows, 0)
                .eq(SmsShopMoneyDetail::getType, 2)
                .eq(SmsShopMoneyDetail::getIsDel, 0);
        return count(queryWrapper);
    }

    @Override
    public BigDecimal countSendAmountTotal(Long shopId) {
        QueryWrapper queryWrapper = new QueryWrapper()
                .select("sum(expense)")
                .eq(SmsShopMoneyDetail::getShopId, shopId)
                .gt(SmsShopMoneyDetail::getSendRows, 0)
                .eq(SmsShopMoneyDetail::getType, 2)
                .eq(SmsShopMoneyDetail::getIsDel, 0);
        return getOneAs(queryWrapper, BigDecimal.class);
    }
}
