package com.ycwl.basic.task;

import cn.hutool.core.date.DateUtil;
import com.ycwl.basic.integration.message.service.ZtMessageProducerService;
import com.ycwl.basic.integration.scenic.dto.scenic.ScenicV2DTO;
import com.ycwl.basic.mapper.MemberMapper;
import com.ycwl.basic.mapper.VideoMapper;
import com.ycwl.basic.model.pc.member.resp.MemberRespVO;
import com.ycwl.basic.integration.common.manager.ScenicConfigManager;
import com.ycwl.basic.model.pc.notify.req.WechatSubscribeNotifyTriggerRequest;
import com.ycwl.basic.model.pc.notify.resp.WechatSubscribeNotifyTriggerResult;
import com.ycwl.basic.model.pc.scenic.req.ScenicReqQuery;
import com.ycwl.basic.repository.ScenicRepository;
import com.ycwl.basic.repository.VideoTaskRepository;
import com.ycwl.basic.service.notify.WechatSubscribeNotifyTriggerService;
import com.ycwl.basic.utils.NotificationAuthUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

@Component
@EnableScheduling
@Slf4j
@Profile("prod")
public class DownloadNotificationTasker {
    @Autowired
    private ScenicRepository scenicRepository;
    @Autowired
    private VideoMapper videoMapper;
    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private WechatSubscribeNotifyTriggerService notifyTriggerService;
    @Autowired
    private VideoTaskRepository videoTaskRepository;

    @Scheduled(cron = "0 0 9,21 * * *")
    public void sendDownloadNotification() {
        log.info("开始执行定时任务");
        // 用于记录已发送通知的用户ID，避免重复发送
        Set<Long> sentMemberIds = ConcurrentHashMap.newKeySet();
        videoMapper.listRelationByCreateTime(new Date(System.currentTimeMillis() - 12 * 60 * 60 * 1000), new Date())
                .forEach(item -> {
                    // 检查该用户是否已经发送过通知，避免重复发送
                    if (sentMemberIds.contains(item.getMemberId())) {
                        log.debug("用户[memberId={}]已发送过下载通知，跳过", item.getMemberId());
                        return;
                    }
                    sentMemberIds.add(item.getMemberId());
                    if (item.getIsBuy() == 1) {
                        return;
                    }

                    MemberRespVO member = memberMapper.getById(item.getMemberId());
                    if (member == null || member.getOpenId() == null) {
                        log.debug("用户[memberId={}]不存在或未绑定微信，跳过", item.getMemberId());
                        return;
                    }
                    // 发送模板消息
                    HashMap<String, Object> variables = new HashMap<>();
                    ScenicV2DTO scenic = scenicRepository.getScenicBasic(item.getScenicId());
                    variables.put("scenicName", scenic.getName());
                    variables.put("scenicId", scenic.getId());
                    variables.put("faceId", item.getFaceId());
                    variables.put("videoId", item.getVideoId());
                    ScenicConfigManager configManager = scenicRepository.getScenicConfigManager(item.getScenicId());
                    if (configManager.getBoolean("grouping_enable", false)) {
                        variables.put("videoResultPage", "travelVideoCenter");
                    } else {
                        variables.put("videoResultPage", "videoSynthesis");
                    }
                    variables.put("videoDeviceCount", videoTaskRepository.getTaskDeviceNum(item.getTaskId()));
                    variables.put("videoLensCount", videoTaskRepository.getTaskLensNum(item.getTaskId()));
                    variables.put("videoShotTime", DateUtil.format(videoTaskRepository.getTaskShotDate(item.getTaskId()), "yyyy-MM-dd HH:mm"));
                    WechatSubscribeNotifyTriggerRequest request = WechatSubscribeNotifyTriggerRequest.builder()
                            .scenicId(item.getScenicId())
                            .memberId(item.getMemberId())
                            .openId(member.getOpenId())
                            .bizId(String.valueOf(item.getId()))
                            .variables(variables)
                            .build();
                    WechatSubscribeNotifyTriggerResult result = notifyTriggerService.trigger("NOT_BUY_NOTIFY", request);
                });
    }

    @Scheduled(cron = "0 0 19 * * *")
    public void sendExpireNotification() {
        log.info("开始执行定时任务");
        // 用于记录已发送通知的用户ID，避免重复发送
        Set<Long> sentMemberIds = ConcurrentHashMap.newKeySet();
        videoMapper.listRelationByCreateTime(new Date(System.currentTimeMillis() - 2 * 24 * 60 * 60 * 1000), new Date(System.currentTimeMillis() - 24 * 60 * 60 * 1000))
                .forEach(item -> {
                    if (item.getIsBuy() == 1) {
                        return;
                    }
                    // 检查该用户是否已经发送过通知，避免重复发送
                    if (sentMemberIds.contains(item.getMemberId())) {
                        log.debug("用户[memberId={}]已发送过过期提醒通知，跳过", item.getMemberId());
                        return;
                    }
                    sentMemberIds.add(item.getMemberId());
                    
                    MemberRespVO member = memberMapper.getById(item.getMemberId());
                    if (member == null || member.getOpenId() == null) {
                        log.debug("用户[memberId={}]不存在或未绑定微信，跳过", item.getMemberId());
                        return;
                    }
                    ScenicConfigManager scenicConfig = scenicRepository.getScenicConfigManager(item.getScenicId());
                    Integer videoStoreDay = scenicConfig.getInteger("video_store_day");
                    if (videoStoreDay == null) {
                        videoStoreDay = 3;
                    }
                    Date expireDate = new Date(item.getCreateTime().getTime() + videoStoreDay * 24 * 60 * 60 * 1000);
                    // 发送模板消息
                    HashMap<String, Object> variables = new HashMap<>();
                    ScenicV2DTO scenic = scenicRepository.getScenicBasic(item.getScenicId());
                    variables.put("scenicName", scenic.getName());
                    variables.put("scenicId", scenic.getId());
                    variables.put("faceId", item.getFaceId());
                    ScenicConfigManager configManager = scenicRepository.getScenicConfigManager(item.getScenicId());
                    if (configManager.getBoolean("grouping_enable", false)) {
                        variables.put("videoResultPage", "travelVideoCenter");
                    } else {
                        variables.put("videoResultPage", "videoSynthesis");
                    }
                    variables.put("expireDate", DateUtil.format(expireDate, "yyyy-MM-dd HH:mm"));
                    variables.put("videoDeviceCount", videoTaskRepository.getTaskDeviceNum(item.getTaskId()));
                    variables.put("videoLensCount", videoTaskRepository.getTaskLensNum(item.getTaskId()));
                    variables.put("videoShotTime", DateUtil.format(videoTaskRepository.getTaskShotDate(item.getTaskId()), "yyyy-MM-dd HH:mm"));
                    WechatSubscribeNotifyTriggerRequest request = WechatSubscribeNotifyTriggerRequest.builder()
                            .scenicId(item.getScenicId())
                            .memberId(item.getMemberId())
                            .openId(member.getOpenId())
                            .bizId(String.valueOf(item.getId()))
                            .variables(variables)
                            .build();
                    WechatSubscribeNotifyTriggerResult result = notifyTriggerService.trigger("EXPIRE_NOTIFY", request);
                });
    }
    @Scheduled(cron = "0 0 19 * * *")
    public void sendPreExpireNotification() {
        log.info("开始执行定时任务");
        // 用于记录已发送通知的用户ID，避免重复发送
        Set<Long> sentMemberIds = ConcurrentHashMap.newKeySet();
        videoMapper.listRelationByCreateTime(new Date(System.currentTimeMillis() - 24 * 60 * 60 * 1000), new Date(System.currentTimeMillis() - 24 * 60 * 60 * 1000))
                .forEach(item -> {
                    if (item.getIsBuy() == 1) {
                        return;
                    }
                    // 检查该用户是否已经发送过通知，避免重复发送
                    if (sentMemberIds.contains(item.getMemberId())) {
                        log.debug("用户[memberId={}]已发送过过期提醒通知，跳过", item.getMemberId());
                        return;
                    }
                    sentMemberIds.add(item.getMemberId());

                    MemberRespVO member = memberMapper.getById(item.getMemberId());
                    if (member == null || member.getOpenId() == null) {
                        log.debug("用户[memberId={}]不存在或未绑定微信，跳过", item.getMemberId());
                        return;
                    }
                    ScenicConfigManager scenicConfig = scenicRepository.getScenicConfigManager(item.getScenicId());
                    Integer videoStoreDay = scenicConfig.getInteger("video_store_day");
                    if (videoStoreDay == null) {
                        videoStoreDay = 3;
                    }
                    Date expireDate = new Date(item.getCreateTime().getTime() + videoStoreDay * 24 * 60 * 60 * 1000);
                    // 发送模板消息
                    HashMap<String, Object> variables = new HashMap<>();
                    ScenicV2DTO scenic = scenicRepository.getScenicBasic(item.getScenicId());
                    variables.put("scenicName", scenic.getName());
                    variables.put("scenicId", scenic.getId());
                    variables.put("faceId", item.getFaceId());
                    ScenicConfigManager configManager = scenicRepository.getScenicConfigManager(item.getScenicId());
                    if (configManager.getBoolean("grouping_enable", false)) {
                        variables.put("videoResultPage", "travelVideoCenter");
                    } else {
                        variables.put("videoResultPage", "videoSynthesis");
                    }
                    variables.put("expireDate", DateUtil.format(expireDate, "yyyy-MM-dd HH:mm"));
                    variables.put("videoDeviceCount", videoTaskRepository.getTaskDeviceNum(item.getTaskId()));
                    variables.put("videoLensCount", videoTaskRepository.getTaskLensNum(item.getTaskId()));
                    variables.put("videoShotTime", DateUtil.format(videoTaskRepository.getTaskShotDate(item.getTaskId()), "yyyy-MM-dd HH:mm"));
                    WechatSubscribeNotifyTriggerRequest request = WechatSubscribeNotifyTriggerRequest.builder()
                            .scenicId(item.getScenicId())
                            .memberId(item.getMemberId())
                            .openId(member.getOpenId())
                            .bizId(String.valueOf(item.getId()))
                            .variables(variables)
                            .build();
                    WechatSubscribeNotifyTriggerResult result = notifyTriggerService.trigger("VIDEO_PRE_EXPIRE", request);
                });
    }

    @Scheduled(cron = "0 0 * * * *")
    public void sendExtraDownloadNotification() {
        log.info("开始执行定时任务");
        ScenicReqQuery query = new ScenicReqQuery();
        query.setPageSize(1000);
        List<ScenicV2DTO> scenicList = scenicRepository.list(query);
        if (scenicList.isEmpty()) {
            return;
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        int currentHour = calendar.get(Calendar.HOUR_OF_DAY);
        calendar.clear();
        scenicList.parallelStream().forEach(scenic -> {
            Long scenicId = Long.parseLong(scenic.getId());
            ScenicConfigManager scenicConfig = scenicRepository.getScenicConfigManager(scenicId);
            if (scenicConfig == null) {
                return;
            }
            if (StringUtils.isEmpty(scenicConfig.getString("extra_notification_time"))) {
                return;
            }
            List<String> timeList = Arrays.asList(StringUtils.split(scenicConfig.getString("extra_notification_time"), ","));
            if (!timeList.contains(String.valueOf(currentHour))) {
                return;
            }
            log.info("当前景区{}，配置了{}", scenic.getName(), scenicConfig.getString("extra_notification_time"));

            // 使用线程安全的Set记录已发送通知的用户ID，避免重复发送
            Set<Long> sentMemberIds = ConcurrentHashMap.newKeySet();
            videoMapper.listRelationByCreateTime(DateUtil.beginOfDay(new Date()), new Date())
                    .stream()
                    .filter(item -> item.getIsBuy() == 0)
                    .filter(item -> item.getScenicId().equals(scenicId))
                    .parallel()
                    .forEach(item -> {
                        // 检查该用户是否已经发送过通知，避免重复发送
                        if (!sentMemberIds.add(item.getMemberId())) {
                            log.debug("用户[memberId={}]已发送过额外下载通知，跳过", item.getMemberId());
                            return;
                        }
                        
                        MemberRespVO member = memberMapper.getById(item.getMemberId());
                        if (member == null || member.getOpenId() == null) {
                            log.debug("用户[memberId={}]不存在或未绑定微信，跳过", item.getMemberId());
                            return;
                        }
                        // 发送模板消息
                        HashMap<String, Object> variables = new HashMap<>();
                        variables.put("scenicName", scenic.getName());
                        variables.put("scenicId", scenic.getId());
                        variables.put("faceId", item.getFaceId());
                        ScenicConfigManager configManager = scenicRepository.getScenicConfigManager(item.getScenicId());
                        if (configManager.getBoolean("grouping_enable", false)) {
                            variables.put("videoResultPage", "travelVideoCenter");
                        } else {
                            variables.put("videoResultPage", "videoSynthesis");
                        }
                        variables.put("videoDeviceCount", videoTaskRepository.getTaskDeviceNum(item.getTaskId()));
                        variables.put("videoLensCount", videoTaskRepository.getTaskLensNum(item.getTaskId()));
                        variables.put("videoShotTime", DateUtil.format(videoTaskRepository.getTaskShotDate(item.getTaskId()), "yyyy-MM-dd HH:mm"));
                        WechatSubscribeNotifyTriggerRequest request = WechatSubscribeNotifyTriggerRequest.builder()
                                .scenicId(item.getScenicId())
                                .memberId(item.getMemberId())
                                .openId(member.getOpenId())
                                .bizId(String.valueOf(item.getId()))
                                .variables(variables)
                                .build();
                        WechatSubscribeNotifyTriggerResult result = notifyTriggerService.trigger("TIME_TRIGGER_NOTIFY", request);
                    });
        });
    }
}
