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.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import com.alibaba.fastjson.JSONObject;
import shop.alien.entity.store.LifeCoupon;
import shop.alien.entity.store.LifeDiscountCoupon;
import shop.alien.entity.store.LifeNotice;
import shop.alien.entity.store.StoreImg;
import shop.alien.entity.store.StoreUser;
import shop.alien.entity.store.vo.WebSocketVo;
import shop.alien.entity.storePlatform.StoreOperationalActivity;
import shop.alien.entity.storePlatform.StoreOperationalActivitySignup;
import shop.alien.entity.storePlatform.vo.StoreOperationalActivityDTO;
import shop.alien.entity.storePlatform.vo.StoreOperationalActivityVO;
import shop.alien.mapper.LifeCouponMapper;
import shop.alien.mapper.LifeDiscountCouponMapper;
import shop.alien.mapper.LifeNoticeMapper;
import shop.alien.util.type.LifeNoticeUtil;
import shop.alien.mapper.StoreImgMapper;
import shop.alien.mapper.StoreUserMapper;
import shop.alien.mapper.storePlantform.StoreOperationalActivityMapper;
import shop.alien.mapper.storePlantform.StoreOperationalActivitySignupMapper;
import shop.alien.storeplatform.feign.AlienAIFeign;
import shop.alien.storeplatform.feign.AlienStoreFeign;
import shop.alien.storeplatform.service.OperationalActivityService;
import shop.alien.storeplatform.util.AiContentModerationUtil;
import shop.alien.util.common.Constants;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;


/**
 * 运营活动服务实现类
 * <p>
 * 提供运营活动的增删改查功能，包括：
 * 1. 活动的创建、更新、删除
 * 2. 活动列表查询、分页查询
 * 3. 活动状态管理
 * </p>
 *
 * @author system
 * @since 2025-11-26
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class OperationalActivityServiceImpl implements OperationalActivityService {

    private final StoreOperationalActivityMapper activityMapper;

    private final StoreImgMapper imgMapper;

    private final LifeDiscountCouponMapper lifeDiscountCouponMapper;

    private final LifeCouponMapper lifeCouponMapper;

    private final StoreOperationalActivitySignupMapper signupMapper;

    private final StoreUserMapper storeUserMapper;

    private final LifeNoticeMapper lifeNoticeMapper;

    private final LifeNoticeUtil lifeNoticeUtil;

    private final AlienAIFeign alienAIFeign;

    private final AlienStoreFeign alienStoreFeign;

    private final RedissonClient redissonClient;

    private final AiContentModerationUtil aiContentModerationUtil;
    @Value("${ai.aiAccount}")
    private String aiAccount;

    @Value("${ai.aiPassword}")
    private String aiPassword;

    @Value("${ai.token-timeout:3}")
    private Integer aiTokenTimeout;

    // AI平台token Redis key
    private static final String AI_TOKEN_KEY = "ai:platform:token";

    ObjectMapper objectMapper = new ObjectMapper();

    public static final ThreadLocal<String> failureReasonHolder = new ThreadLocal<>();

    // AI参数模板
    String tpl = "活动名称：%s\n"
            + "活动时间：%s - %s,格式化时间为yyyy-mm-dd类型\n"
            + "用户可参与次数：%s\n"
            + "活动规则：%s\n"
            + "优惠券发放数量：%s\n"
            + "代金券发放数量：%s\n"
            + "图片描述：%s";

    @Override
    public StoreOperationalActivityDTO generateActivityPromotionImages(StoreOperationalActivityDTO dto) {
        log.info("OperationalActivityServiceImpl.generateActivityPromotionImages: dto={}", dto);
        if (dto.getUploadImgType() == null || dto.getUploadImgType() != 2) {
            throw new IllegalArgumentException("AI 生成图片需 uploadImgType=2");
        }
        if (dto.getActivityTitleImg() == null) {
            dto.setActivityTitleImg(new StoreImg());
        }
        if (dto.getActivityDetailImg() == null) {
            dto.setActivityDetailImg(new StoreImg());
        }
        String accessToken = getToken();
        if (accessToken == null || accessToken.isEmpty()) {
            throw new IllegalStateException("获取AI服务access_token失败，无法生成促销图片");
        }
        String authorization = "Bearer " + accessToken;
        String filled = String.format(
                tpl,
                dto.getActivityName(),
                dto.getStartTime(),
                dto.getEndTime(),
                dto.getParticipationLimit(),
                dto.getActivityRule(),
                dto.getCouponQuantity() != null ? dto.getCouponQuantity() : 0,
                dto.getVoucherQuantity() != null ? dto.getVoucherQuantity() : 0,
                dto.getImgDescribe()
        );
        JsonNode imgResponse = alienAIFeign.generatePromotionImage(authorization, Collections.singletonMap("text", filled));
        applyPromotionImageResponse(imgResponse, dto);
        return dto;
    }

    private void applyPromotionImageResponse(JsonNode imgResponse, StoreOperationalActivityDTO dto) {
        if (imgResponse == null || !imgResponse.has("data")) {
            return;
        }
        JsonNode data = imgResponse.get("data");
        if (data.has("banner_image")) {
            JsonNode bannerImage = data.get("banner_image");
            if (bannerImage.has("ali_url") && !bannerImage.get("ali_url").isNull()) {
                dto.getActivityTitleImg().setImgUrl(bannerImage.get("ali_url").asText());
            }
        }
        if (data.has("vertical_image")) {
            JsonNode verticalImage = data.get("vertical_image");
            if (verticalImage.has("ali_url") && !verticalImage.get("ali_url").isNull()) {
                dto.getActivityDetailImg().setImgUrl(verticalImage.get("ali_url").asText());
            }
        }
    }

    @Override
    public int createActivity(StoreOperationalActivityDTO dto) {
        log.info("OperationalActivityServiceImpl.createActivity: dto={}", dto);

        StoreOperationalActivity activity = new StoreOperationalActivity();
        BeanUtils.copyProperties(dto, activity);

        // 设置默认值
        if (activity.getParticipationLimit() == null) {
            activity.setParticipationLimit(0);
        }
        if (activity.getStatus() == null) {
            activity.setStatus(1);
        }
        Integer result = 0;
        try {
//            String accessToken = getToken();
//            if (accessToken == null || accessToken.isEmpty()) {
//                log.error("获取AI服务 access_token 失败，无法创建活动");
//            } else {
            AiContentModerationUtil.AuditResult auditResult = runActivityTextModeration(dto.getAuditParam());
            applyModerationOutcomeToActivity(activity, auditResult);

            result = activityMapper.insert(activity);
            if (result > 0) {
                try {
                    sendActivityAuditNotice(activity, auditResult.isPassed(), auditResult.getFailureReason());
                } catch (Exception e) {
                    log.error("发送活动审核通知失败，activityId={}, error={}", activity.getId(), e.getMessage(), e);
                }
            }
//            }
        } catch (Exception e) {
            log.error("创建活动/审核流程异常", e);
        }
            dto.getActivityTitleImg().setBusinessId(activity.getId());
            dto.getActivityTitleImg().setImgType(26);
            imgMapper.insert(dto.getActivityTitleImg());

            dto.getActivityDetailImg().setBusinessId(activity.getId());
            dto.getActivityDetailImg().setImgType(27);
            imgMapper.insert(dto.getActivityDetailImg());
        return result;
    }

    /**
     * 登录AI平台，获取token
     */
    private String getToken() {
        // 1. 先从缓存获取
        RBucket<String> tokenBucket = redissonClient.getBucket(AI_TOKEN_KEY);
        String cachedToken = tokenBucket.get();
        if (cachedToken != null && !cachedToken.isEmpty()) {
            log.debug("从缓存获取 AI token");
            return cachedToken;
        }
        // 2. 缓存未命中，调用登录接口
        MultiValueMap<String, String> formData = new LinkedMultiValueMap<>();
        formData.add("username", aiAccount);
        formData.add("password", aiPassword);
        JsonNode loginResponse = alienAIFeign.login(formData);
        String accessToken = null;
        if (loginResponse != null && loginResponse.has("data")) {
            JsonNode data = loginResponse.get("data");
            if (data.has("access_token")) {
                accessToken = data.get("access_token").asText();
            }
        }
        // 3. 如果获取成功，存入缓存
        if (accessToken != null && !accessToken.isEmpty()) {
            tokenBucket.set(accessToken, aiTokenTimeout, TimeUnit.SECONDS);
        } else {
            log.error("获取 AI token 失败");
        }
        return accessToken;
    }

    @Override
    public int updateActivity(StoreOperationalActivityDTO dto) {
        log.info("OperationalActivityServiceImpl.updateActivity: dto={}", dto);

        if (dto.getId() == null) {
            throw new IllegalArgumentException("活动ID不能为空");
        }

        StoreOperationalActivity activity = new StoreOperationalActivity();
        BeanUtils.copyProperties(dto, activity);
        Integer result = 0;
        try {
            String accessToken = getToken();
            if (accessToken == null || accessToken.isEmpty()) {
                log.error("获取AI服务 access_token 失败，无法更新活动");
            } else {
                String authorization = "Bearer " + accessToken;

                AiContentModerationUtil.AuditResult auditResult = runActivityTextModeration(dto.getAuditParam());
                applyModerationOutcomeToActivity(activity, auditResult);

                result = activityMapper.updateById(activity);
                sendActivityAuditNotice(activity, auditResult.isPassed(), auditResult.getFailureReason());
                // 使用用户描述和页面输入框其他信息,让AI生成海报图片。
                if (dto.getUploadImgType() == 2) {
                    if (dto.getActivityTitleImg() == null) {
                        dto.setActivityTitleImg(new StoreImg());
                    }
                    if (dto.getActivityDetailImg() == null) {
                        dto.setActivityDetailImg(new StoreImg());
                    }
                    String filled = String.format(
                            tpl,
                            dto.getActivityName(),
                            dto.getStartTime(),
                            dto.getEndTime(),
                            dto.getParticipationLimit(),
                            dto.getActivityRule(),
                            dto.getCouponQuantity() != null ? dto.getCouponQuantity() : 0,
                            dto.getVoucherQuantity() != null ? dto.getVoucherQuantity() : 0,
                            dto.getImgDescribe()
                    );
                    JsonNode imgResponse = alienAIFeign.generatePromotionImage(authorization, Collections.singletonMap("text", filled));
                    applyPromotionImageResponse(imgResponse, dto);
                }
            }
        } catch (Exception e) {
            // AI调用失败，也可以添加数据
            log.error("调用AI服务生成促销图片失败", e);
        }
//         result = activityMapper.updateById(activity);

        // 添加
        if (result > 0) {
            // 删除原本的图片
            LambdaUpdateWrapper<StoreImg> wrapper = new LambdaUpdateWrapper<>();
            wrapper.eq(StoreImg::getBusinessId, dto.getId())
                    .eq(StoreImg::getStoreId, dto.getStoreId())
                    .set(StoreImg::getDeleteFlag, 1);
            imgMapper.update(null, wrapper);


            // 插入新图片
            StoreImg activityTitleImg = new StoreImg();
            activityTitleImg.setStoreId(dto.getStoreId());
            activityTitleImg.setImgType(26);
            activityTitleImg.setImgSort(dto.getActivityTitleImg().getImgSort());
            activityTitleImg.setImgUrl(dto.getActivityTitleImg().getImgUrl());
            activityTitleImg.setBusinessId(dto.getId());
            imgMapper.insert(activityTitleImg);

            // 插入新图片
            StoreImg activityDetailImg = new StoreImg();
            activityDetailImg.setStoreId(dto.getStoreId());
            activityDetailImg.setImgType(27);
            activityDetailImg.setImgSort(dto.getActivityDetailImg().getImgSort());
            activityDetailImg.setImgUrl(dto.getActivityDetailImg().getImgUrl());
            activityDetailImg.setBusinessId(dto.getId());
            imgMapper.insert(activityDetailImg);
        }
        return result;
    }

    @Override
    public int deleteActivity(Integer id) {
        log.info("OperationalActivityServiceImpl.deleteActivity: id={}", id);

        if (id == null) {
            throw new IllegalArgumentException("活动ID不能为空");
        }

        // 先删除相关的报名人员（逻辑删除）
        LambdaUpdateWrapper<StoreOperationalActivitySignup> signupWrapper = new LambdaUpdateWrapper<>();
        signupWrapper.eq(StoreOperationalActivitySignup::getActivityId, id)
                .eq(StoreOperationalActivitySignup::getDeleteFlag, 0)
                .set(StoreOperationalActivitySignup::getDeleteFlag, 1);
        int signupDeleteCount = signupMapper.update(null, signupWrapper);
        log.info("删除活动相关报名人员数量: {}", signupDeleteCount);

        // 逻辑删除活动
        return activityMapper.deleteById(id);
    }

    @Override
    public StoreOperationalActivityVO queryActivityById(Integer id) {
        log.info("OperationalActivityServiceImpl.getActivityById: id={}", id);

        if (id == null) {
            throw new IllegalArgumentException("活动ID不能为空");
        }

        StoreOperationalActivity activity = activityMapper.selectById(id);

        if (activity == null) {
            return null;
        }

        // 创建实体类
        StoreOperationalActivityVO vo = new StoreOperationalActivityVO();
        BeanUtils.copyProperties(activity, vo);

        if (activity.getStatus() == 1) {
            vo.setStatusName("待审核");
        } else if (activity.getStatus() == 2) {
            vo.setStatusName("未开始");
        } else if (activity.getStatus() == 3) {
            vo.setStatusName("审核拒绝");
        } else if (activity.getStatus() == 4) {
            vo.setStatusName("已售罄");
        } else if (activity.getStatus() == 5) {
            vo.setStatusName("进行中");
        } else if (activity.getStatus() == 6) {
            vo.setStatusName("已下架");
        } else if (activity.getStatus() == 7) {
            vo.setStatusName("已结束");
        }

        // 设置优惠券名称和类型（判空处理）
        if (activity.getCouponId() != null) {
            LifeDiscountCoupon coupon = lifeDiscountCouponMapper.selectByIdIncludeDeleted(activity.getCouponId());
            if (coupon != null) {
                vo.setCouponName(coupon.getName());
                // 设置优惠券类型（满减券/折扣券）：1=满减券，2=折扣券
                vo.setDiscountCouponType(coupon.getCouponType());
                // 如果是折扣券，设置折扣率
                if (coupon.getCouponType() != null && coupon.getCouponType() == 2) {
                    vo.setDiscountRate(coupon.getDiscountRate());
                }
            }
        }

        // 设置代金券名称（判空处理）
        if (activity.getVoucherId() != null) {
            LifeCoupon voucher = lifeCouponMapper.selectById(String.valueOf(activity.getVoucherId()));
            if (voucher != null) {
                vo.setVoucherName(voucher.getName());
            }
        }

        StoreImg activityTitleImg = imgMapper.selectOne(new LambdaQueryWrapper<StoreImg>()
                .eq(StoreImg::getStoreId, vo.getStoreId())
                .eq(StoreImg::getImgType, 26)
                .eq(StoreImg::getDeleteFlag, 0)
                .eq(StoreImg::getBusinessId, activity.getId()));
        if (activityTitleImg != null) {
            vo.setActivityTitleImgUrl(activityTitleImg.getImgUrl());
        }


        StoreImg activityDetailImg = imgMapper.selectOne(new LambdaQueryWrapper<StoreImg>()
                .eq(StoreImg::getStoreId, vo.getStoreId())
                .eq(StoreImg::getImgType, 27)
                .eq(StoreImg::getDeleteFlag, 0)
                .eq(StoreImg::getBusinessId, activity.getId()));
        if (activityDetailImg != null) {
            vo.setActivityDetailImgUrl(activityDetailImg.getImgUrl());
        }

        return vo;
    }


    @Override
    public IPage<StoreOperationalActivityVO> queryActivityList(Integer storeId, Integer status,String activityType, String activityName, Integer pageNum, Integer pageSize) {
        log.info("OperationalActivityServiceImpl.queryActivityList: storeId={}, status={}, activityName={}, pageNum={}, pageSize={}",
                storeId, status, activityName, pageNum, pageSize);

        LambdaQueryWrapper<StoreOperationalActivity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(storeId != null, StoreOperationalActivity::getStoreId, storeId);
        wrapper.like(activityName != null && activityName != "", StoreOperationalActivity::getActivityName, activityName);
        wrapper.eq(status != null, StoreOperationalActivity::getStatus, status);
        wrapper.eq(activityType != null, StoreOperationalActivity::getActivityType, activityType);

        IPage<StoreOperationalActivity> list = activityMapper.selectPage(new Page<>(pageNum, pageSize), wrapper);

        // 将list复制到vo
        List<StoreOperationalActivityVO> voRecords = new ArrayList<>();

        for (StoreOperationalActivity activity : list.getRecords()) {
            // 创建实体类
            StoreOperationalActivityVO vo = new StoreOperationalActivityVO();
            BeanUtils.copyProperties(activity, vo);

            if (activity.getStatus() == 1) {
                vo.setStatusName("待审核");
            } else if (activity.getStatus() == 2) {
                vo.setStatusName("未开始");
            } else if (activity.getStatus() == 3) {
                vo.setStatusName("审核拒绝");
            } else if (activity.getStatus() == 4) {
                vo.setStatusName("已售罄");
            } else if (activity.getStatus() == 5) {
                vo.setStatusName("进行中");
            } else if (activity.getStatus() == 6) {
                vo.setStatusName("已下架");
            } else if (activity.getStatus() == 7) {
                vo.setStatusName("已结束");
            }

            // 设置优惠券名称（判空处理）
            if (activity.getCouponId() != null) {
                LifeDiscountCoupon coupon = lifeDiscountCouponMapper.selectByIdIncludeDeleted(activity.getCouponId());
                if (coupon != null) {
                    vo.setCouponName(coupon.getName());
                }
            }

            // 设置代金券名称（判空处理）
            if (activity.getVoucherId() != null) {
                LifeCoupon voucher = lifeCouponMapper.selectById(String.valueOf(activity.getVoucherId()));
                if (voucher != null) {
                    vo.setVoucherName(voucher.getName());
                }
            }

            // 查询活动标题图片
            StoreImg activityTitleImg = imgMapper.selectOne(new LambdaQueryWrapper<StoreImg>()
                    .eq(StoreImg::getStoreId, vo.getStoreId())
                    .eq(StoreImg::getImgType, 26)
                    .eq(StoreImg::getDeleteFlag, 0)
                    .eq(StoreImg::getBusinessId, activity.getId()));
            if (activityTitleImg != null) {
                vo.setActivityTitleImgUrl(activityTitleImg.getImgUrl());
            }

            // 查询活动详情图片
            StoreImg activityDetailImg = imgMapper.selectOne(new LambdaQueryWrapper<StoreImg>()
                    .eq(StoreImg::getStoreId, vo.getStoreId())
                    .eq(StoreImg::getImgType, 27)
                    .eq(StoreImg::getDeleteFlag, 0)
                    .eq(StoreImg::getBusinessId, activity.getId()));
            if (activityDetailImg != null) {
                vo.setActivityDetailImgUrl(activityDetailImg.getImgUrl());
            }

            voRecords.add(vo);
        }

        // 创建分页结果对象
        Page<StoreOperationalActivityVO> voList = new Page<>(list.getCurrent(), list.getSize(), list.getTotal());
        voList.setRecords(voRecords);

        return voList;
    }

    public static void main(String[] args) {
        // 时间格式化
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        Date now = new Date();
        System.out.println("当前时间: " + sdf.format(now));

        // 获取当天零点零分零秒时间
        Calendar todayStart = Calendar.getInstance();
        todayStart.setTime(now);
        todayStart.set(Calendar.HOUR_OF_DAY, 0);
        todayStart.set(Calendar.MINUTE, 0);
        todayStart.set(Calendar.SECOND, 0);
        todayStart.set(Calendar.MILLISECOND, 0);
        Date todayZero = todayStart.getTime();
        System.out.println("当天零点时间: " + sdf.format(todayZero));

        // now + 1天（零点）
        Calendar calendarPlus = Calendar.getInstance();
        calendarPlus.setTime(now);
        calendarPlus.add(Calendar.DAY_OF_MONTH, 1);
        calendarPlus.set(Calendar.HOUR_OF_DAY, 0);
        calendarPlus.set(Calendar.MINUTE, 0);
        calendarPlus.set(Calendar.SECOND, 0);
        calendarPlus.set(Calendar.MILLISECOND, 0);
        Date nowPlusOneDay = calendarPlus.getTime();
        System.out.println("当前时间+1天(零点): " + sdf.format(nowPlusOneDay));

    }

    @Override
    public int updateActivityStatus(Integer id, Integer status) {
        log.info("OperationalActivityServiceImpl.updateActivityStatus: id={}, status={}", id, status);

        if (id == null) {
            throw new IllegalArgumentException("活动ID不能为空");
        }

        StoreOperationalActivity activity = new StoreOperationalActivity();
        activity.setId(id);
        activity.setStatus(status);

        return activityMapper.updateById(activity);
    }

    @Override
    public int uploadActivityResult(StoreOperationalActivityDTO dto) {
        log.info("OperationalActivityServiceImpl.uploadActivityResult: dto={}", dto);

        if (dto.getId() == null) {
            throw new IllegalArgumentException("活动ID不能为空");
        }

        if (dto.getResultType() == null) {
            throw new IllegalArgumentException("结果类型不能为空");
        }

        StoreOperationalActivity activity = new StoreOperationalActivity();
        activity.setId(dto.getId());
        activity.setResultType(dto.getResultType());
        activity.setResultText(dto.getResultText());
        activity.setResultMediaUrl(dto.getResultMediaUrl());

        return activityMapper.updateById(activity);
    }

    /** auditParam 可为 JSON 对象或 JSON 字符串；其中 image_urls 仅前端使用，服务端只审 text */
    private AiContentModerationUtil.AuditResult runActivityTextModeration(JsonNode rawAuditParam) {
        JsonNode param = unwrapAuditParam(rawAuditParam);
        String text = (param != null && param.has("text")) ? param.get("text").asText() : "";
        return aiContentModerationUtil.auditContent(text, null);
    }

    private JsonNode unwrapAuditParam(JsonNode auditParam) {
        if (auditParam == null || !auditParam.isTextual()) {
            return auditParam;
        }
        try {
            return objectMapper.readTree(auditParam.asText());
        } catch (Exception e) {
            log.error("解析 auditParam 失败: {}", auditParam.asText(), e);
            return null;
        }
    }

    /** 写入审核结果、业务时间轴状态；不通过时 status=3 并记录原因 */
    private void applyModerationOutcomeToActivity(StoreOperationalActivity activity,
                                                  AiContentModerationUtil.AuditResult auditResult) {
        activity.setAuditStatus(auditResult.isPassed() ? 1 : 2);
        activity.setAuditTime(new Date());

        Date now = new Date();
        Date start = activity.getStartTime();
        Date end = activity.getEndTime();
        int timelineStatus;
        if (now.before(start)) {
            timelineStatus = 2;
        } else if (now.compareTo(start) >= 0 && now.compareTo(end) <= 0) {
            timelineStatus = 5;
        } else {
            timelineStatus = 7;
        }
        activity.setStatus(timelineStatus);

        if (!auditResult.isPassed()) {
            failureReasonHolder.set(auditResult.getFailureReason());
            activity.setApprovalComments(auditResult.getFailureReason());
            activity.setStatus(3);
        }
    }

    /**
     * 发送活动审核通知给商户
     *
     * @param activity 活动信息
     * @param approved 是否通过：true-通过，false-拒绝
     * @param rejectReason 拒绝原因（审核不通过时）
     */
    private void sendActivityAuditNotice(StoreOperationalActivity activity, boolean approved, String rejectReason) {
        log.info("OperationalActivityServiceImpl.sendActivityAuditNotice: activityId={}, approved={}", 
                activity.getId(), approved);

        if (activity.getStoreId() == null) {
            log.warn("活动商户ID为空，无法发送通知，activityId={}", activity.getId());
            return;
        }

        // 查询商户用户信息（获取手机号）
        LambdaQueryWrapper<StoreUser> userWrapper = new LambdaQueryWrapper<>();
        userWrapper.eq(StoreUser::getStoreId, activity.getStoreId())
                .eq(StoreUser::getDeleteFlag, 0)
                .last("LIMIT 1");
        StoreUser storeUser = storeUserMapper.selectOne(userWrapper);
        if (storeUser == null || storeUser.getPhone() == null) {
            log.warn("商户用户信息不存在或手机号为空，无法发送通知，storeId={}", activity.getStoreId());
            return;
        }

        String phone = storeUser.getPhone();
        String receiverId = "store_" + phone;

        // 构建通知内容
        String message;
        if (approved) {
            // 审核成功
            message = "您创建的活动已审核通过，快去查看吧";
        } else {
            // 审核拒绝
            message = "您创建的活动经审核未通过，拒绝原因：" + (rejectReason != null ? rejectReason : "") + "，请重新提交审核";
        }

        // 创建通知对象
        JSONObject contextJson = new JSONObject();
        contextJson.put("activityId", activity.getId());
        contextJson.put("activityName", activity.getActivityName());
        contextJson.put("status", approved ? "通过" : "拒绝");
        contextJson.put("message", message);

        LifeNotice lifeNotice = new LifeNotice();
        lifeNotice.setSenderId("system");
        lifeNotice.setReceiverId(receiverId);
        lifeNotice.setBusinessId(activity.getId());
        lifeNotice.setTitle("活动审核通知");
        lifeNotice.setContext(contextJson.toJSONString());
        lifeNotice.setNoticeType(Constants.Notice.SYSTEM_NOTICE); // 系统通知
        lifeNotice.setIsRead(0);

        // 保存通知到数据库
        lifeNoticeUtil.fillUserTypeAndRefId(lifeNotice);
        lifeNoticeMapper.insert(lifeNotice);

        // 通过WebSocket发送实时通知
        try {
            WebSocketVo webSocketVo = new WebSocketVo();
            webSocketVo.setSenderId("system");
            webSocketVo.setReceiverId(receiverId);
            webSocketVo.setCategory("notice");
            webSocketVo.setNoticeType("1");
            webSocketVo.setIsRead(0);
            webSocketVo.setText(JSONObject.toJSONString(lifeNotice));

            alienStoreFeign.sendMsgToClientByPhoneId(receiverId, JSONObject.toJSONString(webSocketVo));
            log.info("活动审核通知发送成功，activityId={}, receiverId={}, approved={}", 
                    activity.getId(), receiverId, approved);
        } catch (Exception e) {
            log.error("发送WebSocket通知失败，activityId={}, receiverId={}, error={}", 
                    activity.getId(), receiverId, e.getMessage(), e);
        }
    }
}

