package com.ruoyi.school.member.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.page.RespPage;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.core.api.APIResponse;
import com.ruoyi.school.course.domain.ScBookCourse;
import com.ruoyi.school.course.domain.ScClaTime;
import com.ruoyi.school.course.domain.ScClaTimeAttend;
import com.ruoyi.school.course.domain.ScCourse;
import com.ruoyi.school.course.enums.ClaTimeStatusEnums;
import com.ruoyi.school.course.mapper.ScClaTimeMapper;
import com.ruoyi.school.course.mapper.ScCourseMapper;
import com.ruoyi.school.course.service.IScClaTimeAttendService;
import com.ruoyi.school.course.service.impl.ScBookCourseServiceImpl;
import com.ruoyi.school.member.domain.ScMemberCard;
import com.ruoyi.school.member.domain.ScMemberCardTypes;
import com.ruoyi.school.member.domain.ScStudent;
import com.ruoyi.school.member.domain.req.CreateMemberCardDTO;
import com.ruoyi.school.member.domain.resp.MemberCardDTO;
import com.ruoyi.school.member.domain.resp.MemberCardVO;
import com.ruoyi.school.member.mapper.ScMemberCardMapper;
import com.ruoyi.school.member.mapper.ScMemberCardTypesMapper;
import com.ruoyi.school.member.mapper.ScStudentMapper;
import com.ruoyi.school.member.service.IScMemberCardService;
import com.ruoyi.school.member.service.ScMemberCardCourseService;
import com.ruoyi.school.member.service.ScMemberCardTypesService;
import com.ruoyi.school.order.domain.ScOrder;
import com.ruoyi.school.order.service.IScOrderService;
import com.ruoyi.school.salary.domain.ScCommissionPlans;
import com.ruoyi.school.salary.service.ScCommissionPlansService;
import com.ruoyi.system.domain.columns.SysTeacher;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.system.service.columns.ISysTeacherService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 会员卡服务实现类
 */
@Slf4j
@Service
public class ScMemberCardServiceImpl extends ServiceImpl<ScMemberCardMapper, ScMemberCard> implements IScMemberCardService {

    @Resource
    private ScMemberCardMapper memberCardMapper;

    @Resource
    private ScStudentMapper memberMapper;

    @Resource
    private ScMemberCardTypesMapper cardTypeMapper;

    @Resource
    private ScMemberCardTypesService cardTypesService;
    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private ScCommissionPlansService commissionPlansService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private IScOrderService scOrderService;

    @Autowired
    private ScMemberCardCourseService cardCoursesService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public MemberCardDTO createMemberCard(CreateMemberCardDTO dto) {

//        if (!dto.getChargeType().equals("total_fee")&&dto.getCardTypeId()==null){
        if (dto.getCardTypeId()==null){
            throw new RuntimeException("未选择卡类型");
        }

        ScMemberCardTypes cardType =new ScMemberCardTypes();

        if (dto.getCardTypeId()!=null){
            // 验证卡类型是否存在
             cardType = cardTypeMapper.selectById(dto.getCardTypeId());
            if (cardType == null) {
                throw new RuntimeException("卡类型不存在");
            }
        }

        // 验证会员是否存在
        ScStudent member = memberMapper.selectById(dto.getMemberId());
        if (member == null) {
            throw new RuntimeException("会员不存在");
        }

        SysDept handleDept = deptService.getById(dto.getHandleDepartId());
        if (null == handleDept) {
            throw new RuntimeException("无法获取经办校区信息,请重试!");
        }

        SysUser staff=userService.selectUserById(dto.getSaleStaffId());
        if (null == staff) {
            throw new RuntimeException("无法获取经办人信息,请重试!");
        }

        ScCommissionPlans commissionPlans= commissionPlansService.getById(dto.getCommissionPlansId());
        if (null == commissionPlans) {
            throw new RuntimeException("无法获取佣金信息,请重试!");
        }

        // 创建会员卡
        ScMemberCard card = new ScMemberCard();
        BeanUtils.copyProperties(dto, card);
        card.setTenantId(SecurityUtils.getLoginUser().getNowTenantId());

        // 设置卡号（如果未提供则自动生成）
        if (card.getCardNo() == null || card.getCardNo().isEmpty()) {
            card.setCardNo(generateCardNo());
        }

        // 设置初始状态
        if (dto.getActivationDate() != null) {
            card.setStatus(ScMemberCard.CardStatus.ACTIVE.name());
            card.setActivationDate(dto.getActivationDate());
        } else {
            card.setStatus(ScMemberCard.CardStatus.INACTIVE.name());
        }

        if (dto.getChargeType().equals("count")){
            card.setRemainingCount(card.getTotalCount());
            if (BigDecimal.ZERO.equals(card.getPrice())||BigDecimal.ZERO.equals(card.getTotalCount())){
                card.setCountFee(new BigDecimal(0));
            }else {
                card.setCountFee(card.getPrice().divide(card.getTotalCount(),2, RoundingMode.HALF_UP));
            }

        }

        if (dto.getChargeType().equals("total_fee")){
            card.setRemainingTotalFee(card.getTotalFee());

        }

        if (dto.getChargeType().equals("days")){
            if (BigDecimal.ZERO.equals(card.getPrice()) || BigDecimal.ZERO.equals(card.getTotalDays())) {
                card.setDayFee(new BigDecimal(0));
            }else {
                card.setDayFee(card.getPrice().divide(new BigDecimal(card.getTotalDays()),2, RoundingMode.HALF_UP));
            }
        }
        // 设置默认到期日期（根据卡类型）
//        if (card.getExpiryDate() == null && cardType.getValidDays() != null) {
//            LocalDate activationDate = card.getActivationDate() != null ?
//                    card.getActivationDate() : LocalDate.now();
//            card.setExpiryDate(activationDate.plusDays(cardType.getValidDays()));
//        }

        // 设置购买时间
        card.setPurchaseDate(LocalDateTime.now());
        card.setCreatedAt(LocalDateTime.now());
        // 保存到数据库
       boolean flag= this.save(card);

        if (flag){
            ScOrder scOrder =new ScOrder();
            scOrder.setTenantId(SecurityUtils.getLoginUser().getNowTenantId());
            scOrder.setCommissionPlansId(dto.getCommissionPlansId());
            scOrder.setStudentId(dto.getMemberId());
            scOrder.setStudentName(member.getStudentName());
            scOrder.setPhone(member.getPhone());
            scOrder.setOriginalTotalFee(ObjectUtil.isEmpty(cardType.getTotalFee())?new BigDecimal(0):cardType.getTotalFee());
            scOrder.setReceiptFee(dto.getPrice());
            scOrder.setSaleStaffId(staff.getUserId());
            scOrder.setSaleStaffName(staff.getNickName());
            scOrder.setOrderStatus("2");
            scOrder.setHandleDeptId(handleDept.getDeptId());
            scOrder.setHandleDeptName(handleDept.getDeptName());
            scOrder.setAccountId(dto.getAccountId());
            scOrder.setCardNo(card.getCardNo());
            scOrder.setCreateUser(SecurityUtils.getUserId());
            scOrderService.save(scOrder);
        }

        // 转换为DTO返回
        return convertToDTO(card);
    }

    @Override
    public MemberCardVO getByCardNo(String cardNo) {
        ScMemberCard card = this.lambdaQuery()
                .eq(ScMemberCard::getCardNo, cardNo)
                .eq(ScMemberCard::getIsDeleted, 0)
                .one();

        if (card == null) {
            throw new RuntimeException("会员卡不存在");
        }

        return convertToVO(card);
    }

    @Autowired
    private ScBookCourseServiceImpl bookCourseService;
    @Autowired
    private IScMemberCardService memberCardService;
    @Autowired
    private ScClaTimeMapper claTimeMapper;
    @Autowired
    private ScCourseMapper courseMapper;
    @Autowired
    private IScClaTimeAttendService attendService;
    @Autowired
    private ISysTeacherService staffService;

    /**
     * 批量签到
     * @param bookIds
     * @return
     */
    @Override
    @Transactional
    public APIResponse checkInByIds(List<Long> bookIds) {
        //预约
        List<ScBookCourse> bookList= bookCourseService.listByIds(bookIds);
        Long courseTimeId = bookList.get(0).getCourseTimeId();
        // 排课信息
        ScClaTime claTime= claTimeMapper.selectById(courseTimeId);
        if (!ClaTimeStatusEnums.WAIT_CLASS.getStatus().equals(claTime.getStatus())) {
            return APIResponse.toExceptionResponse("课程非 待上课 状态,无法签到!");
        }
        //课程信息
        Long courseId = claTime.getCourseId();
        ScCourse scCourse = courseMapper.selectById(courseId);
        if (null == scCourse) {
            return APIResponse.toExceptionResponse("无法获取课程信息,请稍后重试");
        }
        Long departId = claTime.getDeptId();
        SysDept sysDept = deptService.getById(departId);
        if (null == sysDept) {
            return APIResponse.toExceptionResponse("无法获取校区信息,请稍后重试");
        }
        Long  teacherId = claTime.getTeacherId();
        SysTeacher sysStaff=staffService.selectSysTeacherByUserId(teacherId);

        List<ScBookCourse> bookCourseList = new ArrayList<>();
        List<ScMemberCard> memberCardList = new ArrayList<>();
        List<ScClaTimeAttend> attendList = new ArrayList<>();

        for (ScBookCourse bookCourse : bookList) {
            //判断预约状态
            //预约状态:0->预约中；1->教练确认；2->店长确认/预约成功/待上课 3->已取消;4- >已完成/待评价;5- >预约失败；
            if (StrUtil.containsAny("3,4,5",bookCourse.getBookStatus()+"")){
                return APIResponse.toExceptionResponse("请检查会员预约状态！");
            }

            ScMemberCard memberCard=memberCardService.getOne(new QueryWrapper<ScMemberCard>()
                    .eq("card_no",bookCourse.getCardNo())
                    .eq("is_deleted",0)
                    .last(" and expiry_date > CURDATE() ")
            );
            if (ObjectUtil.isEmpty(memberCard)){
                return APIResponse.toExceptionResponse(bookCourse.getCardNo()+"会员卡状态异常，请与教练核实!");
            }

            //预约时的扣费类型
            String chargeType=bookCourse.getChargeType();

            // 上课记出勤表
            ScClaTimeAttend addClaTimeAttend = new ScClaTimeAttend();


            if (chargeType.equals("count")){
                if (memberCard.getRemainingCount().compareTo(bookCourse.getDeductCnt())>-1){
                    addClaTimeAttend.setPayHour(bookCourse.getDeductCnt());
                    addClaTimeAttend.setCountBefore(memberCard.getRemainingCount());
                    addClaTimeAttend.setPayFee(memberCard.getCountFee().multiply(bookCourse.getDeductCnt()));
                    BigDecimal  countAfter= memberCard.getRemainingCount().subtract(bookCourse.getDeductCnt());
                    addClaTimeAttend.setCountAfter(countAfter);
                    memberCard.setRemainingCount(countAfter);
                }else {
                    return APIResponse.toExceptionResponse("会员卡剩余次数不足，请充值后重新预约！");
                }
            }

            if (chargeType.equals("total_fee")){
                if (memberCard.getRemainingTotalFee().compareTo(bookCourse.getDeductFee())>-1){
                    addClaTimeAttend.setPayFee(bookCourse.getDeductFee());
                    addClaTimeAttend.setFeeBefore(memberCard.getRemainingTotalFee());

                    BigDecimal feeAfter=memberCard.getRemainingTotalFee().subtract(bookCourse.getDeductFee());
                    addClaTimeAttend.setFeeAfter(feeAfter);
                    memberCard.setRemainingTotalFee(feeAfter);
                }else {
                    return APIResponse.toExceptionResponse("会员卡剩余金额不足，请充值后重新预约！");
                }
            }
//            if (chargeType.equals("days")){
//                addClaTimeAttend.setPayFee(memberCard.getDayFee());
//
//            }

            bookCourse.setUserId(SecurityUtils.getUserId());
            bookCourse.setCheckIn(1);
            bookCourse.setCheckInTime(new Date());


            //本节课 到课人数变更
            claTime.setRealAttendCnt(claTime.getRealAttendCnt()+1);
            //上课记录
            addClaTimeAttend.setBookId(bookCourse.getId());
            addClaTimeAttend.setMemberCardId(memberCard.getId());
            addClaTimeAttend.setCourseTimeId(courseTimeId);
            addClaTimeAttend.setStudentId(bookCourse.getStudentId());
            addClaTimeAttend.setClaId(claTime.getClaId());
            addClaTimeAttend.setCourseId(scCourse.getCourseId());
            addClaTimeAttend.setTeacherId(teacherId);
            addClaTimeAttend.setTeacherName(sysStaff.getTeacherName());
            addClaTimeAttend.setChargeType(chargeType);
            addClaTimeAttend.setAttendStatus("1");
            addClaTimeAttend.setCreateUser(SecurityUtils.getUserId());
            addClaTimeAttend.setTenantId(claTime.getTenantId());
            bookCourseList.add(bookCourse);
            memberCardList.add(memberCard);
            // 保存上课记录
            attendList.add(addClaTimeAttend);
        }

        bookCourseService.updateBatchById(bookCourseList);

        //会员卡余额变更
        memberCardService.updateBatchById(memberCardList);
        claTimeMapper.updateById(claTime);
        attendService.saveBatch(attendList);

        return APIResponse.toOkResponse();
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean activateCard(Long cardId) {
        LambdaUpdateWrapper<ScMemberCard> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(ScMemberCard::getId, cardId)
                .eq(ScMemberCard::getIsDeleted, 0)
                .set(ScMemberCard::getStatus, ScMemberCard.CardStatus.ACTIVE.name())
                .set(ScMemberCard::getActivationDate, LocalDate.now())
                .set(ScMemberCard::getUpdatedAt, LocalDateTime.now());

        return this.update(updateWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean suspendCard(Long cardId) {
        LambdaUpdateWrapper<ScMemberCard> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(ScMemberCard::getId, cardId)
                .eq(ScMemberCard::getIsDeleted, 0)
                .set(ScMemberCard::getStatus, ScMemberCard.CardStatus.SUSPENDED.name())
                .set(ScMemberCard::getUpdatedAt, LocalDateTime.now());

        return this.update(updateWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean renewCard(Long cardId, Integer days) {
        ScMemberCard card = this.getById(cardId);
        if (card == null) {
            throw new RuntimeException("会员卡不存在");
        }

        // 计算新的到期日期
        LocalDate newExpiryDate;
        if (card.getExpiryDate() != null && card.getExpiryDate().isAfter(LocalDate.now())) {
            newExpiryDate = card.getExpiryDate().plusDays(days);
        } else {
            newExpiryDate = LocalDate.now().plusDays(days);
        }

        // 更新数据库
        LambdaUpdateWrapper<ScMemberCard> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(ScMemberCard::getId, cardId)
                .eq(ScMemberCard::getIsDeleted, 0)
                .set(ScMemberCard::getExpiryDate, newExpiryDate)
                .set(ScMemberCard::getStatus, ScMemberCard.CardStatus.ACTIVE.name())
                .set(ScMemberCard::getUpdatedAt, LocalDateTime.now());

        return this.update(updateWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addCardCount(Long cardId, Integer count) {
        int result = memberCardMapper.addCount(cardId, count);
        return result > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deductCardCount(Long cardId, Integer count) {
        int result = memberCardMapper.deductCount(cardId, count);
        return result > 0;
    }


    @Override
    public List<MemberCardVO> getMemberCards(Long memberId) {

//        // 报读课程
        List<ScMemberCard> cards = memberCardMapper.selectByMemberId(memberId);

        return cards.stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
    }

    @Override
    public List<MemberCardVO> getValidMemberCards(Long memberId) {
        List<ScMemberCard> cards = this.lambdaQuery()
                .eq(ScMemberCard::getMemberId, memberId)
                .eq(ScMemberCard::getIsDeleted, 0)
                .in(ScMemberCard::getStatus,
                    ScMemberCard.CardStatus.ACTIVE.name(),
                    ScMemberCard.CardStatus.INACTIVE.name())
                .and(q -> q.isNull(ScMemberCard::getExpiryDate)
//                        .or(ge(ScMemberCard::getExpiryDate, LocalDate.now()))
                )
                .orderByDesc(ScMemberCard::getCreatedAt)
                .list();

        return cards.stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
    }

    @Override
    public boolean checkCardStatus(Long cardId) {
        ScMemberCard card = this.getById(cardId);
        if (card == null) {
            return false;
        }

        // 检查是否过期
        if (card.isExpired()) {
            // 更新状态为过期
            card.setStatus(ScMemberCard.CardStatus.EXPIRED.name());
            this.updateById(card);
            return false;
        }

        return card.isAvailable();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int expiredMemberCard() {
        // 查找已过期的会员卡
        List<ScMemberCard> expiredCards = this.lambdaQuery()
                .eq(ScMemberCard::getIsDeleted, 0)
                .in(ScMemberCard::getStatus,
                    ScMemberCard.CardStatus.ACTIVE.name(),
                    ScMemberCard.CardStatus.INACTIVE.name())
                .lt(ScMemberCard::getExpiryDate, LocalDate.now())
                .list();

        if (expiredCards.isEmpty()) {
            return 0;
        }

        // 批量更新状态
        expiredCards.forEach(expiredCard -> {
            expiredCard.setStatus(ScMemberCard.CardStatus.EXPIRED.name());
        });
        int updatedRows=this.updateBatchById(expiredCards) ? expiredCards.size() : 0;
        System.out.println("今天开始的过期会员卡修改状态任务已启动，影响记录数：" + updatedRows);
        return updatedRows;
    }


    /**
     * 生成卡号
     */
    private String generateCardNo() {
        // YG + 年月日 + 6位随机数
        String dateStr = LocalDate.now().format(java.time.format.DateTimeFormatter.ofPattern("yyyyMMdd"));
        String randomStr = String.format("%06d", (int)(Math.random() * 1000000));
        return "YG" + dateStr + randomStr;
    }

    /**
     * 转换为DTO
     */
    private MemberCardDTO convertToDTO(ScMemberCard card) {
        if (card == null) return null;

        MemberCardDTO dto = new MemberCardDTO();
        BeanUtils.copyProperties(card, dto);

        // 计算字段
        card.calculateFields();
        dto.setValid(card.getValid());
        dto.setExpired(card.getExpired());
        dto.setAvailable(card.getAvailable());
        dto.setCanRenew(card.getCanRenew());

        return dto;
    }

    /**
     * 转换为VO
     */
    private MemberCardVO convertToVO(ScMemberCard card) {
        if (card == null) return null;

        MemberCardVO vo = new MemberCardVO();
        BeanUtils.copyProperties(card, vo);
        // 计算字段
        card.calculateFields();
        vo.setValid(card.getValid());
        vo.setExpired(card.getExpired());
        vo.setAvailable(card.getAvailable());
        vo.setCanRenew(card.getCanRenew());
        vo.setStatusDesc(card.getCardStatus().getDescription());
        // 查询关联信息
        if (card.getMemberId() != null) {
            ScStudent member = memberMapper.selectById(card.getMemberId());
            if (member != null) {
                vo.setMemberName(member.getStudentName());
                vo.setMemberPhone(member.getPhone());
            }
        }

        if (card.getCardTypeId() != null) {
            ScMemberCardTypes cardType = cardTypeMapper.selectById(card.getCardTypeId());
            if (cardType != null) {
                vo.setCardTypeName(cardType.getCardName());
                vo.setCardTypeCode(cardType.getCardTypeId());
//                vo.setCardTypeCategory(cardType.getCategory());
                vo.setCardTypeDescription(cardType.getDescription());
            }
        }

        return vo;
    }

    @Override
    public MemberCardVO getCardById(Long cardId) {
        ScMemberCard card = this.getById(cardId);
        if (card == null) {
            throw new RuntimeException("会员卡不存在");
        }
        return convertToVO(card);
    }

    @Override
    public RespPage<MemberCardVO> getCardList(MemberCardDTO queryDTO) {
        // 构建查询条件
        LambdaQueryWrapper<ScMemberCard> queryWrapper = new LambdaQueryWrapper<>();

        // 基本查询条件
        queryWrapper.eq(ScMemberCard::getIsDeleted, 0);

        // 条件查询
        if (queryDTO.getMemberId() != null) {
            queryWrapper.eq(ScMemberCard::getMemberId, queryDTO.getMemberId());
        }
        if (StringUtils.hasText(queryDTO.getCardNo())) {
            queryWrapper.like(ScMemberCard::getCardNo, queryDTO.getCardNo());
        }
        if (StringUtils.hasText(queryDTO.getStatus())) {
            queryWrapper.eq(ScMemberCard::getStatus, queryDTO.getStatus());
        }
        if (queryDTO.getCardTypeId() != null) {
            queryWrapper.eq(ScMemberCard::getCardTypeId, queryDTO.getCardTypeId());
        }
        if (StrUtil.isNotEmpty(queryDTO.getStartDate())) {
            queryWrapper.ge(ScMemberCard::getExpiryDate, LocalDate.parse(queryDTO.getStartDate()));
        }
        if (StrUtil.isNotEmpty(queryDTO.getEndDate())) {
            queryWrapper.le(ScMemberCard::getExpiryDate, LocalDate.parse(queryDTO.getEndDate()));
        }

        // 排序
        queryWrapper.orderByDesc(ScMemberCard::getCreatedAt);

        // 分页查询
        RespPage<ScMemberCard> page = new RespPage<>(queryDTO.getPageNum(), queryDTO.getPageSize());
        RespPage<ScMemberCard> listPage =this.page(page, queryWrapper);

        // 转换为VO列表
        List<MemberCardVO> voList = listPage.getRows().stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());

        voList.forEach(l->{
            //课程类别名称 课程名称
            ScMemberCardTypes types=cardTypesService.getById(l.getCardTypeId());
            cardTypesService.memberTypeDetail(types);
            l.setCardTypes(types);
        });
        // 构建返回结果
        RespPage<MemberCardVO> result = new RespPage<>(queryDTO.getPageNum(), queryDTO.getPageSize());
        result.setRows(voList);
        result.setTotal(listPage.getTotal());
        result.setPages(queryDTO.getPageNum());
        result.setSize(queryDTO.getPageSize());
        result.setPages(listPage.getPages());

        return result;
    }


    @Override
    public Integer getTodayCardCount() {
        LocalDateTime todayStart = LocalDate.now().atStartOfDay();
        LocalDateTime todayEnd = LocalDate.now().plusDays(1).atStartOfDay();

        return this.lambdaQuery()
                .eq(ScMemberCard::getIsDeleted, 0)
                .eq(ScMemberCard::getTenantId, SecurityUtils.getLoginUser().getNowTenantId())
                .ge(ScMemberCard::getCreatedAt, todayStart)
                .lt(ScMemberCard::getCreatedAt, todayEnd)
                .count();
    }




}
