package shop.alien.storeplatform.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import shop.alien.entity.result.R;
import shop.alien.entity.store.*;
import shop.alien.entity.store.vo.LifeDiscountCouponVo;
import shop.alien.entity.storePlatform.vo.LifeCouponPlatformDto;
import shop.alien.mapper.*;
import shop.alien.storeplatform.service.LifeCouponPlatformService;
import shop.alien.util.common.UniqueRandomNumGenerator;

import java.math.BigDecimal;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.format.TextStyle;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 优惠券服务实现类（平台端）
 * 负责处理优惠券的创建、更新、删除、查询、核销等核心业务逻辑
 * 支持优惠券库存管理、状态管理、节假日管理、订单核销验证等功能
 *
 * @author alien-cloud
 * @date 2025-11-18
 */
@Service
@RequiredArgsConstructor
public class LifeCouponPlatformServiceImpl extends ServiceImpl<LifeCouponMapper, LifeCoupon> implements LifeCouponPlatformService {

    private final LifeCouponMapper lifeCouponMapper;

    private final LifeUserOrderMapper lifeUserOrderMapper;

    private final StoreDictionaryMapper storeDictionaryMapper;

    private final EssentialHolidayComparisonMapper essentialHolidayComparisonMapper;


    private final OrderCouponMiddleMapper orderCouponMiddleMapper;

    private final LifeGroupBuyMainMapper lifeGroupBuyMainMapper;

    /**
     * 新增或更新优惠券
     * 根据优惠券是否存在ID判断是新增还是更新操作
     * 自动生成优惠券编码，设置优惠标签和状态
     *
     * @param lifeCoupon 优惠券对象
     * @return LifeCoupon 保存后的优惠券信息
     * @author alien-cloud
     * @date 2025-11-18
     */
    @Override
    public LifeCoupon addOrUpdateCoupon(LifeCoupon lifeCoupon) {

        // 添加优惠tag
        //获取经营板块id
//        Integer businessSection = lifeCoupon.getBusinessSection();
        //查询经营板块名称
        StoreDictionary youhuiName = storeDictionaryMapper.selectOne(new LambdaQueryWrapper<StoreDictionary>().eq(StoreDictionary::getDictId, "180").eq(StoreDictionary::getTypeName, "youhui"));
        //查询经营种类
        List<String> discountTypes = lifeCoupon.getTempDiscountTag();
        List<String> businessTypeNames = new ArrayList<>();
        //获取经营种类名称
        if (!CollectionUtils.isEmpty(discountTypes)) {
            for (String businessType : discountTypes) {
                StoreDictionary storeDictionary =
                        storeDictionaryMapper
                                .selectOne(
                                        new LambdaQueryWrapper<StoreDictionary>()
                                                .eq(StoreDictionary::getDictId, businessType).eq(StoreDictionary::getParentId, youhuiName.getId()));
                businessTypeNames.add(storeDictionary.getDictDetail());
            }
            lifeCoupon.setDiscountTag(String.join(",", discountTypes));
            lifeCoupon.setDiscountTagName(String.join(",", businessTypeNames));
        }

        if (lifeCoupon.getPurchaseLimitCode() == null || "".equals(lifeCoupon.getPurchaseLimitCode())) {
            lifeCoupon.setPurchaseLimitCode("0");
        }

        if (lifeCoupon.getSingleCanUse() == null || "".equals(lifeCoupon.getSingleCanUse())) {
            lifeCoupon.setSingleCanUse("0");
        }

        if (lifeCoupon.getSingleQty() == null || "".equals(lifeCoupon.getSingleQty())) {
            lifeCoupon.setSingleQty(0);
        }

        lifeCoupon.setStatus(1);
        if (StringUtils.isEmpty(lifeCoupon.getId())) {
            lifeCoupon.setType(1);
            lifeCoupon.setCouponCode(UniqueRandomNumGenerator.generateUniqueCode(12));
            this.save(lifeCoupon);
        } else {
            this.updateById(lifeCoupon);
        }
        return lifeCoupon;
    }

    /**
     * 修改库存数量
     * 更新指定优惠券的库存数量，当库存为0时增加库存会自动修改状态为进行中
     *
     * @param id 优惠券ID
     * @param singleQty 库存数量
     * @return boolean 更新是否成功
     * @author alien-cloud
     * @date 2025-11-18
     */
    @Override
    public boolean updateCouponSingleQty(Integer id, Integer singleQty) {
        //判断库存数为0 增加库存数修改状态为进行中
        LambdaQueryWrapper<LifeCoupon> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(LifeCoupon :: getId, id);
        LifeCoupon lifeCoupon = lifeCouponMapper.selectOne(lambdaQueryWrapper);

        if(lifeCoupon.getSingleQty() == 0){
        LambdaUpdateWrapper<LifeCoupon> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(LifeCoupon :: getId, id);
        lambdaUpdateWrapper.set(LifeCoupon :: getSingleQty,singleQty);
        lambdaUpdateWrapper.set(LifeCoupon :: getStatus, 5);
        lifeCouponMapper.update(null, lambdaUpdateWrapper);
        }
        else{
            LambdaUpdateWrapper<LifeCoupon> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            lambdaUpdateWrapper.eq(LifeCoupon :: getId, id);
            lambdaUpdateWrapper.set(LifeCoupon :: getSingleQty,singleQty);
            lifeCouponMapper.update(null, lambdaUpdateWrapper);
        }

        return true;
    }

    /**
     * 删除优惠券
     * 通过设置删除标记实现软删除
     *
     * @param id 优惠券ID
     * @return boolean 删除是否成功
     * @author alien-cloud
     * @date 2025-11-18
     */
    @Override
    public boolean deleteCoupon(Integer id) {
        LambdaUpdateWrapper<LifeCoupon> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(LifeCoupon :: getId, id);
        lambdaUpdateWrapper.set(LifeCoupon :: getDeleteFlag, 1);
        lifeCouponMapper.update(null, lambdaUpdateWrapper);
        return true;
    }

    /**
     * 分页查询优惠券列表
     * 支持按门店、状态、名称、数据类型、审核状态等条件筛选
     * 包含销量统计、状态转换等业务逻辑
     *
     * @param page 页码
     * @param size 每页数量
     * @param storeId 门店ID
     * @param status 状态
     * @param name 优惠券名称
     * @return IPage<LifeCouponPlatformDto> 分页优惠券列表
     * @author alien-cloud
     * @date 2025-11-18
     */
    @Override
    public IPage<LifeCouponPlatformDto> getCouponList(int page, int size, String storeId, String status, String name) {

        LambdaUpdateWrapper<LifeCoupon> wrapper = new LambdaUpdateWrapper<>();
        if (status != null && !status.isEmpty() && status.equals("0")) {
            wrapper.eq(LifeCoupon::getDataType, 1);
        } else {
            wrapper.eq(status != null && !status.isEmpty(), LifeCoupon::getStatus, status);
        }

        wrapper.eq(storeId != null && !storeId.isEmpty(), LifeCoupon::getStoreId, storeId);
        wrapper.like(name != null && !name.isEmpty(), LifeCoupon::getName, name);
        wrapper.eq(LifeCoupon::getType, 1);
//        修改排序 按照status(0草稿/1待审核/2未开始/3审核拒绝/4已售罄/5进行中/6已下架/7已结束/8=2+手动下架）   审核拒绝>待审核>进行中>已售罄，已下架，已结束(同等优先级的情况下，按照审核时间的倒序显示)
        wrapper.last("ORDER BY CASE " +
                "WHEN status = 3 THEN 0 " +  // 审核拒绝
                "WHEN status = 1 THEN 1 " +  // 待审核
                "WHEN status = 5 THEN 2 " +  // 进行中
                "WHEN status IN (4, 6, 7) THEN 3 " +  // 已售罄、已下架、已结束
                "ELSE 4 END ASC, " +
                "created_time DESC");

        IPage<LifeCoupon> lifeCouponIPag = lifeCouponMapper.selectPage(new Page<>(page, size), wrapper);

        // 创建 LifeCouponPlatformDto 的分页对象
        IPage<LifeCouponPlatformDto> dto = new Page<>(page, size);

        // 将 lifeCouponIPag 中的数据复制到 dto 中
        // 复制分页信息
        dto.setPages(lifeCouponIPag.getPages());
        dto.setCurrent(lifeCouponIPag.getCurrent());
        dto.setSize(lifeCouponIPag.getSize());
        dto.setTotal(lifeCouponIPag.getTotal());

        // 复制记录列表，将 LifeCoupon 转换为 LifeCouponPlatformDto
        List<LifeCouponPlatformDto> dtoRecords = lifeCouponIPag.getRecords().stream().map(coupon -> {
            LifeCouponPlatformDto dtoRecord = new LifeCouponPlatformDto();
            // 使用 BeanUtils 复制相同属性
            org.springframework.beans.BeanUtils.copyProperties(coupon, dtoRecord);

            if (dtoRecord.getDataType() == 1) {
                dtoRecord.setSaleNum("");
                dtoRecord.setSingleQty(null);
            } else {
                dtoRecord.setSaleNum(lifeUserOrderMapper.countCouponByCouponId(coupon.getId()).toString());
            }


            if (coupon.getStatus() == 1) {
                if (coupon.getDataType() == 0) {
                    dtoRecord.setReviewType("待审核");
                }
            } else if (coupon.getStatus() == 2 || coupon.getStatus() == 4 || coupon.getStatus() == 5 || coupon.getStatus() == 6 || coupon.getStatus() == 7 ) {
                dtoRecord.setReviewType("审核通过");
            } else if (coupon.getStatus() == 3) {
                dtoRecord.setReviewType("审核拒绝");
            }

            if (Objects.nonNull(coupon.getStatus())) {
                switch (coupon.getStatus()) {
                    case 0:
                        dtoRecord.setStatusName("草稿");
                        break;
                    case 1:
                        dtoRecord.setStatusName("待审核");
                        break;
                    case 2:
                        dtoRecord.setStatusName("未开始");
                        break;
                    case 3:
                        dtoRecord.setStatusName("审核拒绝");
                        break;
                    case 4:
                        dtoRecord.setStatusName("已售罄");
                        break;
                    case 5:
                        dtoRecord.setStatusName("进行中");
                        break;
                    case 6:
                        dtoRecord.setStatusName("已下架");
                        break;
                    case 7:
                        dtoRecord.setStatusName("已结束");
                        break;
                    default:
                        dtoRecord.setStatusName("未知状态");
                        break;
                }
            }

            return dtoRecord;
        }).collect(Collectors.toList());

        dto.setRecords(dtoRecords);

        return dto;
    }

    @Override
    public IPage<LifeDiscountCouponVo> getCouponListAsDiscountVo(int page, int size, String storeId, String status, String name) {
        LambdaQueryWrapper<LifeCoupon> wrapper = new LambdaQueryWrapper<>();
        if (status != null && !status.isEmpty() && status.equals("0")) {
            wrapper.eq(LifeCoupon::getDataType, 1);
        } else {
            wrapper.eq(status != null && !status.isEmpty(), LifeCoupon::getStatus, status);
        }
        wrapper.eq(storeId != null && !storeId.isEmpty(), LifeCoupon::getStoreId, storeId);
        wrapper.like(name != null && !name.isEmpty(), LifeCoupon::getName, name);
        wrapper.eq(LifeCoupon::getType, 1);
        wrapper.last("ORDER BY CASE " +
                "WHEN status = 3 THEN 0 " +
                "WHEN status = 1 THEN 1 " +
                "WHEN status = 5 THEN 2 " +
                "WHEN status IN (4, 6, 7) THEN 3 " +
                "ELSE 4 END ASC, created_time DESC");

        IPage<LifeCoupon> lifeCouponIPage = lifeCouponMapper.selectPage(new Page<>(page, size), wrapper);
        IPage<LifeDiscountCouponVo> result = new Page<>(page, size);
        result.setPages(lifeCouponIPage.getPages());
        result.setCurrent(lifeCouponIPage.getCurrent());
        result.setSize(lifeCouponIPage.getSize());
        result.setTotal(lifeCouponIPage.getTotal());

        List<LifeDiscountCouponVo> voList = lifeCouponIPage.getRecords().stream().map(this::mapLifeCouponToDiscountVo).collect(Collectors.toList());
        result.setRecords(voList);
        return result;
    }

    /** 代金券转成与优惠券一致的结构（LifeDiscountCouponVo），type=4 */
    private LifeDiscountCouponVo mapLifeCouponToDiscountVo(LifeCoupon lc) {
        LifeDiscountCouponVo vo = new LifeDiscountCouponVo();
        // 代金券 id 统一从 life_coupon.id 返回：voucherId 必填（字符串），id/couponId 在为数字时一并返回便于前端与优惠券格式一致
        vo.setVoucherId(lc.getId());
        if (lc.getId() != null) {
            try {
                int numericId = Integer.parseInt(lc.getId());
                vo.setId(numericId);
                vo.setCouponId(numericId);
            } catch (NumberFormatException ignored) { }
        }
        vo.setStoreId(lc.getStoreId());
        vo.setName(lc.getName());
        vo.setType(lc.getType());
        vo.setSingleQty(lc.getSingleQty());
        if (lc.getPrice() != null) {
            try {
                vo.setNominalValue(new BigDecimal(lc.getPrice()));
            } catch (Exception ignored) { }
        }
        if (lc.getStartDate() != null) {
            vo.setStartDate(lc.getStartDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDate());
        }
        if (lc.getEndDate() != null) {
            vo.setEndDate(lc.getEndDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDate());
            vo.setValidDate(lc.getEndDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDate());
        }
        vo.setBeginGetDate(vo.getStartDate());
        vo.setEndGetDate(vo.getEndDate());
        vo.setCreatedTime(lc.getCreatedTime());
        vo.setCouponStatus(lc.getDataType() != null && lc.getDataType() == 0 ? 1 : 0);
        vo.setQuantityClaimed(0);
        if (lc.getStatus() != null) {
            switch (lc.getStatus()) {
                case 0:
                    vo.setStatus(5);
                    vo.setStatusDesc("草稿");
                    break;
                case 1:
                    vo.setStatus(2);
                    vo.setStatusDesc("待审核");
                    break;
                case 2:
                    vo.setStatus(2);
                    vo.setStatusDesc("未开始");
                    break;
                case 3:
                    vo.setStatus(3);
                    vo.setStatusDesc("审核拒绝");
                    break;
                case 4:
                    vo.setStatus(4);
                    vo.setStatusDesc("已售罄");
                    break;
                case 5:
                    vo.setStatus(0);
                    vo.setStatusDesc("进行中");
                    break;
                case 6:
                    vo.setStatus(3);
                    vo.setStatusDesc("已下架");
                    break;
                case 7:
                    vo.setStatus(1);
                    vo.setStatusDesc("已结束");
                    break;
                default:
                    vo.setStatus(null);
                    vo.setStatusDesc("未知状态");
                    break;
            }
        }
        vo.setLongTermValid(0);
        vo.setUnlimitedQty(0);
        return vo;
    }

    /**
     * 更新优惠券状态
     * 修改优惠券的状态，支持上架、下架等操作
     * 自动判断优惠券是否已结束
     *
     * @param id 优惠券ID
     * @param status 状态值
     * @return int 更新的记录数
     * @author alien-cloud
     * @date 2025-11-18
     */
    @Override
    public int updateCoupon(String id, Integer status) {
        LifeCoupon coupon = lifeCouponMapper.selectById(id);
        if (null == coupon) {
            throw new RuntimeException("该券不存在");
        }
        // 已结束
        if (LocalDate.now().isAfter(coupon.getEndDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDate())) {
            status = 7;
        }
        LifeCoupon lifeCoupon = new LifeCoupon();
        lifeCoupon.setId(id);
        lifeCoupon.setStatus(status);
        return lifeCouponMapper.updateById(lifeCoupon);
    }


    /**
     * 分页查询节假日列表
     * 支持按年份、开关状态、节假日名称筛选
     * 未指定年份时按年份分组查询，指定年份时查询该年份的详细节假日列表
     *
     * @param page 页码
     * @param size 每页数量
     * @param year 年份
     * @param openFlag 是否启用(0:未启用,1:已启用)
     * @param holidayName 节假日名称
     * @return IPage<EssentialHolidayComparison> 分页节假日列表
     * @author alien-cloud
     * @date 2025-11-18
     */
    @Override
    public IPage<EssentialHolidayComparison> getHolidayList(int page, int size, String year, String openFlag, String holidayName) {
        if (StringUtils.isEmpty(year)) {
            LambdaQueryWrapper<EssentialHolidayComparison> essentialHolidayComparisonLambdaQueryWrapper = new LambdaQueryWrapper<>();
            essentialHolidayComparisonLambdaQueryWrapper.eq(EssentialHolidayComparison::getDelFlag, 0).groupBy(EssentialHolidayComparison::getParticularYear).orderByDesc(EssentialHolidayComparison::getParticularYear);
            IPage<EssentialHolidayComparison> essentialHolidayComparisonIPage = new Page<>(page, size);
            return essentialHolidayComparisonMapper.selectPage(essentialHolidayComparisonIPage, essentialHolidayComparisonLambdaQueryWrapper);
        } else {
            LambdaQueryWrapper<EssentialHolidayComparison> essentialHolidayComparisonLambdaQueryWrapper = new LambdaQueryWrapper<>();
            essentialHolidayComparisonLambdaQueryWrapper.eq(EssentialHolidayComparison::getDelFlag, 0)
                    .eq(com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotEmpty(year), EssentialHolidayComparison::getParticularYear, year)
                    .eq(com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotEmpty(openFlag), EssentialHolidayComparison::getOpenFlag, openFlag)
                    .like(com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotEmpty(holidayName), EssentialHolidayComparison::getFestivalName, holidayName)
                    .orderByAsc(EssentialHolidayComparison::getStartTime);
            IPage<EssentialHolidayComparison> essentialHolidayComparisonIPage = new Page<>(page, size);
            return essentialHolidayComparisonMapper.selectPage(essentialHolidayComparisonIPage, essentialHolidayComparisonLambdaQueryWrapper);
        }
    }

    /**
     * 保存节假日信息
     * 新增或更新节假日配置，自动设置节假日日期
     *
     * @param essentialHolidayComparison 节假日对象
     * @return boolean 保存是否成功
     * @author alien-cloud
     * @date 2025-11-18
     */
    @Override
    public boolean saveHoliday(EssentialHolidayComparison essentialHolidayComparison) {
        if (ObjectUtils.isNotEmpty(essentialHolidayComparison.getId())) {
            if (ObjectUtils.isNotEmpty(essentialHolidayComparison.getStartTime())) {
                essentialHolidayComparison.setFestivalDate(essentialHolidayComparison.getStartTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate());
            }
            essentialHolidayComparisonMapper.updateById(essentialHolidayComparison);
            return true;
        } else {
            if (ObjectUtils.isNotEmpty(essentialHolidayComparison.getStartTime())) {
                essentialHolidayComparison.setFestivalDate(essentialHolidayComparison.getStartTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate());
            }
            essentialHolidayComparisonMapper.insert(essentialHolidayComparison);
            return true;
        }
    }

    /**
     * 删除节假日
     * 根据ID删除指定的节假日配置（软删除）
     *
     * @param id 节假日ID
     * @return boolean 删除是否成功
     * @author alien-cloud
     * @date 2025-11-18
     */
    @Override
    public boolean delHoliday(String id) {
        essentialHolidayComparisonMapper.update(null, new LambdaUpdateWrapper<EssentialHolidayComparison>().eq(EssentialHolidayComparison::getId, id).set(EssentialHolidayComparison::getDelFlag, 1));
        return true;
    }

    /**
     * 按年份删除节假日
     * 删除指定年份的所有节假日配置（软删除）
     *
     * @param year 年份
     * @return boolean 删除是否成功
     * @author alien-cloud
     * @date 2025-11-18
     */
    @Override
    public boolean delHolidayByYear(String year) {
        essentialHolidayComparisonMapper.update(null, new LambdaUpdateWrapper<EssentialHolidayComparison>().eq(EssentialHolidayComparison::getParticularYear, year).set(EssentialHolidayComparison::getDelFlag, 1));
        return true;
    }

    /**
     * 启用或禁用节假日
     * 切换指定节假日的开关状态（0-未启用，1-已启用）
     *
     * @param id 节假日ID
     * @return boolean 操作是否成功
     * @author alien-cloud
     * @date 2025-11-18
     */
    @Override
    public boolean openCloseHoliday(String id) {
        EssentialHolidayComparison essentialHolidayComparison = essentialHolidayComparisonMapper.selectById(id);
        if (essentialHolidayComparison.getOpenFlag() == 0) {
            essentialHolidayComparisonMapper.update(null, new LambdaUpdateWrapper<EssentialHolidayComparison>().eq(EssentialHolidayComparison::getId, id).set(EssentialHolidayComparison::getOpenFlag, 1));
        } else {
            essentialHolidayComparisonMapper.update(null, new LambdaUpdateWrapper<EssentialHolidayComparison>().eq(EssentialHolidayComparison::getId, id).set(EssentialHolidayComparison::getOpenFlag, 0));
        }
        return true;
    }

    /**
     * 判断当前日期是否在任意一个日期范围内
     * 用于验证优惠券或团购券的自定义不可用日期
     *
     * @param dateRanges 日期范围数组，格式为["yyyy-MM-dd,yyyy-MM-dd", ...]
     * @return boolean 当前日期是否在任意范围内
     * @author alien-cloud
     * @date 2025-11-18
     */
    public static boolean isCurrentDateInAnyRange(String[] dateRanges) {
        // 获取当前日期
        LocalDate currentDate = LocalDate.now();
        // 定义日期格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

        // 遍历数组中的每一对日期范围
        for (String range : dateRanges) {
            // 分割每一对日期（开始日期和结束日期）
            String[] dates = range.split(",");
            if (dates.length != 2) {
                // 格式不正确，跳过这一对
                continue;
            }
            try {
                // 解析开始日期和结束日期
                LocalDate startDate = LocalDate.parse(dates[0], formatter);
                LocalDate endDate = LocalDate.parse(dates[1], formatter);

                // 检查当前日期是否在范围内（包括开始和结束日期）
                if (!currentDate.isBefore(startDate) &&
                        !currentDate.isAfter(endDate)) {
                    return true;
                }
            } catch (Exception e) {
                // 日期解析错误，跳过这一对
                continue;
            }
        }
        // 没有任何一对日期范围包含当前日期
        return false;
    }

    /**
     * 团购券核销验证
     * 验证团购券的有效期、不可用日期（星期、节日、自定义日期）等
     *
     * @param orderCouponMiddle 订单优惠券中间表对象
     * @return R<String> 验证结果
     * @author alien-cloud
     * @date 2025-11-18
     */
    public R<String> groupVerification(OrderCouponMiddle orderCouponMiddle) {
        LifeGroupBuyMain lifeGroupBuyMain = lifeGroupBuyMainMapper.selectOne(new LambdaQueryWrapper<LifeGroupBuyMain>().eq(LifeGroupBuyMain::getId, orderCouponMiddle.getCouponId()));
        //团购有效期类型为:0 指定天数
        if (lifeGroupBuyMain.getEffectiveDateType() == 0) {
            //订单支付时间加上指定天数 为团购劵有效期
            LifeUserOrder lifeUserOrder = lifeUserOrderMapper.selectOne(new LambdaQueryWrapper<LifeUserOrder>().eq(LifeUserOrder::getId, orderCouponMiddle.getOrderId()));
            LocalDate localDate = lifeUserOrder.getPayTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
            LocalDate validityPeriod = localDate.plusDays(Long.parseLong(lifeGroupBuyMain.getEffectiveDateValue()));
            LocalDate nowDate = LocalDate.now(); // 获取当前时间
            if (nowDate.isAfter(validityPeriod)) {
                return R.fail("该劵不在有效期内");
            }
        } else if (lifeGroupBuyMain.getEffectiveDateType() == 1) {//类型为:1 指定时间段
            String[] strings = lifeGroupBuyMain.getEffectiveDateValue().split(",");
            String startDate = strings[0];
            String endDate = strings[1];
            LocalDate localStartDate = LocalDate.parse(startDate);
            LocalDate localEndDate = LocalDate.parse(endDate);
            LocalDate nowDate = LocalDate.now(); // 获取当前时间
            if (nowDate.isAfter(localEndDate) || nowDate.isBefore(localStartDate)) {
                return R.fail("该劵不在有效期内");
            }
        }
        //判断订单是否在不可用日期内
        //判断当前日期是否在不可用星期
        if (lifeGroupBuyMain.getDisableDateType() == 1) {//限制日期: 1234567;节日id
            LocalDate nowDate = LocalDate.now(); // 获取当前时间
            DayOfWeek dayOfWeek = nowDate.getDayOfWeek();
            String week = dayOfWeek.getDisplayName(TextStyle.FULL, Locale.CHINA);
            String beforeSemicolon = lifeGroupBuyMain.getDisableDateValue().split(";")[0];
            if (!StringUtils.isEmpty(beforeSemicolon)) {
                List<String> collectUnavailableDate = Arrays.stream(beforeSemicolon.split(",")).map(String::trim).collect(Collectors.toList());
                boolean isExist = collectUnavailableDate.stream().anyMatch(s -> s.equals(week));
                if (isExist) {
                    return R.fail("该劵在不可用日期内");
                }
            }
            //判断当前日期是否在不可用节日
            String[] strings = lifeGroupBuyMain.getDisableDateValue().split(";");
            if (strings.length > 1) {
                String afterSemicolon = lifeGroupBuyMain.getDisableDateValue().split(";")[1];
                List<String> collectUnavailableDate = Arrays.stream(afterSemicolon.split(",")).map(String::trim).collect(Collectors.toList());
                List<EssentialHolidayComparison> essentialHolidayComparisons = essentialHolidayComparisonMapper.
                        selectList(new LambdaQueryWrapper<EssentialHolidayComparison>().in(EssentialHolidayComparison::getId, collectUnavailableDate));
                boolean isExist = essentialHolidayComparisons.stream().anyMatch(s -> !nowDate.isBefore(s.getStartTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate())
                        && !nowDate.isAfter(s.getEndTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate()));
                if (isExist) {
                    return R.fail("该劵在不可用日期内");
                }
            }
        }
        //判断当前日期是否在自定义不可用日期内
        if (lifeGroupBuyMain.getDisableDateType() == 2) {
            String[] customDate = lifeGroupBuyMain.getDisableDateValue().split(";");
            boolean isExist = isCurrentDateInAnyRange(customDate);
            if (isExist) {
                return R.fail("该劵在不可用日期内");
            }
        }
        return R.success("效验通过");
    }

    /**
     * 代金券核销验证
     * 验证代金券的有效期、不可用日期（星期、节日、自定义日期）、使用时间段、单次核销数量等
     *
     * @param orderCouponMiddle 订单优惠券中间表对象
     * @return R<String> 验证结果
     * @author alien-cloud
     * @date 2025-11-18
     */
    public R<String> couponVerification(OrderCouponMiddle orderCouponMiddle) {
        LifeCoupon lifeCoupon = lifeCouponMapper.selectOne(new LambdaQueryWrapper<LifeCoupon>().eq(LifeCoupon::getId, orderCouponMiddle.getCouponId()));
        //代金券有效期类型为:1 指定天数
        if (lifeCoupon.getExpirationType().equals("1")) {
            //订单支付时间加上指定天数 为团购劵有效期
            LifeUserOrder lifeUserOrder = lifeUserOrderMapper.selectOne(new LambdaQueryWrapper<LifeUserOrder>().eq(LifeUserOrder::getId, orderCouponMiddle.getOrderId()));
            LocalDate localDate = lifeUserOrder.getPayTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
            LocalDate validityPeriod = localDate.plusDays(lifeCoupon.getExpirationDate());
            LocalDate nowDate = LocalDate.now(); // 获取当前时间
            if (nowDate.isAfter(validityPeriod)) {
                return R.fail("该劵不在有效期内");
            }
        } else if (lifeCoupon.getExpirationType().equals("2")) {//类型为:2 指定时间段
            String[] strings = lifeCoupon.getValidityPeriod().split(",");
            long start = Long.parseLong(strings[0]);
            long end = Long.parseLong(strings[1]);
            LocalDate startDate = Instant.ofEpochMilli(start)
                    .atZone(ZoneId.systemDefault())
                    .toLocalDate();
            LocalDate endDate = Instant.ofEpochMilli(end)
                    .atZone(ZoneId.systemDefault())
                    .toLocalDate();
            LocalDate nowDate = LocalDate.now(); // 获取当前时间
            if (nowDate.isAfter(endDate) || nowDate.isBefore(startDate)) {
                return R.fail("该劵不在有效期内");
            }
        }

        //判断代金券订单是否在不可用日期内
        //判断当前日期是否在不可用星期
        if (lifeCoupon.getUnusedType().equals("2")) {//限制日期: 1234567;节日id
            LocalDate nowDate = LocalDate.now(); // 获取当前时间
            DayOfWeek dayOfWeek = nowDate.getDayOfWeek();
            String week = dayOfWeek.getDisplayName(TextStyle.FULL, Locale.CHINA);
            String beforeSemicolon = lifeCoupon.getUnavaiLableDate().split(";")[0];
            if (!StringUtils.isEmpty(beforeSemicolon)) {
                List<String> collectUnavailableDate = Arrays.stream(beforeSemicolon.split(",")).map(String::trim).collect(Collectors.toList());
                boolean isExist = collectUnavailableDate.stream().anyMatch(s -> s.equals(week));
                if (isExist) {
                    return R.fail("该劵在不可用日期内");
                }
            }

            //判断当前日期是否在不可用节日
            String[] strings = lifeCoupon.getUnavaiLableDate().split(";");
            if (strings.length > 1) {
                String afterSemicolon = lifeCoupon.getUnavaiLableDate().split(";")[1];
                List<String> collectUnavailableDate = Arrays.stream(afterSemicolon.split(",")).map(String::trim).collect(Collectors.toList());
                List<EssentialHolidayComparison> essentialHolidayComparisons = essentialHolidayComparisonMapper.
                        selectList(new LambdaQueryWrapper<EssentialHolidayComparison>().in(EssentialHolidayComparison::getId, collectUnavailableDate));
                boolean isExist = essentialHolidayComparisons.stream().anyMatch(s -> !nowDate.isBefore(s.getStartTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate())
                        && !nowDate.isAfter(s.getEndTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate()));
                if (isExist) {
                    return R.fail("该劵在不可用日期内");
                }
            }
        }
        //判断当前日期是否在自定义不可用日期内
        if (lifeCoupon.getUnusedType().equals("3")) {
            String[] customDate = lifeCoupon.getUnavaiLableDate().split(";");
            boolean isExist = isCurrentDateInAnyRange(customDate);
            if (isExist) {
                return R.fail("该劵在不可用日期内");
            }
        }
    /*    //有效期到
        Date date = DateUtils.calcDays(orderCouponMiddle.getCreatedTime(), lifeCoupon.getExpirationDate());
        //开始时间段
        int beginUseTime = Integer.parseInt(lifeCoupon.getBuyUseStartTime());
        //结束时间段
        int endUseTime = Integer.parseInt(lifeCoupon.getBuyUseEndTime());
        if (new Date().after(date)) {
            return R.fail("该劵已过期");
        }
        if (endUseTime < beginUseTime) {
            if (!(LocalDateTime.now().getHour() >= beginUseTime || LocalDateTime.now().getHour() < endUseTime)) {
                return R.fail("该劵未到使用时间");
            }
        } else if (endUseTime > beginUseTime) {
            if (LocalDateTime.now().getHour() < beginUseTime || LocalDateTime.now().getHour() >= endUseTime) {
                return R.fail("该劵未到使用时间");
            }
        }*/
        // 判断是否在使用时间内
        Integer buyUseStartTime = Integer.parseInt(lifeCoupon.getBuyUseStartTime());
        Integer buyUseEndTime = Integer.parseInt(lifeCoupon.getBuyUseEndTime());
        // 获取当前小时
        LocalTime now = LocalTime.now();
        int currentHour = now.getHour();
        // 验证输入的小时是否有效
        if (buyUseStartTime < 0 || buyUseStartTime > 24 || buyUseEndTime < 0 || buyUseEndTime > 24) {
            return R.fail("小时必须在0-23之间");
        }
        // 处理跨天的情况，例如22点到次日3点
        if (buyUseStartTime >= buyUseEndTime) {
            if (currentHour < buyUseStartTime && currentHour > buyUseEndTime) {
                return R.fail("该劵不在有效期内");
            }

        } else {
            if (!(currentHour >= buyUseStartTime && currentHour <= buyUseEndTime)) {
                return R.fail("该劵不在有效期内");
            }
        }

        // 获取当天开始时间（00:00:00）
        LocalDateTime todayStart = LocalDateTime.of(LocalDate.now(), LocalTime.MIN);
        // 获取当天结束时间（23:59:59.999）
        LocalDateTime todayEnd = LocalDateTime.of(LocalDate.now(), LocalTime.MAX);
        if(!lifeCoupon.getSingleCanUse().equals("0")){
            Integer orderNum = orderCouponMiddleMapper.selectCount(new LambdaQueryWrapper<OrderCouponMiddle>()
                    .eq(OrderCouponMiddle :: getOrderId, orderCouponMiddle.getOrderId())
                    .between(OrderCouponMiddle :: getUsedTime,todayStart,todayEnd)
                    .eq(OrderCouponMiddle ::getStatus, 2)
            );
            if(orderNum >= Integer.parseInt(lifeCoupon.getSingleCanUse())){
                return R.fail("该订单已经超过今日单次核销数量");
            }
        }
        return R.success("效验通过");
    }

}
