package shop.alien.store.service.impl;

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.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import shop.alien.entity.store.*;
import shop.alien.entity.store.excelVo.StoreCouponStatusVo;
import shop.alien.entity.store.excelVo.util.ExcelGenerator;
import shop.alien.entity.store.vo.LifeCouponVo;
import shop.alien.entity.store.vo.LifeGroupBuyMainVo;
import shop.alien.mapper.*;
import shop.alien.store.service.PlatformStoreCouponService;
import shop.alien.util.ali.AliOSSUtil;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class PlatformStoreCouponServiceImpl implements PlatformStoreCouponService {

    private final PlatformStoreCouponMapper platformStoreCouponMapper;

    private final PlatformStoreLifeGroupBuyMainMapper platformStoreLifeGroupBuyMainMapper;

    private final StoreInfoMapper storeInfoMapper;

    private final StoreImgMapper storeImgMapper;

    private final EssentialHolidayComparisonMapper essentialHolidayComparisonMapper;

    private final LifeGroupBuyThaliMapper lifeGroupBuyThaliMapper;

    private final AliOSSUtil aliOSSUtil;

    private final WebAuditMapper webAuditMapper;

    List<LifeCouponVo> toExcel = new ArrayList<>();

    @Value("${spring.web.resources.excel-path}")
    private String excelPath;

    @Value("${spring.web.resources.excel-generate-path}")
    private String excelGeneratePath;

    @Override
    public IPage<LifeCouponVo> getCouponList(Integer page, Integer size, String storeName, String status, String createdTime, String phone, String type) {
        QueryWrapper<LifeCouponVo> wrapper = new QueryWrapper<>();
        wrapper.like(StringUtils.isNotEmpty(storeName), "store.store_name", storeName);
        wrapper.eq(StringUtils.isNotEmpty(status), "coupon.status", status);
        wrapper.eq(StringUtils.isNotEmpty(type), "coupon.type", type);
        wrapper.eq("coupon.delete_flag", 0);
        wrapper.eq("coupon.data_type", 0);
        wrapper.eq("store.delete_flag", 0);
        wrapper.eq("user.delete_flag", 0);
        wrapper.like(StringUtils.isNotEmpty(createdTime), "coupon.created_time", createdTime);
        wrapper.like(StringUtils.isNotEmpty(phone), "user.phone", phone);
        wrapper.isNotNull("coupon.status");
        wrapper.orderByDesc("coupon.created_time");
        IPage<LifeCouponVo> lifeCouponVo = platformStoreCouponMapper.getCouponList(new Page<>(page, size), wrapper);
        lifeCouponVo.getRecords().forEach(item -> {
            if (item.getStatus() == 1) {
                item.setStatusName("待审核");
            } else if (item.getStatus() == 3) {
                item.setStatusName("已拒绝");
            } else {
                item.setStatusName("已通过");
            }
            // expiredState 赋值逻辑（修正版）
            LocalDateTime now = LocalDateTime.now(); // 获取当前时间
            Date endDate = item.getEndDate();
            if (endDate != null) {
                LocalDateTime endDateTime = endDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
                // 核心逻辑：未过期时赋 0，已过期赋 1（与前端枚举定义一致）
                if (now.isBefore(endDateTime)) {
                    item.setExpiredState("0"); // 当前时间未超过 endDate → 未到期
                } else {
                    item.setExpiredState("1"); // 当前时间超过 endDate → 已到期
                }
            }
        });
        return lifeCouponVo;
    }

    @Override
    public IPage<LifeGroupBuyMainVo> getLifeGroupBuyMainList(Integer page, Integer size, String storeName, String status, String createdTime, String phone, String expiredState) {
        QueryWrapper<LifeGroupBuyMainVo> wrapper = new QueryWrapper<>();
        wrapper.like(StringUtils.isNotEmpty(storeName), "store.store_name", storeName);
        if (status == null || status.isEmpty()) {
            wrapper.in("life.status", 1, 2, 3, 4, 5, 6, 7);
        }
        if (status.equals("9")) {
            wrapper.in("life.status", 4, 5, 6, 7);
        } else {
            wrapper.eq(StringUtils.isNotEmpty(status), "life.status", status);
        }
        //0:套餐未过期 1:套餐已过期
        LocalDateTime nowDate = LocalDateTime.now(); // 获取当前时间
        if (expiredState != null) {
            if (expiredState.equals("0")) {
                wrapper.gt("life.end_time", nowDate);
            }
            if (expiredState.equals("1")) {
                wrapper.lt("life.end_time", nowDate);
            }
        }

        wrapper.eq("life.delete_flag", 0);
        wrapper.eq("store.delete_flag", 0);
        wrapper.eq("user.delete_flag", 0);
        wrapper.like(StringUtils.isNotEmpty(createdTime), "life.created_time", createdTime);
        wrapper.like(StringUtils.isNotEmpty(phone), "user.phone", phone);
        wrapper.orderByDesc("life.created_time");

        IPage<LifeGroupBuyMainVo> lifeGroupBuyMainList = platformStoreLifeGroupBuyMainMapper.getLifeGroupBuyMainList(new Page<>(page, size), wrapper);
        lifeGroupBuyMainList.getRecords().forEach(item -> {
// expiredState 赋值逻辑（修正版）
            LocalDateTime now = LocalDateTime.now(); // 获取当前时间
            Date endDate = item.getEndTime();
            if (endDate != null) {
                LocalDateTime endDateTime = endDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
                // 核心逻辑：未过期时赋 0，已过期赋 1（与前端枚举定义一致）
                if (now.isBefore(endDateTime)) {
                    item.setExpiredState("0"); // 当前时间未超过 endDate → 未到期
                } else {
                    item.setExpiredState("1"); // 当前时间超过 endDate → 已到期
                }
            }
        });
        return lifeGroupBuyMainList;
    }

    @Override
    public IPage<LifeCouponVo> getCouponStatusList(Integer page, Integer size, String status, String expiredState) {
        IPage<LifeCouponVo> iPage = new Page<>(page, size);
        QueryWrapper<LifeCouponVo> wrapper = new QueryWrapper<>();
        if ("-3".equals(status)) { // 已售罄（逻辑状态，状态为进行中但是余量为0的）
            wrapper.eq("coupon.status", "1");
            wrapper.eq("coupon.stock_qty", 0);
        } else if ("1".equals(status)) {
            wrapper.eq("coupon.status", "1");
            wrapper.ne("coupon.stock_qty", 0);
        } else if ("4".equals(status)) {
            wrapper.eq("coupon.status", "1");
            wrapper.gt("coupon.start_date", new Date());
        } else {
            if (StringUtils.isNotEmpty(status)) {
                wrapper.eq("coupon.status", status);
            }
        }
        wrapper.eq("coupon.delete_flag", 0);
        wrapper.eq("store.delete_flag", 0);
        wrapper.eq("user.delete_flag", 0);
        wrapper.eq("coupon.status_delete_flag", 0);
        wrapper.isNotNull("coupon.status");
        wrapper.orderByDesc("coupon.created_time");
        Date currentDate = new Date();
        if ("0".equals(expiredState)) {
            wrapper.ge("coupon.end_date", currentDate);
        } else if ("1".equals(expiredState)) {
            wrapper.lt("coupon.end_date", currentDate);
        }

        IPage<LifeCouponVo> lifeCouponVo = platformStoreCouponMapper.getCouponList(iPage, wrapper);
        List<LifeCouponVo> records = lifeCouponVo.getRecords();
        records.forEach(item -> {
//            if (item.getStatus() == -1) {
//                item.setStatusName("待审核");
//            } else if (item.getStatus() == -2) {
//                item.setStatusName("已驳回");
//            } else {
//                item.setStatusName("已通过");
//            }
            // expiredState 赋值逻辑（修正版）
            LocalDateTime now = LocalDateTime.now(); // 获取当前时间
            Date endDate = item.getEndDate(); // 假设 endDate 是 Date 类型
            if (endDate != null) {
                LocalDateTime endDateTime = endDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
                // 核心逻辑：未过期时赋 0，已过期赋 1（与前端枚举定义一致）
                if (now.isBefore(endDateTime)) {
                    item.setExpiredState("0"); // 当前时间未超过 endDate → 未到期
                } else {
                    item.setExpiredState("1"); // 当前时间超过 endDate → 已到期
                }
            }

            //判断是否售罄
            if (item.getStatus() == 1 && item.getStockQty() == 0) {
                item.setStatus(-3);
            }

            //判断是否为未开始
            if (item.getStatus() == 1 && item.getStartDate().after(new Date())) {
                item.setStatus(4);
            }
        });

        // 根据 expiredState 进行筛选
        if (StringUtils.isNotEmpty(expiredState)) {
            records = records.stream()
                    .filter(item -> expiredState.equals(item.getExpiredState()))
                    .collect(Collectors.toList());
            lifeCouponVo.setRecords(records);
        }

        toExcel = records;
        return lifeCouponVo;
    }

    @Override
    public LifeCouponVo getCouponById(Integer id) {
        return platformStoreCouponMapper.getCouponById(id);
    }

    @Override
    public int approvalCoupon(Integer id, Integer status, String comment, String type) {
        if (type.equals("1")) {
            LifeCoupon coupon = platformStoreCouponMapper.selectById(id);
            if (null == coupon) return 0;

            // 如果通过，且券有效时间在当前时间之前，则修改状态为进行中
            Date now = new Date();
            if (status == 2 && coupon.getStartDate().before(now) && coupon.getEndDate().after(now)) {
                status = 5;
            }
            coupon.setApprovalComments(comment);
            // 审核后开始
            if ("0".equals(coupon.getSaleTimeStrType())) {
                coupon.setStartDate(new Date());
                status = 5;
            }
            coupon.setStatus(status);
            coupon.setStartDate(now);
            // 将待办列表状态设置为已审核
            LambdaUpdateWrapper<WebAudit> wrapper = new LambdaUpdateWrapper<>();
            wrapper.eq(WebAudit::getCouponId, id);
            wrapper.set(WebAudit::getStatus, "1");
            webAuditMapper.update(null, wrapper);
            return platformStoreCouponMapper.updateById(coupon);
        } else {
            LifeGroupBuyMain lifeGroupBuyMain = platformStoreLifeGroupBuyMainMapper.selectById(id);
            if (null == lifeGroupBuyMain) return 0;
            lifeGroupBuyMain.setStatus(status);
            lifeGroupBuyMain.setApprovalComments(comment);
            // 审核通过后开始
            if (lifeGroupBuyMain.getStartTimeType() == 0 && lifeGroupBuyMain.getStatus() == 5) {
                lifeGroupBuyMain.setStartTimeValue(new Date());
            }

            //审核通过 开始时间是手动设置且不在当前时间内
            if (lifeGroupBuyMain.getStartTimeType() == 1 && lifeGroupBuyMain.getStatus() == 5 && lifeGroupBuyMain.getStartTimeValue().after(new Date())) {
                lifeGroupBuyMain.setStatus(2);
            }

            // 将待办列表状态设置为已审核
            LambdaUpdateWrapper<WebAudit> wrapper = new LambdaUpdateWrapper<>();
            wrapper.eq(WebAudit::getLifeGroupPackageId, id);
            wrapper.set(WebAudit::getStatus, "1");
            webAuditMapper.update(null, wrapper);
            return platformStoreLifeGroupBuyMainMapper.updateById(lifeGroupBuyMain);
        }
    }

    @Override
    public String couponStatusExport(String status, String expiredState) throws IOException {

        QueryWrapper<LifeCouponVo> wrapper = new QueryWrapper<>();
        // 定义允许的状态值
        List<String> allowedStatus = Arrays.asList("1", "2", "3");
//        wrapper.like(StringUtils.isNotEmpty(storeName), "store.store_name", storeName);
        if (StringUtils.isNotEmpty(status) && status.equals("-3")) {
            status = "1";
            wrapper.eq("coupon.single_qty", 0);
        }
        if (StringUtils.isNotEmpty(status) && allowedStatus.indexOf(status) != -1) {
            wrapper.eq(StringUtils.isNotEmpty(status), "coupon.status", status);
        } else {
            wrapper.in("coupon.status", allowedStatus);
        }
        wrapper.eq("coupon.delete_flag", 0);
        wrapper.eq("store.delete_flag", 0);
        wrapper.eq("user.delete_flag", 0);
        wrapper.eq("coupon.status_delete_flag", 0);
//        wrapper.like(StringUtils.isNotEmpty(createdTime),"coupon.created_time", createdTime);
//        wrapper.like(StringUtils.isNotEmpty(phone),"user.phone", phone);
        wrapper.isNotNull("coupon.status");
        wrapper.orderByDesc("coupon.created_time");

        Date currentDate = new Date();
        if ("0".equals(expiredState)) {
            wrapper.ge("coupon.end_date", currentDate);
        } else if ("1".equals(expiredState)) {
            wrapper.lt("coupon.end_date", currentDate);
        }

        List<LifeCouponVo> lifeCouponVo = platformStoreCouponMapper.getCouponListWithoutPage(wrapper);
        lifeCouponVo.forEach(item -> {
            if (item.getStatus() == 5 && item.getStockQty() > 0) {
                item.setCouponState("进行中");
            } else if (item.getStatus() == 5 && item.getStockQty() == 0) {
                item.setCouponState("已售罄");
            } else if (item.getStatus() == 6) {
                item.setCouponState("已暂停");
            } else if (item.getStatus() == 7) {
                item.setCouponState("已结束");
            }
            item.setCouponName(item.getName());
            Date startDate = item.getStartDate();
            Date endDate = item.getEndDate();
//            item.setCouponTime(startDate.toString() + "-" + endDate.toString());
            // expiredState 赋值逻辑（修正版）
            LocalDateTime now = LocalDateTime.now(); // 获取当前时间
//            Date endDate = item.getEndDate(); // 假设 endDate 是 Date 类型

            // 格式化日期
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            String formattedEndDate = "";
            if (endDate != null) {
                LocalDateTime endDateTime = endDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
                // 调整结束时间为前一天的23:59:59
                endDateTime = endDateTime.minusDays(1).withHour(23).withMinute(59).withSecond(59);
                formattedEndDate = endDateTime.format(formatter);

                // 核心逻辑：未过期时赋 0，已过期赋 1（与前端枚举定义一致）
                if (now.isBefore(endDateTime)) {
                    // 计算剩余天数
                    long remainingDays = ChronoUnit.DAYS.between(now, endDateTime);
                    item.setDaysToExpire(remainingDays + "天");
                    item.setExpiredState("未到期"); // 当前时间未超过 endDate → 未到期
                } else {
                    item.setDaysToExpire("0天");
                    item.setExpiredState("已到期"); // 当前时间超过 endDate → 已到期
                }
                // 将结束时间调整为前一秒
                endDateTime = endDateTime.minusSeconds(1);
            }

            if (startDate != null) {
                LocalDateTime startDateTime = startDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
                String formattedStartDate = startDateTime.format(formatter);
                item.setCouponTime(formattedStartDate + "-" + formattedEndDate);
            }
        });

        // 根据 expiredState 进行筛选
        if (StringUtils.isNotEmpty(expiredState)) {
            // 将前端传递的 "0"/"1" 转换为业务状态
            String targetState = "0".equals(expiredState) ? "未到期" : "已到期";

            // 筛选时增加空值判断，避免 NPE
            lifeCouponVo = lifeCouponVo.stream()
                    .filter(item -> {
                        String itemState = item.getExpiredState(); // 获取当前项的状态
                        return targetState.equals(itemState); // 严格匹配字符串
                    })
                    .collect(Collectors.toList());
        }
        List<StoreCouponStatusVo> storeCouponStatusVos = new ArrayList<>();
        int index = 1;
        for (LifeCouponVo record : lifeCouponVo) {
            StoreCouponStatusVo storeCouponStatusVo = new StoreCouponStatusVo();
            BeanUtils.copyProperties(record, storeCouponStatusVo);
            storeCouponStatusVo.setId(String.valueOf(index++)); // 设置序号
            storeCouponStatusVos.add(storeCouponStatusVo);
        }
        String fileName = UUID.randomUUID().toString().replace("-", "");
        String filePath = ExcelGenerator.generateExcel(excelPath + excelGeneratePath + fileName + ".xlsx", storeCouponStatusVos, StoreCouponStatusVo.class);
        String url = aliOSSUtil.uploadFile(new File(filePath), "excel/" + fileName + ".xlsx");
        return url;
    }

    @Override
    public String lifeGroupBuyMainStatusExport(String status, String expiredState) throws IOException {
        QueryWrapper<LifeGroupBuyMainVo> wrapper = new QueryWrapper<>();
        // 定义允许的状态值
        if (StringUtils.isEmpty(status)) {
            wrapper.in("life.status", 1, 2, 3, 4, 5, 6, 7);
        }
        if (status.equals("9")) {
            wrapper.in("life.status", 4, 5, 6, 7);
        } else {
            wrapper.eq(StringUtils.isNotEmpty(status), "life.status", status);
        }
        //0:套餐未过期 1:套餐已过期
        LocalDateTime nowDate = LocalDateTime.now(); // 获取当前时间
        if (expiredState != null) {
            if (expiredState.equals("0")) {
                wrapper.gt("life.end_time", nowDate);
            }
            if (expiredState.equals("1")) {
                wrapper.lt("life.end_time", nowDate);
            }
        }

        wrapper.eq("life.delete_flag", 0);
        wrapper.eq("store.delete_flag", 0);
        wrapper.eq("user.delete_flag", 0);

        wrapper.orderByDesc("life.created_time");

        List<LifeGroupBuyMainVo> lifeGroupBuyMainList = platformStoreLifeGroupBuyMainMapper.getLifeGroupBuyMainListWithoutPage(wrapper);
        lifeGroupBuyMainList.forEach(item -> {
            if (item.getStatus() == 1) {
                item.setCouponState("待审核");
            } else if (item.getStatus() == 2) {
                item.setCouponState("未开始");
            } else if (item.getStatus() == 3) {
                item.setCouponState("审核拒绝");
            } else if (item.getStatus() == 4 && item.getInventoryNum() == 0) {
                item.setCouponState("已售罄");
            } else if (item.getStatus() == 5 && item.getInventoryNum() > 0) {
                item.setCouponState("进行中");
            } else if (item.getStatus() == 6) {
                item.setCouponState("已下架");
            } else if (item.getStatus() == 7) {
                item.setCouponState("已结束");
            }
            item.setCouponName(item.getGroupName());
            Date startDate = item.getStartTimeValue();
            Date endDate = item.getEndTime();
            // expiredState 赋值逻辑（修正版）
            LocalDateTime now = LocalDateTime.now(); // 获取当前时间

            // 格式化日期
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            String formattedEndDate = "";
            if (endDate != null) {
                LocalDateTime endDateTime = endDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
                // 调整结束时间为前一天的23:59:59
                endDateTime = endDateTime.minusDays(1).withHour(23).withMinute(59).withSecond(59);
                formattedEndDate = endDateTime.format(formatter);

                // 核心逻辑：未过期时赋 0，已过期赋 1（与前端枚举定义一致）
                if (now.isBefore(endDateTime)) {
                    // 计算剩余天数
                    long remainingDays = ChronoUnit.DAYS.between(now, endDateTime);
                    item.setDaysToExpire(remainingDays + "天");
                    item.setExpiredState("未到期"); // 当前时间未超过 endDate → 未到期
                } else {
                    item.setDaysToExpire("0天");
                    item.setExpiredState("已到期"); // 当前时间超过 endDate → 已到期
                }
                // 将结束时间调整为前一秒
                endDateTime = endDateTime.minusSeconds(1);
            }

            if (startDate != null) {
                LocalDateTime startDateTime = startDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
                String formattedStartDate = startDateTime.format(formatter);
                item.setCouponTime(formattedStartDate + "-" + formattedEndDate);
            }
        });

        // 根据 expiredState 进行筛选
        if (StringUtils.isNotEmpty(expiredState)) {
            // 将前端传递的 "0"/"1" 转换为业务状态
            String targetState = "0".equals(expiredState) ? "未到期" : "已到期";

            // 筛选时增加空值判断，避免 NPE
            lifeGroupBuyMainList = lifeGroupBuyMainList.stream()
                    .filter(item -> {
                        String itemState = item.getExpiredState(); // 获取当前项的状态
                        return targetState.equals(itemState); // 严格匹配字符串
                    })
                    .collect(Collectors.toList());
        }
        List<StoreCouponStatusVo> storeCouponStatusVos = new ArrayList<>();
        int index = 1;
        for (LifeGroupBuyMainVo record : lifeGroupBuyMainList) {
            StoreCouponStatusVo storeCouponStatusVo = new StoreCouponStatusVo();
            BeanUtils.copyProperties(record, storeCouponStatusVo);
            storeCouponStatusVo.setId(String.valueOf(index++)); // 设置序号
            storeCouponStatusVos.add(storeCouponStatusVo);
        }
        String fileName = UUID.randomUUID().toString().replace("-", "");
        String filePath = ExcelGenerator.generateExcel(excelPath + excelGeneratePath + fileName + ".xlsx", storeCouponStatusVos, StoreCouponStatusVo.class);
        return aliOSSUtil.uploadFile(new File(filePath), "excel/" + fileName + ".xlsx");
    }

    @Override
    public int deleteCouponStatus(Integer id) {
        LifeCoupon lifeCoupon = new LifeCoupon();
        lifeCoupon.setId(String.valueOf(id));
        lifeCoupon.setStatusDeleteFlag(1);
        return platformStoreCouponMapper.deleteById(id);
    }

    @Override
    public LifeGroupBuyMainVo getLifeGroupBuyMainByDetail(Integer id) {
        LifeGroupBuyMainVo lifeGroupBuyMainVo = new LifeGroupBuyMainVo();
        LifeGroupBuyMain lifeGroupBuyMain = platformStoreLifeGroupBuyMainMapper.selectById(id);
        List<LifeGroupBuyThali> lifeGroupBuyThali = lifeGroupBuyThaliMapper.getLifeGroupBuyThaliList(new LambdaQueryWrapper<LifeGroupBuyThali>()
                .eq(LifeGroupBuyThali::getParentId, lifeGroupBuyMain.getId()).groupBy(LifeGroupBuyThali::getDetailId));
        lifeGroupBuyMainVo.setLifeGroupBuyThaliList(lifeGroupBuyThali);

        // 添加商户信息
        StoreInfo storeUser = storeInfoMapper.selectById(lifeGroupBuyMain.getStoreId());
        // 图片
        List<String> collect = Arrays.stream(lifeGroupBuyMain.getImageId().split(","))
                .map(String::trim)
                .collect(Collectors.toList());
        List<StoreImg> storeImgs = storeImgMapper.selectList(new LambdaQueryWrapper<StoreImg>().in(StoreImg::getId, collect));
        BeanUtils.copyProperties(lifeGroupBuyMain, lifeGroupBuyMainVo);
        lifeGroupBuyMainVo.setStoreName(storeUser.getStoreName());
        lifeGroupBuyMainVo.setStoreImgList(storeImgs);
        //0:套餐未过期 1:套餐已过期
        LocalDateTime nowDate = LocalDateTime.now(); // 获取当前时间

        // 格式化日期
        LocalDateTime endDateTime = lifeGroupBuyMainVo.getEndTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
        // 调整结束时间为前一天的23:59:59
        endDateTime = endDateTime.minusDays(1).withHour(23).withMinute(59).withSecond(59);
//            formattedEndDate = endDateTime.format(formatter);

        // 核心逻辑：未过期时赋 0，已过期赋 1（与前端枚举定义一致）
        if (nowDate.isBefore(endDateTime)) {
            // 计算剩余天数
            long remainingDays = ChronoUnit.DAYS.between(nowDate, endDateTime);
            lifeGroupBuyMainVo.setDaysToExpire(remainingDays + "天");
            lifeGroupBuyMainVo.setExpiredState("0"); // 当前时间未超过 endDate → 未到期
        } else {
            lifeGroupBuyMainVo.setDaysToExpire("0天");
            lifeGroupBuyMainVo.setExpiredState("1"); // 当前时间超过 endDate → 已到期
        }

        // 核心逻辑：未过期时赋 0，已过期赋 1（与前端枚举定义一致）
        if (nowDate.isBefore(endDateTime)) {
            // 计算剩余天数
            long remainingDays = ChronoUnit.DAYS.between(nowDate, endDateTime);
            lifeGroupBuyMainVo.setDaysToExpire(remainingDays + "天");
            lifeGroupBuyMainVo.setExpiredState("0"); // 当前时间未超过 endDate → 未到期
        } else {
            lifeGroupBuyMainVo.setDaysToExpire("0天");
            lifeGroupBuyMainVo.setExpiredState("1"); // 当前时间超过 endDate → 已到期
        }
        // 不可用日期
        if (lifeGroupBuyMainVo.getDisableDateType() == 1) {
            String[] split = lifeGroupBuyMain.getDisableDateValue().split(";");
            String afterSemicolon = split.length > 2 ? split[1] : split[0];
            if (StringUtils.isNotEmpty(afterSemicolon)) {
                List<String> collectUnavailableDate = Arrays.stream(afterSemicolon.split(",")).map(String::trim).collect(Collectors.toList());
                if (CollectionUtils.isNotEmpty(collectUnavailableDate)) {
                    List<EssentialHolidayComparison> essentialHolidayComparisons = essentialHolidayComparisonMapper.selectList(new LambdaQueryWrapper<EssentialHolidayComparison>().in(EssentialHolidayComparison::getId, collectUnavailableDate));
                    lifeGroupBuyMainVo.setEssentialHolidayComparisonList(essentialHolidayComparisons);
                }
            }
        }
        return lifeGroupBuyMainVo;
    }
}
