package com.ylx.point.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
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.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ylx.common.core.domain.model.WxLoginUser;
import com.ylx.common.exception.ServiceException;
import com.ylx.common.utils.DateUtils;
import com.ylx.common.utils.SecurityUtils;
import com.ylx.point.domain.*;
import com.ylx.point.domain.dto.*;
import com.ylx.point.domain.vo.*;
import com.ylx.point.enums.*;
import com.ylx.point.mapper.PointActivityMapper;
import com.ylx.point.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.*;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 积分活动主Service业务层处理
 *
 * @author wzj
 * @date 2026-03-25
 */
@Slf4j
@Service
public class PointActivityServiceImpl extends ServiceImpl<PointActivityMapper, PointActivity> implements IPointActivityService {
    @Resource
    private PointActivityMapper pointActivityMapper;
    @Resource
    private IPointActivityTaskService pointActivityTaskService;
    @Resource
    private IPointSignTaskService pointSignTaskService;
    @Resource
    private IPointSignRewardService pointSignRewardService;
    @Resource
    private IPointUserActivityTaskCompletionService pointUserActivityTaskCompletionService;
    @Resource
    private IPointActivityExpirePolicyService pointActivityExpirePolicyService;
    @Resource
    private IPointUserSignLogService pointUserSignLogService;
    @Resource
    private IPointUserSignStatusService pointUserSignStatusService;
    @Resource
    private IPointAccountService pointAccountService;

    private static final int BATCH_SIZE = 1000;

    private static final int TARGET_COUNT = 2;

    private static final String INVALID_EXPIRE_POLICY_TYPE_MESSAGE = "无效的过期策略类型";
    private static final String EXPIRE_DAYS_REQUIRED_MESSAGE = "过期天数不能为空";
    private static final String EXPIRE_YEAR_REQUIRED_MESSAGE = "过期年数不能为空";
    private static final String UPDATE_FAILED_MESSAGE = "更新积分活动过期策略失败";

    // 优先级顺序
    private static final List<Integer> PRIORITY_TYPES = Arrays.asList(
            PointActivityTypeEnum.NEW_USER_ACTIVITY.getCode(),
            PointActivityTypeEnum.DAILY_ACTIVITY.getCode(),
            PointActivityTypeEnum.MONTHLY_ACTIVITY.getCode()); // 新手, 每日, 每月


    @Override
    public Page<PointActivityPageVo> list(Page<PointActivity> page, PointActivityPageDTO dto) {
        LambdaQueryWrapper<PointActivity> queryWrapper = new LambdaQueryWrapper<>();
        if (ObjectUtil.isNotNull(dto.getActivityType())) {
            queryWrapper.eq(PointActivity::getActivityType, dto.getActivityType());
        }
        if (StrUtil.isNotEmpty(dto.getCityCode())) {
            queryWrapper.eq(PointActivity::getCityCode, dto.getCityCode());
        }
        if (ObjectUtil.isNotNull(dto.getStatus())) {
            queryWrapper.eq(PointActivity::getStatus, dto.getStatus());
        }
        if (ObjectUtil.isNotNull(dto.getStartTime()) && ObjectUtil.isNotNull(dto.getEndTime())) {
            queryWrapper.le(PointActivity::getStartTime, dto.getEndTime());
            queryWrapper.ge(PointActivity::getEndTime, dto.getStartTime());
        }
        queryWrapper.orderByDesc(PointActivity::getCreateTime)
                .orderByDesc(PointActivity::getSortOrder);
        Page<PointActivityPageVo> pageData = new Page<>();
        pageData.setSize(page.getSize());
        pageData.setCurrent(page.getCurrent());

        Page<PointActivity> pointActivityPage = pointActivityMapper.selectPage(page, queryWrapper);
        if (ObjectUtil.isNotNull(pointActivityPage) && CollectionUtil.isNotEmpty(pointActivityPage.getRecords())) {
            List<PointActivityPageVo> voList = pointActivityPage.getRecords().stream()
                    .map(this::convertToVo) // 抽取转换方法
                    .collect(Collectors.toList());
            pageData.setRecords(voList);
            pageData.setTotal(pointActivityPage.getTotal());
            pageData.setPages(pointActivityPage.getPages());
        }
        return pageData;
    }

    @Override
    public PointActivityDetailsVo<?> getDetailsInfo(Long id) {

        PointActivity pointActivity = this.pointActivityMapper.selectPointActivityById(id);
        if (ObjectUtil.isNull(pointActivity)) {
            throw new IllegalArgumentException("参数有误，活动不存在");
        }

        Integer activityType = pointActivity.getActivityType();
        if (PointActivityTypeEnum.SIGN_TASK.getCode().equals(activityType)) {
            PointSignTaskVo vo = this.pointSignTaskService.selectPointSignTaskByActivityId(pointActivity.getId());
            BeanUtil.copyProperties(pointActivity, vo);
            return PointActivityDetailsVo.of(activityType, vo);
        } else {
            PointActivityTaskVo vo = new PointActivityTaskVo();
            BeanUtil.copyProperties(pointActivity, vo);
            List<PointActivityTaskDTO> activityTaskList = this.pointActivityTaskService.selectPointActivityTaskByActivityId(pointActivity.getId());
            vo.setActivityTaskList(activityTaskList);
            return PointActivityDetailsVo.of(activityType, vo);
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(PointActivityDTO dto) {

        // 校验参数
        validateActivityDTO(dto);

        // 保存活动信息
        PointActivity entity = createActivityEntity(dto);
        saveActivity(entity);

        // 保存活动详情信息
        saveActivityDetails(dto, entity.getId());

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void edit(PointActivityDTO dto) {

        // 校验参数
        Long id = dto.getId();
        if (ObjectUtil.isNull(id)) {
            throw new IllegalArgumentException("活动主键id不能为空");
        }

        // 根据id获取活动详情
        PointActivity entity = this.pointActivityMapper.selectPointActivityById(id);
        if (ObjectUtil.isNull(entity)) {
            throw new IllegalArgumentException("参数有误，活动不存在");
        }

        // 校验活动状态
        if (PointActivityStatusEnum.IN_PROGRESS.getCode().equals(entity.getStatus())) {
            throw new ServiceException("活动进行中，不可编辑");
        }

        updateActivity(entity, dto);

        // 更新活动详情信息
        updateActivityDetails(dto, id);

    }

    @Override
    public PointActivityStatVo getStatInfo(Long id) {

        // 根据id获取活动详情
        PointActivity entity = this.pointActivityMapper.selectPointActivityById(id);
        if (ObjectUtil.isNull(entity)) {
            throw new IllegalArgumentException("参数有误，活动不存在");
        }

        PointActivityStatVo vo = new PointActivityStatVo();
        BeanUtil.copyProperties(entity, vo);

        // 数据总览
        PointActivityOverviewVO dataOverview = this.pointUserActivityTaskCompletionService.getPointActivityOverviewByActivityId(id);
        vo.setDataOverview(dataOverview);

        // 数据详情
        List<PointActivityTaskDetailVO> taskDetailList = pointActivityMapper.getTaskDetailListById(id);
        vo.setTaskDetailList(taskDetailList);

        return vo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void editValidity(PointActivityValidityDTO dto) {

        // 根据dto中activityType获取全部的活动list
        PointActivity pointActivity = new PointActivity();
        pointActivity.setActivityType(dto.getActivityType());
        List<PointActivity> activityList = pointActivityMapper.selectPointActivityList(pointActivity);

        // 根据类型获取积分活动过期策略表数据
        PointActivityExpirePolicy expirePolicy = pointActivityExpirePolicyService.selectPointActivityExpirePolicyByActivityType(dto.getActivityType());
        if (CollectionUtil.isEmpty(activityList)) {
            // 更新积分活动过期策略表
            this.saveOrUpdatePointActivityExpirePolicy(expirePolicy, dto);
        } else {
            // 判断活动list中只要有活动的状态为"进行中"，修改就失败
            boolean hasOngoingActivity = activityList.stream()
                    .anyMatch(activity -> PointActivityStatusEnum.IN_PROGRESS.getCode().equals(activity.getStatus()));
            if (hasOngoingActivity) {
                throw new ServiceException("存在进行中的活动，无法修改有效期");
            }
            // 更新积分活动过期策略表
            expirePolicy = this.saveOrUpdatePointActivityExpirePolicy(expirePolicy, dto);
            // 批量更新活动的有效期策略
            batchUpdateExpirePolicy(activityList, expirePolicy.getId());
        }

    }

    @Override
    public List<PointActivityValidityVo> validityDetails() {
        try {
            // 查询所有过期策略
            List<PointActivityExpirePolicy> expirePolicies = this.pointActivityExpirePolicyService.list();

            // 如果没有数据，返回空列表
            if (CollectionUtil.isEmpty(expirePolicies)) {
                log.debug("没有查询到积分活动过期策略数据");
                return Collections.emptyList();
            }

            // 转换为VO对象
            List<PointActivityValidityVo> result = expirePolicies.stream()
                    .map(this::convertToVo)
                    .collect(Collectors.toList());

            log.info("成功查询到 {} 条积分活动有效期详情", result.size());
            return result;
        } catch (Exception e) {
            log.error("查询积分活动有效期详情失败", e);
            throw new ServiceException("查询积分活动有效期详情失败");
        }
    }

    @Override
    public Integer selectTotalActiveTasks(String cityCode) {
        return pointActivityMapper.selectTotalActiveTasks(cityCode);
    }

    @Override
    public Page<UserPointActivityVo> getUserPointActivityList(Page<PointActivity> page, UserPointActivityPageDTO dto) {

        // 当前登录用户信息
        WxLoginUser wxLoginUser = getCurrentWxLoginUser();
        String openId = wxLoginUser.getCOpenid();
        dto.setOpenId(openId);
        Page<UserPointActivityVo> userPointActivityVoPage = pointActivityMapper.selectTaskWithProgress(page, dto);
        if (ObjectUtil.isNotNull(userPointActivityVoPage) && CollectionUtil.isNotEmpty(userPointActivityVoPage.getRecords())) {
            userPointActivityVoPage.getRecords().forEach(userPointActivityVo -> {
                String frequencyLimitValue = userPointActivityVo.getTriggerValue();
                // 2. 非空才走枚举匹配，为空直接设0
                String triggerValue = "0";
                if (StrUtil.isNotBlank(frequencyLimitValue)) {
                    // 3. 链式调用 + 空安全，避免NPE
                    triggerValue = Optional.ofNullable(TaskLimitTimesEnum.getByValue(frequencyLimitValue))
                            .map(TaskLimitTimesEnum::getTime)
                            .map(Object::toString)
                            .orElse("0");
                }
                userPointActivityVo.setTriggerValue(triggerValue);
            });
        }
        return userPointActivityVoPage;
    }

    @Override
    public List<UserPointActivityVo> activityList() {

        // 当前登录用户信息
        WxLoginUser wxLoginUser = getCurrentWxLoginUser();
        String openId = wxLoginUser.getCOpenid();

        List<UserPointActivityVo> resultList = new ArrayList<>();

        // 2. 按优先级遍历活动类型
        for (Integer activityType : PRIORITY_TYPES) {
            if (resultList.size() >= TARGET_COUNT) {
                break;
            }

            // 3. 查询该类型下 进行中 的任务
            List<PointActivityTask> taskList = pointActivityTaskService.selectTasksByActivityType(activityType);
            if (CollectionUtil.isEmpty(taskList)) {
                continue;
            }

            // 4. 批量查询用户完成记录
            List<Long> taskIds = taskList.stream().map(PointActivityTask::getId).collect(Collectors.toList());
            List<PointUserActivityTaskCompletion> completionList =
                    pointUserActivityTaskCompletionService.selectCompletionsByOpenIdAndTaskIds(openId, taskIds);

            Map<Long, PointUserActivityTaskCompletion> completionMap = completionList.stream()
                    .collect(Collectors.toMap(PointUserActivityTaskCompletion::getTaskId, c -> c));

            // 5. 对任务进行排序：未完成优先，创建时间正序
            taskList.sort((t1, t2) -> {
                PointUserActivityTaskCompletion comp1 = completionMap.get(t1.getId());
                PointUserActivityTaskCompletion comp2 = completionMap.get(t2.getId());

                // 判断是否已完成
                boolean isCompleted1 = comp1 != null;
                boolean isCompleted2 = comp2 != null;

                // 未完成优先
                if (isCompleted1 != isCompleted2) {
                    return isCompleted1 ? 1 : -1;
                }

                // 同一状态按创建时间正序排列
                if (t1.getCreateTime() != null && t2.getCreateTime() != null) {
                    return t1.getCreateTime().compareTo(t2.getCreateTime());
                }

                return 0;
            });

            // 6. 筛选任务并添加到结果列表
            for (PointActivityTask task : taskList) {
                if (resultList.size() >= TARGET_COUNT) break;

                PointUserActivityTaskCompletion completion = completionMap.get(task.getId());
                resultList.add(convertToVo(task, completion));
            }
        }

        return resultList.stream().limit(2).collect(Collectors.toList());

    }

    @Override
    public List<SignDayVo> getSignInfo(SignDTO dto) {
        // 1. 获取当前登录用户
        WxLoginUser wxLoginUser = getCurrentWxLoginUser();
        String openId = wxLoginUser.getCOpenid();

        // 2. 获取当前城市签到任务
        PointSignTask task = getEnabledTask(dto.getCityCode());
        if (ObjectUtil.isNull(task)) {
            throw new ServiceException("当前城市暂无签到活动");
        }
        Long taskId = task.getId();
        Long activityId = task.getActivityId();

        PointActivity activity = this.pointActivityMapper.selectPointActivityById(activityId);
        if (ObjectUtil.isNull(activity)) {
            throw new IllegalArgumentException("参数有误，活动不存在");
        }

        // 3. 基础配置
        ZoneId zoneId = ZoneId.of("Asia/Shanghai");
        LocalDate today = LocalDate.now(zoneId);
        int basePoints = task.getBasePoints() == null ? 0 : task.getBasePoints();

        LocalDate activityStartDate = activity.getStartTime() == null ? null
                : activity.getStartTime().toInstant().atZone(zoneId).toLocalDate();
        LocalDate activityEndDate = activity.getEndTime() == null ? null
                : activity.getEndTime().toInstant().atZone(zoneId).toLocalDate();
        boolean isPermanent = "1".equals(activity.getIsPermanent());

        // 4. 阶梯奖励配置（按配置顺序累加，勿按 continue_days 数值排序）
        List<PointSignReward> rewardList = listSignRewardsByTaskId(taskId);

        // 5. 用户当前连续天数（读接口不加锁）
        PointUserSignStatus status = pointUserSignStatusService.getOne(new LambdaQueryWrapper<PointUserSignStatus>()
                .eq(PointUserSignStatus::getOpenId, openId)
                .eq(PointUserSignStatus::getActivityId, activityId)
                .last("LIMIT 1"));
        int currentContinuousDays = (status == null || status.getCurrentContinuousDays() == null) ? 0 : status.getCurrentContinuousDays();
        // 今天是否已签到：直接让 DB 判断 DATE 是否为今天，避免 JDBC/时区导致的跨天偏移
        boolean signedToday = pointUserSignStatusService.count(new LambdaQueryWrapper<PointUserSignStatus>()
                .eq(PointUserSignStatus::getOpenId, openId)
                .eq(PointUserSignStatus::getActivityId, activityId)
                .apply("last_sign_date = CURDATE()")) > 0;

        // 6. 本周范围（周日-周六）
        DayOfWeek dayOfWeek = today.getDayOfWeek();
        int daysSinceSunday = (dayOfWeek.getValue() == 7) ? 0 : dayOfWeek.getValue();
        LocalDate weekStart = today.minusDays(daysSinceSunday);
        LocalDate weekEndExclusive = weekStart.plusDays(7);

        // 7. 本周签到日志（只取本周，避免历史污染）
        // 注意：历史数据里 PointUserSignLog.points 可能仅存“阶梯加成”(如 5/6/7)，
        // 面板展示需要按 continuousDays + 当前配置重算“基础分+阶梯累加”。
        Map<LocalDate, PointUserSignLog> signedLogMap = new HashMap<>();
        Date weekStartDate = Date.from(weekStart.atStartOfDay(zoneId).toInstant());
        Date weekEndDateExclusive = Date.from(weekEndExclusive.atStartOfDay(zoneId).toInstant());
        // 显式列名，避免字段映射差异导致过滤失效
        List<PointUserSignLog> signLogList = pointUserSignLogService.list(new LambdaQueryWrapper<PointUserSignLog>()
                .eq(PointUserSignLog::getOpenId, openId)
                .eq(PointUserSignLog::getTaskId, taskId)
                .ge(PointUserSignLog::getSignDate, weekStartDate)
                .lt(PointUserSignLog::getSignDate, weekEndDateExclusive));
        if (CollUtil.isNotEmpty(signLogList)) {
            for (PointUserSignLog log : signLogList) {
                if (log == null || log.getSignDate() == null) {
                    continue;
                }
                LocalDate signDate = log.getSignDate().toInstant().atZone(zoneId).toLocalDate();
                signedLogMap.put(signDate, log);
            }
        }
        boolean hasSignHistory = (status != null && status.getLastSignDate() != null) || CollUtil.isNotEmpty(signedLogMap);

        // 8. 生成 7 天面板数据
        List<SignDayVo> voList = new ArrayList<>(7);
        // 面板口径：今天未签到时，今天永远按“连续第 1 天”预估
        int virtualTodayContinuousDays = signedToday ? currentContinuousDays : 1;
        int nextContinuousDays = virtualTodayContinuousDays + 1;

        for (int i = 0; i < 7; i++) {
            LocalDate date = weekStart.plusDays(i);
            PointUserSignLog signedLog = signedLogMap.get(date);
            // 今天是否已签，以状态表为准（更权威且是 date 类型）
            boolean signed = date.equals(today) ? signedToday : signedLog != null;

            SignDayVo vo = new SignDayVo();
            vo.setDate(date);

            // 8.1 活动有效性校验：不在活动时间范围内，直接过期（status=4）
            if ((activityStartDate != null && date.isBefore(activityStartDate))
                    || (!isPermanent && activityEndDate != null && date.isAfter(activityEndDate))) {
                vo.setStatus(4);
                vo.setPoints(basePoints);
                voList.add(vo);
                continue;
            }

            // 8.2 状态计算
            if (signed) {
                vo.setStatus(1);
            } else if (date.equals(today)) {
                vo.setStatus(2);
            } else if (date.isAfter(today)) {
                vo.setStatus(0);
            } else {
                // 过去未签：只有“存在历史签到”的情况下，昨天才算断签(3)；否则一律过期(4)
                vo.setStatus(hasSignHistory && date.equals(today.minusDays(1)) ? 3 : 4);
            }

            // 8.3 积分计算（基础分 + 阶梯累加）
            int points;
            if (vo.getStatus() == 1) {
                Integer continuousDays = (signedLog == null) ? null : signedLog.getContinuousDays();
                // 优先按连续天数重算（兼容旧数据 points=5/6/7 的情况）
                if (continuousDays != null) {
                    points = calcCumulativeSignPoints(basePoints, continuousDays, rewardList);
                } else if (signedLog != null && signedLog.getPoints() != null) {
                    // 兜底：如果日志里就是实际发放值（新数据），则直接回显
                    points = signedLog.getPoints();
                } else if (date.equals(today) && signedToday) {
                    // 今天已签但本周日志未查到（极端情况）：用状态表连续天数兜底
                    points = calcCumulativeSignPoints(basePoints, currentContinuousDays, rewardList);
                } else {
                    points = basePoints;
                }
            } else if (vo.getStatus() == 2) {
                points = calcCumulativeSignPoints(basePoints, virtualTodayContinuousDays, rewardList);
            } else if (vo.getStatus() == 0) {
                points = calcCumulativeSignPoints(basePoints, nextContinuousDays, rewardList);
                nextContinuousDays++;
            } else {
                // 断签/过期：展示基础分
                points = basePoints;
            }

            vo.setPoints(points);
            voList.add(vo);
        }

        return voList;
    }

    /**
     * 按任务 ID 查询阶梯奖励，并按 sort_order / id 保持后台配置顺序。
     * continue_days 为“本档再连续 N 天”，不能按数值升序排序（如 3 天档后接 2 天档时 2<3 会算错）。
     */
    private List<PointSignReward> listSignRewardsByTaskId(Long taskId) {
        List<PointSignReward> rewardList = pointSignRewardService.list(new LambdaQueryWrapper<PointSignReward>()
                .eq(PointSignReward::getSignTaskId, taskId)
                .eq(PointSignReward::getIsDeleted, 0));
        if (CollUtil.isEmpty(rewardList)) {
            return rewardList;
        }
        rewardList.sort(Comparator
                .comparing((PointSignReward r) -> r.getSortOrder() == null ? Long.MAX_VALUE : r.getSortOrder())
                .thenComparing(r -> r.getId() == null ? Long.MAX_VALUE : r.getId()));
        return rewardList;
    }

    /**
     * 签到积分计算：基础分 + 阶梯奖励累加
     * <p>
     * rewardList 须为后台配置顺序；每档 continueDays 表示“本档再连续签到 N 天”，累计阈值为各档之和。
     * 例如配置 3 天 +1、再 2 天 +2，阈值为 3、(3+2)=5。
     * <p>
     * 连续满某档后的下一次签到起生效：continuousDays > threshold 时加上该档 rewardPoints。
     */
    private int calcCumulativeSignPoints(int basePoints, int continuousDays, List<PointSignReward> rewardList) {
        int total = Math.max(basePoints, 0);
        if (continuousDays <= 0 || CollUtil.isEmpty(rewardList)) {
            return total;
        }
        int threshold = 0;
        for (PointSignReward reward : rewardList) {
            if (reward == null || reward.getContinueDays() == null || reward.getRewardPoints() == null) {
                continue;
            }
            threshold += reward.getContinueDays();
            if (continuousDays > threshold) {
                total += reward.getRewardPoints();
            }
        }
        return total;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void sign(SignDTO dto) {
        // 1. 用户登录校验
        WxLoginUser wxLoginUser = getCurrentWxLoginUser();
        String openId = wxLoginUser.getCOpenid();

        // 2. 获取有效签到任务
        PointSignTask task = getEnabledTask(dto.getCityCode());
        if (ObjectUtil.isNull(task)) {
            throw new ServiceException("当前城市暂无签到活动");
        }
        Long activityId = task.getActivityId();
        Long taskId = task.getId();
        String activityName = task.getActivityName();
        Integer taskType = ActivityCompletionTaskTypeEnum.SIGN.getCode();

        // ======================== 核心：统一使用任务完成表防重 ========================
        boolean todaySigned = pointUserActivityTaskCompletionService.isTodayCompleted(openId, activityId, taskId, taskType);
        if (todaySigned) {
            throw new ServiceException("今日已签到");
        }

        // 3. 悲观锁获取用户签到状态（并发安全）
        PointUserSignStatus status = pointUserSignStatusService.selectByOpenIdAndActivityIdForUpdate(openId, activityId);
        Date todayDate = DateUtil.date();
        Date yesterdayDate = DateUtil.yesterday();
        int newContinuousDays;

        if (ObjectUtil.isNull(status)) {
            // 首次签到
            newContinuousDays = 1;
            status = new PointUserSignStatus();
            status.setOpenId(openId);
            status.setActivityId(activityId);
            status.setLastSignDate(todayDate);
            status.setCurrentContinuousDays(newContinuousDays);
            status.setLastRewardCycleDays(0);
            pointUserSignStatusService.save(status);
        } else {
            // 计算连续天数（修复断签逻辑）
            boolean isContinue = DateUtil.isSameDay(status.getLastSignDate(), yesterdayDate);
            if (isContinue) {
                newContinuousDays = status.getCurrentContinuousDays() + 1;
            } else {
                // 断签规则：0重置 1保留
                newContinuousDays = task.getBreakRule() == 0 ? 1 : status.getCurrentContinuousDays();
            }

            status.setLastSignDate(todayDate);
            status.setCurrentContinuousDays(newContinuousDays);
            pointUserSignStatusService.updateById(status);
        }

        // 4. 计算奖励积分（基础分 + 阶梯奖励累加）
        int basePoints = task.getBasePoints() == null ? 0 : task.getBasePoints();
        List<PointSignReward> rewardList = listSignRewardsByTaskId(taskId);
        int rewardPoints = calcCumulativeSignPoints(basePoints, newContinuousDays, rewardList);

        // 5. 写入签到流水
        PointUserSignLog signLog = new PointUserSignLog();
        signLog.setOpenId(openId);
        signLog.setActivityId(activityId);
        signLog.setTaskId(taskId);
        signLog.setSignDate(todayDate);
        signLog.setContinuousDays(newContinuousDays);
        signLog.setPoints(rewardPoints);
        signLog.setIsMakeUp(0);
        pointUserSignLogService.save(signLog);

        // ======================== 统一记录任务完成（必须放在这里，事务内） ========================
        pointUserActivityTaskCompletionService.completeTask(openId, activityId, taskId, taskType);

        // 6. 发放积分
        try {
            pointAccountService.addPoints(openId, rewardPoints, activityName, null, activityId, taskId, taskType, TaskNameEnum.USER_SIGN_IN.name());
        } catch (Exception e) {
            log.error("签到发放积分异常 openid:{}", openId, e);
            throw new ServiceException("签到成功，但积分发放失败，请联系客服");
        }
    }

    /**
     * 组装 VO 对象
     */
    private UserPointActivityVo convertToVo(PointActivityTask task, PointUserActivityTaskCompletion completion) {
        UserPointActivityVo vo = new UserPointActivityVo();

        vo.setActivityId(task.getActivityId());
        vo.setTaskId(task.getId().toString());
        vo.setTaskName(task.getTaskName()); // 或者是从字典表查出的中文名称
        vo.setRewardPoints(task.getRewardPoints());

        // 完成次数：如果没有记录则为 "0"
        vo.setCompletedCount(completion != null ? String.valueOf(completion.getCompletedCount()) : "0");

        // 触发条件：直接从任务配置中获取，或者根据 taskCode 查字典
        // 1. 获取值 + 统一判空
        String frequencyLimitValue = task.getFrequencyLimitValue();
        // 2. 非空才走枚举匹配，为空直接设0
        String triggerValue = "0";
        if (StrUtil.isNotBlank(frequencyLimitValue)) {
            // 3. 链式调用 + 空安全，避免NPE
            triggerValue = Optional.ofNullable(TaskLimitTimesEnum.getByValue(frequencyLimitValue))
                    .map(TaskLimitTimesEnum::getTime)
                    .map(Object::toString)
                    .orElse("0");
        }
        vo.setTriggerValue(triggerValue);

        return vo;
    }

    private PointActivityValidityVo convertToVo(PointActivityExpirePolicy policy) {
        PointActivityValidityVo vo = new PointActivityValidityVo();
        BeanUtil.copyProperties(policy, vo);
        // 可以在这里添加额外的转换逻辑
        return vo;
    }

    private void validateActivityDTO(PointActivityDTO dto) {
        if (ObjectUtil.isNull(dto)) {
            throw new ServiceException("活动信息不能为空");
        }

        PointActivityDTO.ActivityTimeConfig timeConfig = dto.getTimeConfig();
        if (ObjectUtil.isNull(timeConfig) || (StrUtil.equals(timeConfig.getIsPermanent(), "0") &&
                (ObjectUtil.isNull(timeConfig.getStartTime()) || ObjectUtil.isNull(timeConfig.getEndTime())))) {
            throw new ServiceException("活动时间配置不能为空");
        }

        // 检查是否为签到活动
        if (PointActivityTypeEnum.SIGN_TASK.getCode().equals(dto.getActivityType())) {
            // 检查该城市是否已存在进行中的签到活动
            checkExistingSignInActivity(dto.getCityCode());
        }
    }

    /**
     * 检查指定城市是否已存在进行中的签到活动
     *
     * @param cityCode 城市代码
     */
    private void checkExistingSignInActivity(String cityCode) {
        // 构建查询条件：活动类型为签到任务，状态为进行中，城市代码匹配
        LambdaQueryWrapper<PointActivity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PointActivity::getActivityType, PointActivityTypeEnum.SIGN_TASK.getCode())
                .eq(PointActivity::getStatus, PointActivityStatusEnum.IN_PROGRESS.getCode())
                .eq(PointActivity::getCityCode, cityCode);

        // 查询是否存在符合条件的活动
        long count = this.count(queryWrapper);
        if (count > 0) {
            throw new ServiceException("该城市已存在进行中的签到活动，不能再次创建");
        }
    }

    private PointActivity createActivityEntity(PointActivityDTO dto) {

        // 创建基础实体
        PointActivity entity = new PointActivity();
        BeanUtil.copyProperties(dto, entity);

        // 处理时间配置
        PointActivityDTO.ActivityTimeConfig timeConfig = dto.getTimeConfig();
        entity.setIsPermanent(timeConfig.getIsPermanent());
        // 添加对活动时间的校验
        if (ObjectUtil.isNotEmpty(timeConfig.getStartTime())) {
            entity.setStartTime(DateUtil.beginOfDay(timeConfig.getStartTime()));
        }
        if (ObjectUtil.isNotEmpty(timeConfig.getEndTime())) {
            entity.setEndTime(processEndTime(timeConfig.getEndTime()));
        }

        // 处理状态
        if (PointActivityStatusEnum.PUBLISHED.getCode().equals(dto.getStatus())) {
            entity.setStatus(determineActivityStatus(
                    entity.getStartTime(),
                    entity.getEndTime(),
                    timeConfig.getIsPermanent()
            ));
        }

        return entity;
    }

    private void saveActivity(PointActivity entity) {
        entity.setCreateBy(SecurityUtils.getUsername());
        entity.setCreateTime(new Date());
        int affectedRows = pointActivityMapper.insertPointActivity(entity);
        if (affectedRows <= 0) {
            throw new ServiceException("保存积分活动失败");
        }
    }

    private PointActivityExpirePolicy saveOrUpdatePointActivityExpirePolicy(PointActivityExpirePolicy expirePolicy, PointActivityValidityDTO dto) {

        // 参数校验
        if (ObjectUtil.isNull(dto)) {
            throw new IllegalArgumentException("参数不能为空");
        }


        // 根据expirePolicy类型设置对应的过期时间
        Integer expirePolicyCode = dto.getExpirePolicy();
        if (ObjectUtil.isNull(expirePolicyCode)) {
            throw new IllegalArgumentException("过期策略类型不能为空");
        }

        // 准备要保存或更新的实体
        PointActivityExpirePolicy entity = expirePolicy != null ? expirePolicy : new PointActivityExpirePolicy();

        // 设置基本信息
        entity.setActivityType(dto.getActivityType());
        entity.setExpirePolicy(dto.getExpirePolicy());

        // 根据过期策略类型设置对应的过期时间
        setExpireTimeByPolicyType(entity, dto, expirePolicyCode);

        // 保存或更新
        return saveOrUpdateExpirePolicy(entity, dto.getActivityType());
    }

    private void setExpireTimeByPolicyType(PointActivityExpirePolicy entity, PointActivityValidityDTO dto, Integer expirePolicyCode) {
        // 先清空所有过期时间字段
        entity.setExpireDays(null);
        entity.setExpireYear(null);

        // 根据策略类型设置对应的过期时间
        switch (expirePolicyCode) {
            case 1: // PERMANENT_VALID - 永久有效
                // 已经清空了过期天数和年数，无需额外操作
                break;
            case 2: // TRANSACTION_EXPIRE - 按交易过期
                if (dto.getExpireDays() == null) {
                    throw new IllegalArgumentException(EXPIRE_DAYS_REQUIRED_MESSAGE);
                }
                entity.setExpireDays(dto.getExpireDays());
                break;
            case 3: // YEARLY_EXPIRE - 按年过期
                if (dto.getExpireYear() == null) {
                    throw new IllegalArgumentException(EXPIRE_YEAR_REQUIRED_MESSAGE);
                }
                entity.setExpireYear(dto.getExpireYear());
                break;
            default:
                throw new IllegalArgumentException(INVALID_EXPIRE_POLICY_TYPE_MESSAGE);
        }
    }

    private PointActivityExpirePolicy saveOrUpdateExpirePolicy(PointActivityExpirePolicy entity, Integer activityType) {
        try {
            entity.setUpdateBy(SecurityUtils.getUsername());
            entity.setUpdateTime(DateUtils.getNowDate());
            boolean isSuccess = pointActivityExpirePolicyService.saveOrUpdate(entity);
            if (!isSuccess) {
                log.error("保存或更新积分活动过期策略失败, activityType: {}", activityType);
                throw new ServiceException(UPDATE_FAILED_MESSAGE);
            }
            return entity;
        } catch (Exception e) {
            log.error("保存或更新积分活动过期策略时发生异常, activityType: {}", activityType, e);
            throw new ServiceException(UPDATE_FAILED_MESSAGE);
        }
    }

    private void saveActivityDetails(PointActivityDTO dto, Long activityId) {
        if (PointActivityTypeEnum.SIGN_TASK.getCode().equals(dto.getActivityType())) {
            saveSignTaskDetails(dto, activityId);
        } else {
            saveActivityTaskDetails(dto, activityId);
        }
    }

    private void updateActivityDetails(PointActivityDTO dto, Long activityId) {
        if (PointActivityTypeEnum.SIGN_TASK.getCode().equals(dto.getActivityType())) {
            updateSignTaskDetails(dto, activityId);
        } else {
            updateActivityTaskDetails(dto, activityId);
        }
    }

    private void updateActivity(PointActivity entity, PointActivityDTO dto) {
        // 更新活动信息
        BeanUtil.copyProperties(dto, entity);

        // 处理时间配置
        PointActivityDTO.ActivityTimeConfig timeConfig = dto.getTimeConfig();
        if (timeConfig != null) {
            entity.setStartTime(DateUtil.beginOfDay(timeConfig.getStartTime()));
            entity.setEndTime(processEndTime(timeConfig.getEndTime()));
            entity.setIsPermanent(timeConfig.getIsPermanent());
        }

        // 处理状态
        if (PointActivityStatusEnum.PUBLISHED.getCode().equals(dto.getStatus())) {
            entity.setStatus(determineActivityStatus(
                    entity.getStartTime(),
                    entity.getEndTime(),
                    timeConfig.getIsPermanent()
            ));
        }

        entity.setUpdateBy(SecurityUtils.getUsername());
        entity.setUpdateTime(DateUtils.getNowDate());

        int affectedRows = pointActivityMapper.updatePointActivity(entity);
        if (affectedRows <= 0) {
            throw new ServiceException("更新积分活动失败");
        }
    }

    private void saveSignTaskDetails(PointActivityDTO dto, Long activityId) {
        PointSignTaskDTO signTaskDTO = dto.getSignTaskDTO();
        if (ObjectUtil.isNull(signTaskDTO)) {
            throw new ServiceException("签到任务配置不能为空");
        }

        PointSignTask pointSignTask = new PointSignTask();
        pointSignTask.setActivityId(activityId);
        pointSignTask.setBasePoints(signTaskDTO.getBasePoints());
        pointSignTask.setBreakRule(signTaskDTO.getBreakRule());
        int affectedRows = pointSignTaskService.insertPointSignTask(pointSignTask);
        if (affectedRows <= 0) {
            throw new ServiceException("保存积分签到任务规则失败");
        }

        saveSignRewards(signTaskDTO.getSignRewardList(), pointSignTask.getId());
    }

    private void saveSignRewards(List<PointSignRewardDTO> rewardList, Long taskId) {
        if (CollectionUtil.isEmpty(rewardList)) {
            return;
        }

        List<PointSignReward> rewards = new ArrayList<>(rewardList.size());
        for (int i = 0; i < rewardList.size(); i++) {
            PointSignRewardDTO dto = rewardList.get(i);
            PointSignReward reward = new PointSignReward();
            reward.setRewardPoints(dto.getRewardPoints());
            reward.setContinueDays(dto.getContinueDays());
            reward.setSortOrder((long) i);
            reward.setCreateBy(SecurityUtils.getUsername());
            reward.setCreateTime(DateUtils.getNowDate());
            reward.setUpdateTime(reward.getCreateTime());
            reward.setIsDeleted(0);
            reward.setSignTaskId(taskId);
            rewards.add(reward);
        }

        pointSignRewardService.batchInsertPointSignReward(rewards);
    }

    private void saveActivityTaskDetails(PointActivityDTO dto, Long activityId) {
        List<PointActivityTaskDTO> tasks = dto.getTasks();
        if (CollectionUtil.isEmpty(tasks)) {
            return;
        }

        List<PointActivityTask> activityTasks = tasks.stream()
                .map(task -> {
                    PointActivityTask activityTask = new PointActivityTask();
                    BeanUtil.copyProperties(task, activityTask);
                    activityTask.setActivityId(activityId);
                    activityTask.setIsDeleted(0);
                    activityTask.setCreateBy(SecurityUtils.getUsername());
                    activityTask.setCreateTime(DateUtils.getNowDate());
                    activityTask.setUpdateTime(activityTask.getCreateTime());
                    return activityTask;
                })
                .collect(Collectors.toList());

        pointActivityTaskService.batchInsertPointActivityTask(activityTasks);
    }

    /**
     * 处理结束时间，设置为当天的23:59:59
     */
    private Date processEndTime(Date endTime) {
        if (endTime == null) {
            return null;
        }

        try {
            LocalDateTime localDateTime = LocalDateTime.ofInstant(
                    endTime.toInstant(),
                    ZoneId.systemDefault()
            );
            LocalDateTime endOfDay = localDateTime.with(
                    LocalTime.of(23, 59, 59));
            return Date.from(endOfDay.atZone(ZoneId.systemDefault()).toInstant());
        } catch (DateTimeException e) {
            throw new IllegalArgumentException("Invalid end time", e);
        }
    }

    /**
     * 确定活动状态
     */
    private Integer determineActivityStatus(Date startTime, Date endTime, String isPermanent) {
        if (StrUtil.equals(isPermanent, "1")) {
            return PointActivityStatusEnum.IN_PROGRESS.getCode();
        }

        Date now = DateUtils.getNowDate();
        if (startTime.after(now)) {
            return PointActivityStatusEnum.NOT_START.getCode();
        } else if (endTime != null && endTime.before(now)) {
            return PointActivityStatusEnum.FINISHED.getCode();
        } else {
            return PointActivityStatusEnum.IN_PROGRESS.getCode();
        }
    }

    /**
     * 更新签到任务详情
     */
    private void updateSignTaskDetails(PointActivityDTO dto, Long activityId) {
        PointSignTaskDTO signTaskDTO = dto.getSignTaskDTO();
        if (ObjectUtil.isNull(signTaskDTO)) {
            throw new ServiceException("签到任务配置不能为空");
        }

        // 获取现有的签到任务
        PointSignTaskVo existingTask = pointSignTaskService.selectPointSignTaskByActivityId(activityId);

        // 更新签到任务基本信息
        PointSignTask pointSignTask = new PointSignTask();
        pointSignTask.setId(existingTask.getSignTaskId());
        pointSignTask.setBasePoints(signTaskDTO.getBasePoints());
        pointSignTask.setBreakRule(signTaskDTO.getBreakRule());

        // 更新签到任务
        int affectedRows = pointSignTaskService.updatePointSignTask(pointSignTask);
        if (affectedRows <= 0) {
            throw new ServiceException("更新积分签到任务规则失败");
        }

        // 更新签到奖励配置
        updateSignRewards(signTaskDTO.getSignRewardList(), pointSignTask.getId());
    }

    /**
     * 更新签到奖励配置
     */
    private void updateSignRewards(List<PointSignRewardDTO> rewardList, Long taskId) {
        // 先删除原有的奖励配置
        PointSignReward query = new PointSignReward();
        query.setSignTaskId(taskId);
        List<PointSignReward> existingRewards = pointSignRewardService.selectPointSignRewardList(query);

        if (CollectionUtil.isNotEmpty(existingRewards)) {
            String[] ids = existingRewards.stream()
                    .map(reward -> String.valueOf(reward.getId()))
                    .toArray(String[]::new);
            pointSignRewardService.deletePointSignRewardByIds(ids);
        }

        // 重新插入新的奖励配置
        if (CollectionUtil.isEmpty(rewardList)) {
            return;
        }

        List<PointSignReward> rewards = new ArrayList<>(rewardList.size());
        for (int i = 0; i < rewardList.size(); i++) {
            PointSignRewardDTO dto = rewardList.get(i);
            PointSignReward reward = new PointSignReward();
            reward.setRewardPoints(dto.getRewardPoints());
            reward.setContinueDays(dto.getContinueDays());
            reward.setSortOrder((long) i);
            reward.setCreateTime(DateUtils.getNowDate());
            reward.setUpdateTime(reward.getCreateTime());
            reward.setIsDeleted(0);
            reward.setSignTaskId(taskId);
            rewards.add(reward);
        }

        pointSignRewardService.batchInsertPointSignReward(rewards);
    }

    /**
     * 更新活动任务详情
     */
    private void updateActivityTaskDetails(PointActivityDTO dto, Long activityId) {

        // 先删除原有的活动任务
        pointActivityTaskService.deletePointActivityTaskByActivityId(activityId);

        // 重新插入新的活动任务
        List<PointActivityTaskDTO> tasks = dto.getTasks();
        if (CollectionUtil.isEmpty(tasks)) {
            return;
        }

        List<PointActivityTask> activityTasks = tasks.stream()
                .map(task -> {
                    PointActivityTask activityTask = new PointActivityTask();
                    BeanUtil.copyProperties(task, activityTask);
                    activityTask.setActivityId(activityId);
                    activityTask.setIsDeleted(0);
                    activityTask.setUpdateBy(SecurityUtils.getUsername());
                    activityTask.setUpdateTime(DateUtils.getNowDate());
                    return activityTask;
                })
                .collect(Collectors.toList());

        pointActivityTaskService.batchInsertPointActivityTask(activityTasks);
    }

    private void batchUpdateExpirePolicy(List<PointActivity> activityList, Long expirePolicyId) {
        // 参数校验
        if (CollectionUtil.isEmpty(activityList)) {
            log.debug("活动列表为空，无需更新过期策略");
            return;
        }

        if (expirePolicyId == null) {
            throw new IllegalArgumentException("过期策略ID不能为空");
        }

        try {
            // 使用Stream处理活动列表，设置过期策略ID
            List<PointActivity> activitiesToUpdate = activityList.stream()
                    .map(activity -> {
                        activity.setExpirePolicyId(expirePolicyId);
                        activity.setUpdateTime(DateUtils.getNowDate());
                        activity.setUpdateBy(SecurityUtils.getUsername());
                        return activity;
                    })
                    .collect(Collectors.toList());

            // 批量更新数据库
            super.updateBatchById(activitiesToUpdate, BATCH_SIZE);

            log.info("成功更新 {} 个活动的过期策略为 {}", activitiesToUpdate.size(), expirePolicyId);
        } catch (Exception e) {
            log.error("批量更新活动过期策略失败, expirePolicyId: {}", expirePolicyId, e);
            throw new ServiceException("批量更新活动过期策略失败");
        }
    }

    /**
     * 获取当前城市生效的签到任务
     *
     * @param cityCode
     * @return PointSignTask 积分签到任务规则
     */
    private PointSignTask getEnabledTask(String cityCode) {
        // 1. 根据城市查询当前生效的活动
        PointActivity activity = pointActivityMapper.selectOne(
                new QueryWrapper<PointActivity>()
                        .eq("city_code", cityCode)
                        .eq("status", 1)  // 活动启用
                        .last("LIMIT 1")
        );
        if (ObjectUtil.isNull(activity)) {
            throw new ServiceException("当前城市未配置签到活动");
        }

        // 2. 根据活动绑定的 taskId 查询签到任务
        LambdaQueryWrapper<PointSignTask> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PointSignTask::getActivityId, activity.getId());
        queryWrapper.eq(PointSignTask::getIsDeleted, 0);
        List<PointSignTask> list = pointSignTaskService.list(queryWrapper);
        PointSignTask task = null;

        if (CollectionUtil.isNotEmpty(list)) {
            task = CollectionUtil.getLast(list);
            task.setActivityName(activity.getName());
        }
        return task;
    }

    private PointActivityPageVo convertToVo(PointActivity activity) {
        PointActivityPageVo vo = new PointActivityPageVo();
        // 属性拷贝（推荐）
        BeanUtil.copyProperties(activity, vo);
        return vo;
    }

    private WxLoginUser getCurrentWxLoginUser() {
        WxLoginUser loginUser = SecurityUtils.getWxLoginUser();
        if (ObjectUtil.isNull(loginUser)) {
            throw new ServiceException("用户未登录或登录已过期");
        }
        return loginUser;
    }

}
