package shop.alien.storeplatform.service.impl;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.aliyun.tea.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.stereotype.Service;
import shop.alien.entity.store.*;
import shop.alien.entity.store.dto.LifeDiscountCouponDto;
import shop.alien.entity.store.vo.LifeDiscountCouponVo;
import shop.alien.mapper.*;
import shop.alien.storeplatform.service.LifeDiscountCouponPlatformService;
import shop.alien.storeplatform.service.LifeDiscountCouponQuantumRulesPlatformService;
import shop.alien.util.common.constant.DiscountCouponEnum;
import shop.alien.util.coupon.DiscountCouponExpirationUtil;
import shop.alien.util.coupon.LifeDiscountCouponStock;

import java.math.BigDecimal;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 优惠券服务实现类（平台端）
 * 实现优惠券相关的业务逻辑处理，包括优惠券的创建、更新、删除、查询等功能
 * 支持优惠券规则配置、时间段限制、库存管理等
 *
 * @author zjy
 * @since 2025-11-19
 */
@Service
@RequiredArgsConstructor
public class LifeDiscountCouponPlatformServiceImpl extends ServiceImpl<LifeDiscountCouponMapper, LifeDiscountCoupon> implements LifeDiscountCouponPlatformService {

    private final LifeDiscountCouponMapper lifeDiscountCouponMapper;

    private final LifeDiscountCouponUnavailableRulesMapper lifeDiscountCouponUnavailableRulesMapper;

    private final LifeDiscountCouponQuantumRulesMapper lifeDiscountCouponQuantumRulesMapper;

    private final LifeDiscountCouponQuantumRulesPlatformService lifeDiscountCouponQuantumRulesService;

    private final LifeDiscountCouponUserMapper lifeDiscountCouponUserMapper;

    /**
     * 发布优惠券
     * 创建新的优惠券，包括以下功能：
     * 1. 保存优惠券基本信息
     * 2. 根据时间判断并设置可领取状态
     * 3. 计算并设置优惠券有效期
     * 4. 保存周中不可用规则
     * 5. 保存节假日不可用规则
     * 6. 保存领取规则
     * 7. 保存指定时间段可用/不可用规则
     *
     * @param lifeDiscountCouponDto 优惠券信息对象
     * @return boolean 操作结果，true-成功，false-失败
     */
    @Override
    public boolean addDiscountCoupon(LifeDiscountCouponDto lifeDiscountCouponDto) {
        try {
            //发布优惠券表信息
            LifeDiscountCoupon lifeDiscountCoupon = new LifeDiscountCoupon();
            BeanUtils.copyProperties(lifeDiscountCouponDto, lifeDiscountCoupon);
            // 显式设置最低消费金额（门槛费），确保能正确保存
            // 如果 DTO 中有值，使用 DTO 的值；如果为 null，设置为 0（表示无门槛）
            if (lifeDiscountCouponDto.getMinimumSpendingAmount() != null) {
                lifeDiscountCoupon.setMinimumSpendingAmount(lifeDiscountCouponDto.getMinimumSpendingAmount());
            } else {
                lifeDiscountCoupon.setMinimumSpendingAmount(BigDecimal.ZERO);
            }
            if (lifeDiscountCoupon.getLongTermValid() == null) {
                lifeDiscountCoupon.setLongTermValid(0);
            }
            if (Integer.valueOf(1).equals(lifeDiscountCouponDto.getCouponStatus())
                    && !Integer.valueOf(1).equals(lifeDiscountCoupon.getLongTermValid())
                    && !DiscountCouponExpirationUtil.templateHasPositiveDayValidity(
                    lifeDiscountCoupon.getSpecifiedDay(), lifeDiscountCoupon.getExpirationDate())) {
                throw new IllegalArgumentException("请配置有效期天数（expirationDate 或 specifiedDay）或开启长期有效");
            }
            clearTemplateObsoleteAbsoluteUsePeriod(lifeDiscountCoupon);
            // 根据开始领取时间判断可领取状态
            // 判断是否在领取时间内

            Date now = new Date();
            Instant instant = now.toInstant();
            ZoneId zoneId = ZoneId.systemDefault();
            LocalDate localNow = instant.atZone(zoneId).toLocalDate();
            if (Integer.valueOf(1).equals(lifeDiscountCouponDto.getCouponStatus())
                    && lifeDiscountCoupon.getBeginGetDate() != null
                    && lifeDiscountCoupon.getEndGetDate() != null) {
                int startResult = localNow.compareTo(lifeDiscountCoupon.getBeginGetDate());
                int endResult = localNow.compareTo(lifeDiscountCoupon.getEndGetDate());
                if (startResult < 0 || endResult > 0) {
                    lifeDiscountCoupon.setGetStatus(0);
                } else {
                    lifeDiscountCoupon.setGetStatus(1);
                }
            }

            lifeDiscountCouponMapper.insert(lifeDiscountCoupon);
            //发布优惠券规则信息
            //周中规则保存
            LifeDiscountCouponUnavailableRules lifeDiscountCouponUnavailableRules = new LifeDiscountCouponUnavailableRules();
            lifeDiscountCouponUnavailableRules.setDiscountCouponId(lifeDiscountCoupon.getId());
            lifeDiscountCouponUnavailableRules.setUnavailableRuleType(DiscountCouponEnum.WEEKDAY_UNAVAILABLE.getValue());
            if (CollectionUtils.isNotEmpty(lifeDiscountCouponDto.getWeeklyDisabledList())) {
                lifeDiscountCouponDto.getWeeklyDisabledList().forEach(weeklyDisabled -> {
                    lifeDiscountCouponUnavailableRules.setUnavailableRuleValue(weeklyDisabled);
                    lifeDiscountCouponUnavailableRulesMapper.insert(lifeDiscountCouponUnavailableRules);
                });
            }

            //节假日规则保存
            lifeDiscountCouponUnavailableRules.setUnavailableRuleType(DiscountCouponEnum.HOLIDAY_UNAVAILABLE.getValue());
            if (CollectionUtils.isNotEmpty(lifeDiscountCouponDto.getHolidayDisabledList())) {
                lifeDiscountCouponDto.getHolidayDisabledList().forEach(holidayDisabled -> {
                    lifeDiscountCouponUnavailableRules.setUnavailableRuleValue(holidayDisabled);
                    lifeDiscountCouponUnavailableRulesMapper.insert(lifeDiscountCouponUnavailableRules);
                });
            }

            //领取规则
            lifeDiscountCouponUnavailableRules.setUnavailableRuleType(DiscountCouponEnum.CLAIM_RULE.getValue());
            String claimRule = lifeDiscountCouponDto.getClaimRule();
            //领取规则为自定义时，获取自定义数量
            if (claimRule != null && claimRule.equals(DiscountCouponEnum.CUSTOMIZE.getValue())) {
                lifeDiscountCouponUnavailableRules.setCustomizeValue(lifeDiscountCouponDto.getClaimRuleCustomizeValue());
            }
            lifeDiscountCouponUnavailableRules.setUnavailableRuleValue(lifeDiscountCouponDto.getClaimRule());
            lifeDiscountCouponUnavailableRulesMapper.insert(lifeDiscountCouponUnavailableRules);

            //指定时间段可用规则
            List<LifeDiscountCouponQuantumRules> availableTimeQuantumList = lifeDiscountCouponDto.getAvailableTimeQuantum();
            if (CollectionUtils.isNotEmpty(availableTimeQuantumList)) {
                availableTimeQuantumList.forEach(availableTimeQuantum -> {
                    availableTimeQuantum.setDiscountCouponId(lifeDiscountCoupon.getId());
                });
                lifeDiscountCouponQuantumRulesService.saveBatch(availableTimeQuantumList);
            }

            //自定义时间段不可用规则
            List<LifeDiscountCouponQuantumRules> customizeUnavailableTimeQuantumList = lifeDiscountCouponDto.getCustomizeUnavailableTimeQuantum();
            if (CollectionUtils.isNotEmpty(customizeUnavailableTimeQuantumList)) {
                customizeUnavailableTimeQuantumList.forEach(customizeUnavailableTimeQuantum -> {
                    customizeUnavailableTimeQuantum.setDiscountCouponId(lifeDiscountCoupon.getId());
                });
                lifeDiscountCouponQuantumRulesService.saveBatch(customizeUnavailableTimeQuantumList);
            }
        } catch (BeansException e) {
            log.error("LifeDiscountCouponServiceImpl.receiveCoupon ERROR Msg=" + e.getMessage());
            return false;
        }
        return true;
    }

    /**
     * 修改优惠券
     * 更新已存在的优惠券信息，包括以下功能：
     * 1. 更新优惠券基本信息
     * 2. 重新计算可领取状态
     * 3. 重新计算有效期
     * 4. 删除并重新保存所有规则信息（周中规则、节假日规则、领取规则）
     * 5. 删除并重新保存时间段规则
     *
     * @param lifeDiscountCouponDto 优惠券信息对象
     * @return boolean 操作结果，true-成功，false-失败
     */
    @Override
    public boolean editDiscountCoupon(LifeDiscountCouponDto lifeDiscountCouponDto) {
        try {
            //发布优惠券表信息
            LifeDiscountCoupon lifeDiscountCoupon = new LifeDiscountCoupon();
            lifeDiscountCoupon.setId(Integer.parseInt(lifeDiscountCouponDto.getCouponId()));
            BeanUtils.copyProperties(lifeDiscountCouponDto, lifeDiscountCoupon);
            // 显式设置最低消费金额（门槛费），确保能正确保存
            // 如果 DTO 中有值，使用 DTO 的值；如果为 null，设置为 0（表示无门槛）
            if (lifeDiscountCouponDto.getMinimumSpendingAmount() != null) {
                lifeDiscountCoupon.setMinimumSpendingAmount(lifeDiscountCouponDto.getMinimumSpendingAmount());
            } else {
                lifeDiscountCoupon.setMinimumSpendingAmount(BigDecimal.ZERO);
            }

            // 根据开始领取时间判断可领取状态
            // 判断是否在领取时间内
            Date now = new Date();
            Instant instant = now.toInstant();
            ZoneId zoneId = ZoneId.systemDefault();
            LocalDate localNow = instant.atZone(zoneId).toLocalDate();
            if (Integer.valueOf(1).equals(lifeDiscountCouponDto.getCouponStatus())
                    && lifeDiscountCoupon.getBeginGetDate() != null
                    && lifeDiscountCoupon.getEndGetDate() != null) {
                int startResult = localNow.compareTo(lifeDiscountCoupon.getBeginGetDate());
                int endResult = localNow.compareTo(lifeDiscountCoupon.getEndGetDate());
                if (startResult < 0 || endResult > 0) {
                    lifeDiscountCoupon.setGetStatus(0);
                } else {
                    lifeDiscountCoupon.setGetStatus(1);
                }
            } else if (lifeDiscountCouponDto.getCouponStatus() != null && lifeDiscountCouponDto.getCouponStatus() == 0) {
                lifeDiscountCoupon.setGetStatus(0);
            }

            lifeDiscountCouponMapper.updateById(lifeDiscountCoupon);
            //发布优惠券规则信息
            //先删除之前所有规则
            LambdaQueryWrapper<LifeDiscountCouponUnavailableRules> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(LifeDiscountCouponUnavailableRules::getDiscountCouponId, lifeDiscountCoupon.getId());
            lifeDiscountCouponUnavailableRulesMapper.delete(queryWrapper);

            //周中规则保存
            LifeDiscountCouponUnavailableRules lifeDiscountCouponUnavailableRules = new LifeDiscountCouponUnavailableRules();
            lifeDiscountCouponUnavailableRules.setDiscountCouponId(lifeDiscountCoupon.getId());
            lifeDiscountCouponUnavailableRules.setUnavailableRuleType(DiscountCouponEnum.WEEKDAY_UNAVAILABLE.getValue());
            if (CollectionUtils.isNotEmpty(lifeDiscountCouponDto.getWeeklyDisabledList())) {
                lifeDiscountCouponDto.getWeeklyDisabledList().forEach(weeklyDisabled -> {
                    lifeDiscountCouponUnavailableRules.setUnavailableRuleValue(weeklyDisabled);
                    lifeDiscountCouponUnavailableRulesMapper.insert(lifeDiscountCouponUnavailableRules);
                });
            }

            //节假日规则保存
            lifeDiscountCouponUnavailableRules.setUnavailableRuleType(DiscountCouponEnum.HOLIDAY_UNAVAILABLE.getValue());
            if (CollectionUtils.isNotEmpty(lifeDiscountCouponDto.getHolidayDisabledList())) {
                lifeDiscountCouponDto.getHolidayDisabledList().forEach(holidayDisabled -> {
                    lifeDiscountCouponUnavailableRules.setUnavailableRuleValue(holidayDisabled);
                    lifeDiscountCouponUnavailableRulesMapper.insert(lifeDiscountCouponUnavailableRules);
                });
            }

            //领取规则
            lifeDiscountCouponUnavailableRules.setUnavailableRuleType(DiscountCouponEnum.CLAIM_RULE.getValue());
            lifeDiscountCouponUnavailableRules.setUnavailableRuleValue(lifeDiscountCouponDto.getClaimRule());
            lifeDiscountCouponUnavailableRulesMapper.insert(lifeDiscountCouponUnavailableRules);

            // 删除优惠券时间段规则信息
            LambdaQueryWrapper<LifeDiscountCouponQuantumRules> lifeDiscountCouponQuantumRulesLambdaQueryWrapper = new LambdaQueryWrapper<>();
            lifeDiscountCouponQuantumRulesLambdaQueryWrapper.eq(LifeDiscountCouponQuantumRules::getDiscountCouponId, lifeDiscountCoupon.getId());
            lifeDiscountCouponQuantumRulesMapper.delete(lifeDiscountCouponQuantumRulesLambdaQueryWrapper);

            // 保存指定时间段可用规则
            List<LifeDiscountCouponQuantumRules> availableTimeQuantumList = lifeDiscountCouponDto.getAvailableTimeQuantum();
            if (CollectionUtils.isNotEmpty(availableTimeQuantumList)) {
                availableTimeQuantumList.forEach(availableTimeQuantum -> {
                    availableTimeQuantum.setDiscountCouponId(lifeDiscountCoupon.getId());
                });
                lifeDiscountCouponQuantumRulesService.saveBatch(availableTimeQuantumList);
            }
            // 保存自定义时间段不可用规则
            List<LifeDiscountCouponQuantumRules> customizeUnavailableTimeQuantumList = lifeDiscountCouponDto.getCustomizeUnavailableTimeQuantum();
            if (CollectionUtils.isNotEmpty(customizeUnavailableTimeQuantumList)) {
                customizeUnavailableTimeQuantumList.forEach(customizeUnavailableTimeQuantum -> {
                    customizeUnavailableTimeQuantum.setDiscountCouponId(lifeDiscountCoupon.getId());
                });
                lifeDiscountCouponQuantumRulesService.saveBatch(customizeUnavailableTimeQuantumList);
            }

        } catch (BeansException e) {
            log.error("LifeDiscountCouponServiceImpl.editDiscountCoupon ERROR Msg=" + e.getMessage());
            return false;
        }
        return true;
    }

    /**
     * 删除优惠券
     * 删除优惠券及其关联的所有规则信息
     *
     * @param id 优惠券ID
     * @return boolean 操作结果，true-成功，false-失败
     */
    @Override
    public boolean deleteDiscountCoupon(Integer id) {
        //删除优惠券表信息
        lifeDiscountCouponMapper.deleteById(id);
        //删除优惠券规则信息
        lifeDiscountCouponUnavailableRulesMapper.delete(new LambdaQueryWrapper<LifeDiscountCouponUnavailableRules>().eq(LifeDiscountCouponUnavailableRules::getDiscountCouponId, id));
        return true;
    }

    /**
     * 修改优惠券库存数量
     * 直接更新指定优惠券的库存数量
     *
     * @param id 优惠券ID
     * @param singleQty 库存数量
     * @return boolean 操作结果，true-成功，false-失败
     */
    @Override
    public boolean updateCouponSingleQty(Integer id, Integer singleQty) {
        return lifeDiscountCouponMapper.updateCouponById(id, singleQty) > 0;
    }

    /**
     * 切换优惠券进行状态
     * 切换优惠券的可领取状态（启用/暂停）
     * 如果当前状态为不可领取，切换为可领取时会设置开始领取时间为当前日期
     *
     * @param counponId 优惠券ID
     * @return boolean 操作结果，true-成功，false-失败
     */
    @Override
    public boolean cutDiscountCouponStatus(String counponId) {
        LifeDiscountCoupon lifeDiscountCoupon = lifeDiscountCouponMapper.selectById(counponId);
        if (lifeDiscountCoupon.getGetStatus() == Integer.parseInt(DiscountCouponEnum.NO_GET.getValue())) {
            Date now = new Date();
            Instant instant = now.toInstant();
            ZoneId zoneId = ZoneId.systemDefault();
            LocalDate localNow = instant.atZone(zoneId).toLocalDate();
            lifeDiscountCoupon.setBeginGetDate(localNow);
        }
        lifeDiscountCoupon.setGetStatus(lifeDiscountCoupon.getGetStatus() == Integer.parseInt(DiscountCouponEnum.NO_GET.getValue()) ? Integer.parseInt(DiscountCouponEnum.CAN_GET.getValue()) : Integer.parseInt(DiscountCouponEnum.NO_GET.getValue()));
        lifeDiscountCouponMapper.updateById(lifeDiscountCoupon);
        return true;
    }

    /**
     * 获取该优惠券的明细信息
     * 根据优惠券ID查询优惠券的详细信息，包括：
     * 1. 优惠券基本信息
     * 2. 周中不可用规则列表
     * 3. 节假日不可用规则列表
     * 4. 领取规则
     * 5. 指定时间段可用规则列表
     * 6. 自定义时间段不可用规则列表
     *
     * @param counponId 优惠券ID
     * @param userLoginInfo 当前登录用户信息
     * @return LifeDiscountCouponVo 优惠券详情对象
     */
    @Override
    public LifeDiscountCouponVo getCounponDetailById(String counponId, UserLoginInfo userLoginInfo) {
        int couponIdInt = Integer.parseInt(counponId);
        LifeDiscountCoupon lifeDiscountCoupon = lifeDiscountCouponMapper.selectByIdIncludeDeleted(couponIdInt);
        LifeDiscountCouponVo lifeDiscountCouponVo = new LifeDiscountCouponVo();
        lifeDiscountCouponVo.setCouponId(couponIdInt);
        if (lifeDiscountCoupon == null) {
            return lifeDiscountCouponVo;
        }
        BeanUtils.copyProperties(lifeDiscountCoupon, lifeDiscountCouponVo);
        //查规则信息
        List<LifeDiscountCouponUnavailableRules> lifeDiscountCouponUnavailableRules =
                lifeDiscountCouponUnavailableRulesMapper.listByDiscountCouponIdIncludeDeleted(couponIdInt);

        List<String> weeklyDisabledList = new ArrayList<>();
        List<String> holidayDisabledList = new ArrayList<>();
        String claimRule = "";
        for (LifeDiscountCouponUnavailableRules rule : lifeDiscountCouponUnavailableRules) {
            if (rule.getUnavailableRuleType().equals(DiscountCouponEnum.WEEKDAY_UNAVAILABLE.getValue())) {
                weeklyDisabledList.add(rule.getUnavailableRuleValue());
            }
            if (rule.getUnavailableRuleType().equals(DiscountCouponEnum.HOLIDAY_UNAVAILABLE.getValue())) {
                holidayDisabledList.add(rule.getUnavailableRuleValue());
            }
            if (rule.getUnavailableRuleType().equals(DiscountCouponEnum.CLAIM_RULE.getValue())) {
                claimRule = rule.getUnavailableRuleValue();
            }
        }
        lifeDiscountCouponVo.setWeeklyDisabledList(weeklyDisabledList);
        lifeDiscountCouponVo.setHolidayDisabledList(holidayDisabledList);
        lifeDiscountCouponVo.setClaimRule(claimRule);

        // 查询时间段规则信息
        List<LifeDiscountCouponQuantumRules> lifeDiscountCouponQuantumRulesList =
                lifeDiscountCouponQuantumRulesMapper.listByDiscountCouponIdIncludeDeleted(couponIdInt);
        List<LifeDiscountCouponQuantumRules> availableTimeQuantumList = new ArrayList<>();
        List<LifeDiscountCouponQuantumRules> customizeUnavailableTimeQuantumList = new ArrayList<>();
        for (LifeDiscountCouponQuantumRules lifeDiscountCouponQuantumRules : lifeDiscountCouponQuantumRulesList) {
            if (lifeDiscountCouponQuantumRules.getTimeQuantumType().equals(DiscountCouponEnum.AVAILABLE_TIME_QUANTUM.getValue())) {
                availableTimeQuantumList.add(lifeDiscountCouponQuantumRules);
            }
            if (lifeDiscountCouponQuantumRules.getTimeQuantumType().equals(DiscountCouponEnum.UNAVAILABLE_TIME_QUANTUM.getValue())) {
                customizeUnavailableTimeQuantumList.add(lifeDiscountCouponQuantumRules);
            }
        }
        lifeDiscountCouponVo.setAvailableTimeQuantum(availableTimeQuantumList);
        lifeDiscountCouponVo.setCustomizeUnavailableTimeQuantum(customizeUnavailableTimeQuantumList);
        lifeDiscountCouponVo.setCreatedTime(lifeDiscountCoupon.getCreatedTime());
        if (lifeDiscountCouponVo.getMinimumSpendingAmount() != null && lifeDiscountCouponVo.getMinimumSpendingAmount().compareTo(BigDecimal.ZERO) == 0) {
            lifeDiscountCouponVo.setMinimumSpendingAmount(null);
        }
        return lifeDiscountCouponVo;
    }

    /**
     * 日期增加天数（Java 8方式）
     * 使用Java 8的日期API为指定日期增加天数
     *
     * @param date 原始日期
     * @param days 要增加的天数
     * @return Date 增加后的日期
     */
    public static Date addDaysToDateJava8(Date date, int days) {
        // 将Date转换为Instant
        Instant instant = date.toInstant();

        // 转换为LocalDate并加天数
        LocalDate localDate = instant.atZone(ZoneId.systemDefault()).toLocalDate();
        LocalDate newLocalDate = localDate.plusDays(days);

        // 转换回Date
        return Date.from(newLocalDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
    }

    /**
     * 获取纯日期
     * 将日期时间转换为纯日期（时间部分设置为00:00:00）
     *
     * @param date 原始日期时间
     * @return Date 纯日期（时间为00:00:00）
     */
    public static Date getPureDate(Date date) {
        Instant instant = date.toInstant();
        LocalDate localDate = instant.atZone(ZoneId.systemDefault()).toLocalDate();
        LocalDateTime localDateTime = localDate.atStartOfDay(); // 时间为 00:00
        return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
    }

    /**
     * 获取所有优惠券列表（分页）
     * 根据条件查询店铺的优惠券列表，支持按名称、状态等条件筛选
     * 主要功能：
     * 1. 按优惠券名称模糊查询
     * 2. 按状态筛选（进行中/已结束/已暂停）
     * 3. 计算每个优惠券的当前状态（草稿/进行中/已结束/未开始/已暂停/已售罄）
     * 4. 查询优惠券的规则配置信息
     * 5. 统计优惠券已领取数量
     * 6. 支持分页查询
     *
     * @param storeId 店铺ID
     * @param userLoginInfo 当前登录用户信息
     * @param page 页码
     * @param size 每页数量
     * @param couponName 优惠券名称（模糊查询）
     * @param couponsFromType 优惠券来源类型
     * @param couponStatus 优惠券状态(1:进行中, 2:已结束, 3:已暂停)
     * @return IPage<LifeDiscountCouponVo> 分页优惠券列表
     */
    @Override
    public IPage<LifeDiscountCouponVo> getStoreAllCouponList(String storeId, UserLoginInfo userLoginInfo, int page, int size, String couponName, Integer couponsFromType, Integer couponStatus, Integer discountCouponType) {

        IPage<LifeDiscountCoupon> iPage = new Page<>(page, size);
        List<LifeDiscountCouponVo> lifeDiscountCouponVos = new ArrayList<>();
        LambdaQueryWrapper<LifeDiscountCoupon> lifeDiscountCouponLambdaQueryWrapper = new LambdaQueryWrapper<LifeDiscountCoupon>();

        //如果couponName不为空，则模糊查询
        if (!StringUtils.isEmpty(couponName)) {
            lifeDiscountCouponLambdaQueryWrapper.like(LifeDiscountCoupon::getName, couponName);
        }
        //如果指定了优惠券类型（满减券或折扣券），添加筛选条件
        if (discountCouponType != null) {
            lifeDiscountCouponLambdaQueryWrapper.eq(LifeDiscountCoupon::getCouponType, discountCouponType);
        }
        //获取当日日期
        Date now = new Date();
        LocalDate pureLocalDate = now.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        //如果根据类型查询
        if (!StringUtils.isEmpty(couponStatus) && couponStatus.equals(1)) {//进行中
            lifeDiscountCouponLambdaQueryWrapper.eq(LifeDiscountCoupon::getGetStatus, 1)
                    .eq(LifeDiscountCoupon::getCouponStatus, 1)
                    .and(w -> w.eq(LifeDiscountCoupon::getUnlimitedQty, 1)
                            .or()
                            .gt(LifeDiscountCoupon::getSingleQty, 0))
                    .and(w -> w.and(w2 -> w2.isNull(LifeDiscountCoupon::getBeginGetDate)
                                    .or()
                                    .le(LifeDiscountCoupon::getBeginGetDate, pureLocalDate))
                            .and(w2 -> w2.isNull(LifeDiscountCoupon::getEndGetDate)
                                    .or()
                                    .ge(LifeDiscountCoupon::getEndGetDate, pureLocalDate)));
        } else if (!StringUtils.isEmpty(couponStatus) && couponStatus.equals(2)) {//已结束
            //结束时间小于当前时间
            lifeDiscountCouponLambdaQueryWrapper.lt(LifeDiscountCoupon::getEndGetDate, getPureDate(now));

            //不要已暂停关闭领取的
            lifeDiscountCouponLambdaQueryWrapper.eq(LifeDiscountCoupon::getGetStatus, 1);
            lifeDiscountCouponLambdaQueryWrapper.eq(LifeDiscountCoupon::getCouponStatus, 1);
        } else if (!StringUtils.isEmpty(couponStatus) && couponStatus.equals(3)) {
            lifeDiscountCouponLambdaQueryWrapper.eq(LifeDiscountCoupon::getCouponStatus, 0);
        }
        lifeDiscountCouponLambdaQueryWrapper.eq(LifeDiscountCoupon::getStoreId, storeId);
        lifeDiscountCouponLambdaQueryWrapper.orderByDesc(LifeDiscountCoupon::getCreatedTime);
        //根据店铺id查询该店铺的优惠券,状态是开启领取的券
        IPage<LifeDiscountCoupon> lifeDiscountCouponIPage = lifeDiscountCouponMapper.selectPage(iPage, lifeDiscountCouponLambdaQueryWrapper);
        for (LifeDiscountCoupon lifeDiscountCoupon : lifeDiscountCouponIPage.getRecords()) {
            LifeDiscountCouponVo lifeDiscountCouponVo = new LifeDiscountCouponVo();
            lifeDiscountCouponVo.setCouponId(lifeDiscountCoupon.getId());
            //处理一下该优惠券的状态 状态(0:进行中，1:已结束，2:未开始，3:已暂停)
            // 将 Date 转换为 LocalDate
            Instant instant = now.toInstant();
            ZoneId zoneId = ZoneId.systemDefault();
            LocalDate localNow = instant.atZone(zoneId).toLocalDate();
            if (!StringUtils.isEmpty(lifeDiscountCoupon.getBeginGetDate()) && !StringUtils.isEmpty(lifeDiscountCoupon.getEndGetDate())) {
                int startResult = localNow.compareTo(lifeDiscountCoupon.getBeginGetDate());
                int endResult = localNow.compareTo(lifeDiscountCoupon.getEndGetDate());
                if (lifeDiscountCoupon.getCouponStatus() == 0) {
                    lifeDiscountCouponVo.setStatus(Integer.parseInt(DiscountCouponEnum.DRAFT.getValue()));
                    lifeDiscountCouponVo.setStatusDesc("草稿");
                } else if (!LifeDiscountCouponStock.hasTemplateStockRemaining(
                        lifeDiscountCoupon.getUnlimitedQty(), lifeDiscountCoupon.getSingleQty())) {
                    lifeDiscountCouponVo.setStatus(Integer.parseInt(DiscountCouponEnum.HAVE_SOLD_OUT.getValue()));
                    lifeDiscountCouponVo.setStatusDesc("已售罄");
                } else if (startResult < 0) {
                    lifeDiscountCouponVo.setStatus(Integer.parseInt(DiscountCouponEnum.HAVE_NOT_STARTED.getValue()));
                    lifeDiscountCouponVo.setStatusDesc("未开始");
                } else if (lifeDiscountCoupon.getGetStatus() == null || lifeDiscountCoupon.getGetStatus().toString().equals(DiscountCouponEnum.NO_GET.getValue())) {
                    lifeDiscountCouponVo.setStatus(Integer.parseInt(DiscountCouponEnum.SUSPEND_GET.getValue()));
                    lifeDiscountCouponVo.setStatusDesc("已暂停");
                } else if (endResult > 0) {
                    lifeDiscountCouponVo.setStatus(Integer.parseInt(DiscountCouponEnum.FINISHED.getValue()));
                    lifeDiscountCouponVo.setStatusDesc("已结束");
                } else if (startResult >= 0 && endResult <= 0) {
                    lifeDiscountCouponVo.setStatus(Integer.parseInt(DiscountCouponEnum.UNDER_WAY.getValue()));
                    lifeDiscountCouponVo.setStatusDesc("进行中");
                }
            } else {
                int st = resolvePlatformListStatusWithoutGetWindow(
                        lifeDiscountCoupon.getCouponStatus(),
                        lifeDiscountCoupon.getGetStatus(),
                        lifeDiscountCoupon.getUnlimitedQty(),
                        lifeDiscountCoupon.getSingleQty());
                lifeDiscountCouponVo.setStatus(st);
                lifeDiscountCouponVo.setStatusDesc(platformStatusDesc(st));
            }
            // 查询三个规则
            List<LifeDiscountCouponUnavailableRules> discountCouponId = lifeDiscountCouponUnavailableRulesMapper.selectList(new QueryWrapper<LifeDiscountCouponUnavailableRules>().eq("discount_coupon_id", lifeDiscountCoupon.getId()));
            Map<String, List<LifeDiscountCouponUnavailableRules>> collect = discountCouponId.stream().collect(Collectors.groupingBy(x -> x.getUnavailableRuleType()));
            if (collect.containsKey(DiscountCouponEnum.WEEKDAY_UNAVAILABLE.getValue())) {
                lifeDiscountCouponVo.setWeeklyDisabledList(collect.get(DiscountCouponEnum.WEEKDAY_UNAVAILABLE.getValue()).stream().map(x -> x.getUnavailableRuleValue()).collect(Collectors.toList()));
            }
            if (collect.containsKey(DiscountCouponEnum.HOLIDAY_UNAVAILABLE.getValue())) {
                lifeDiscountCouponVo.setHolidayDisabledList(collect.get(DiscountCouponEnum.HOLIDAY_UNAVAILABLE.getValue()).stream().map(x -> x.getUnavailableRuleValue()).collect(Collectors.toList()));
            }
            if (collect.containsKey(DiscountCouponEnum.CLAIM_RULE.getValue())) {
                lifeDiscountCouponVo.setClaimRule(collect.get(DiscountCouponEnum.CLAIM_RULE.getValue()).get(0).getUnavailableRuleValue());
            }
            BeanUtils.copyProperties(lifeDiscountCoupon, lifeDiscountCouponVo);

            //查询已领取多少券
            LambdaQueryWrapper<LifeDiscountCouponUser> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(LifeDiscountCouponUser::getCouponId, lifeDiscountCoupon.getId());
            queryWrapper.eq(LifeDiscountCouponUser::getDeleteFlag, 0);
            queryWrapper.in(LifeDiscountCouponUser::getStatus, 0, 1);
            List<LifeDiscountCouponUser> lifeDiscountCouponUsers = lifeDiscountCouponUserMapper.selectList(queryWrapper);
            lifeDiscountCouponVo.setQuantityClaimed(lifeDiscountCouponUsers.size());

            lifeDiscountCouponVos.add(lifeDiscountCouponVo);
        }
        IPage<LifeDiscountCouponVo> lifeDiscountCouponVoIPage = new Page<>();
        BeanUtils.copyProperties(lifeDiscountCouponIPage, lifeDiscountCouponVoIPage);
        lifeDiscountCouponVoIPage.setRecords(lifeDiscountCouponVos);
        return lifeDiscountCouponVoIPage;
    }

    private int resolvePlatformListStatusWithoutGetWindow(Integer couponStatus, Integer getStatus,
                                                          Integer unlimitedQty, Integer singleQty) {
        if (couponStatus != null && couponStatus == 0) {
            return Integer.parseInt(DiscountCouponEnum.DRAFT.getValue());
        }
        if (!LifeDiscountCouponStock.hasTemplateStockRemaining(unlimitedQty, singleQty)) {
            return Integer.parseInt(DiscountCouponEnum.HAVE_SOLD_OUT.getValue());
        }
        if (getStatus == null || getStatus.toString().equals(DiscountCouponEnum.NO_GET.getValue())) {
            return Integer.parseInt(DiscountCouponEnum.SUSPEND_GET.getValue());
        }
        return Integer.parseInt(DiscountCouponEnum.UNDER_WAY.getValue());
    }

    private static String platformStatusDesc(int st) {
        if (st == Integer.parseInt(DiscountCouponEnum.DRAFT.getValue())) {
            return "草稿";
        }
        if (st == Integer.parseInt(DiscountCouponEnum.UNDER_WAY.getValue())) {
            return "进行中";
        }
        if (st == Integer.parseInt(DiscountCouponEnum.FINISHED.getValue())) {
            return "已结束";
        }
        if (st == Integer.parseInt(DiscountCouponEnum.HAVE_NOT_STARTED.getValue())) {
            return "未开始";
        }
        if (st == Integer.parseInt(DiscountCouponEnum.SUSPEND_GET.getValue())) {
            return "已暂停";
        }
        if (st == Integer.parseInt(DiscountCouponEnum.HAVE_SOLD_OUT.getValue())) {
            return "已售罄";
        }
        return "";
    }

    private static void clearTemplateObsoleteAbsoluteUsePeriod(LifeDiscountCoupon c) {
        c.setStartDate(null);
        c.setEndDate(null);
        c.setValidDate(null);
    }
}
