package com.ycwl.basic.task;

import cn.hutool.core.date.DateUtil;
import com.ycwl.basic.integration.message.dto.ZtMessage;
import com.ycwl.basic.integration.message.service.ZtMessageProducerService;
import com.ycwl.basic.integration.scenic.dto.scenic.ScenicV2DTO;
import com.ycwl.basic.mapper.CouponMapper;
import com.ycwl.basic.mapper.MemberMapper;
import com.ycwl.basic.mapper.VideoMapper;
import com.ycwl.basic.model.pc.coupon.req.CouponQueryReq;
import com.ycwl.basic.model.pc.coupon.resp.CouponRespVO;
import com.ycwl.basic.model.pc.member.resp.MemberRespVO;
import com.ycwl.basic.model.pc.mp.MpConfigEntity;
import com.ycwl.basic.model.pc.scenic.entity.ScenicConfigEntity;
import com.ycwl.basic.model.pc.scenic.entity.ScenicEntity;
import com.ycwl.basic.model.pc.scenic.req.ScenicReqQuery;
import com.ycwl.basic.repository.ScenicRepository;
import com.ycwl.basic.repository.TemplateRepository;
import com.ycwl.basic.integration.common.manager.ScenicConfigManager;
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 CouponMapper couponMapper;
    @Autowired
    private ZtMessageProducerService ztMessageProducerService;
    @Autowired
    private NotificationAuthUtils notificationAuthUtils;

    @Scheduled(cron = "0 0 21 * * *")
    public void sendDownloadNotification() {
        log.info("开始执行定时任务");
        // 用于记录已发送通知的用户ID，避免重复发送
        Set<Long> sentMemberIds = ConcurrentHashMap.newKeySet();
        videoMapper.listRelationByCreateTime(new Date(System.currentTimeMillis() - 24 * 60 * 60 * 1000), new Date())
                .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());
                    // 发送模板消息
                    String templateId = scenicRepository.getVideoDownloadTemplateId(item.getScenicId());
                    if (StringUtils.isBlank(templateId)) {
                        log.info("模板消息为空");
                        return;
                    }

                    // 检查并消费通知授权
                    if (!notificationAuthUtils.checkAndConsumeAuthorization(item.getMemberId(), templateId, item.getScenicId())) {
                        log.debug("用户[memberId={}]对模板[templateId={}]授权不足，跳过下载通知", item.getMemberId(), templateId);
                        return;
                    }

                    ScenicV2DTO scenic = scenicRepository.getScenicBasic(item.getScenicId());
                    ScenicConfigManager configManager = scenicRepository.getScenicConfigManager(item.getScenicId());
                    String configTitle = configManager.getString("second_notification_title");
                    String configContent = configManager.getString("second_notification_content");

                    if (StringUtils.isBlank(configTitle) || StringUtils.isBlank(configContent)) {
                        log.info("景区[{}]未配置第二次通知内容，跳过发送通知", scenic.getName());
                        return;
                    }

                    String title = configTitle.replace("【景区】", scenic.getName());
                    String page;
                    if (configManager.getBoolean("grouping_enable", false)) {
                        page = "pages/travelVideoCenter/index?type=2&scenicId=" + item.getScenicId() + "&faceId=" + item.getFaceId();
                    } else {
                        page = "pages/videoSynthesis/index?type=2&scenicId=" + item.getScenicId() + "&faceId=" + item.getFaceId();
                    }
                    /**
                     * 景区 {{thing1.DATA}}
                     * 备注 {{thing3.DATA}}
                     */
                    Map<String, Object> dataParam = new HashMap<>();
                    dataParam.put("thing1", title);
                    dataParam.put("thing3", configContent);

                    // 构建extra，只包含data和page
                    Map<String, Object> extra = new HashMap<>();
                    extra.put("data", dataParam);
                    extra.put("page", page);

                    // 使用ZT消息服务发送通知（第二次通知）
                    ZtMessage msg = new ZtMessage();
                    msg.setChannelId(templateId);
                    msg.setTitle(title);
                    msg.setContent("【" + item.getFaceId() + "】"+configContent);
                    msg.setTarget(member.getOpenId());
                    msg.setExtra(extra);
                    msg.setSendReason("第二次通知");
                    msg.setSendBiz("定时通知");
                    ztMessageProducerService.send(msg);
                });
    }

    @Scheduled(cron = "0 0 20 * * *")
    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());
                    ScenicConfigEntity scenicConfig = scenicRepository.getScenicConfig(item.getScenicId());
                    Integer videoStoreDay = scenicConfig.getVideoStoreDay();
                    if (videoStoreDay == null) {
                        videoStoreDay = 3;
                    }
                    // 发送模板消息
                    String templateId = scenicRepository.getVideoPreExpireTemplateId(item.getScenicId());
                    if (StringUtils.isBlank(templateId)) {
                        log.info("模板消息为空");
                        return;
                    }

                    // 检查并消费通知授权
                    if (!notificationAuthUtils.checkAndConsumeAuthorization(item.getMemberId(), templateId, item.getScenicId())) {
                        log.debug("用户[memberId={}]对模板[templateId={}]授权不足，跳过过期提醒通知", item.getMemberId(), templateId);
                        return;
                    }

                    ScenicV2DTO scenic = scenicRepository.getScenicBasic(item.getScenicId());
                    ScenicConfigManager configManager = scenicRepository.getScenicConfigManager(item.getScenicId());
                    String configTitle = configManager.getString("third_notification_title");
                    String configContent = configManager.getString("third_notification_content");

                    if (StringUtils.isBlank(configTitle) || StringUtils.isBlank(configContent)) {
                        log.info("景区[{}]未配置第三次通知内容，跳过发送通知", scenic.getName());
                        return;
                    }

                    String title = configTitle.replace("【景区】", scenic.getName());
                    String page;
                    if (configManager.getBoolean("grouping_enable", false)) {
                        page = "pages/travelVideoCenter/index?type=3&scenicId=" + item.getScenicId() + "&faceId=" + item.getFaceId();
                    } else {
                        page = "pages/videoSynthesis/index?type=3&scenicId=" + item.getScenicId() + "&faceId=" + item.getFaceId();
                    }
                    /**
                     * 影像名称 {{thing1.DATA}}
                     * 过期时间 {{time2.DATA}}
                     * 备注 {{thing3.DATA}}
                     */
                    Date expireDate = new Date(item.getCreateTime().getTime() + videoStoreDay * 24 * 60 * 60 * 1000);
                    Map<String, Object> dataParam = new HashMap<>();
                    dataParam.put("thing1", title);
                    dataParam.put("time2", DateUtil.format(expireDate, "yyyy-MM-dd HH:mm"));
                    dataParam.put("thing3", configContent);

                    // 构建extra，只包含data和page
                    Map<String, Object> extra = new HashMap<>();
                    extra.put("data", dataParam);
                    extra.put("page", page);

                    // 使用ZT消息服务发送通知（第三次通知 - 过期提醒）
                    ZtMessage msg = new ZtMessage();
                    msg.setChannelId(templateId);
                    msg.setTitle(title);
                    msg.setContent("【" + item.getFaceId() + "】"+configContent);
                    msg.setTarget(member.getOpenId());
                    msg.setExtra(extra);
                    msg.setSendReason("第三次通知");
                    msg.setSendBiz("定时通知");
                    ztMessageProducerService.send(msg);
                });
    }

    @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());
                        // 发送模板消息
                        String templateId = scenicRepository.getVideoDownloadTemplateId(item.getScenicId());
                        if (StringUtils.isBlank(templateId)) {
                            log.info("模板消息为空");
                            return;
                        }

                        // 检查并消费通知授权
                        if (!notificationAuthUtils.checkAndConsumeAuthorization(item.getMemberId(), templateId, item.getScenicId())) {
                            log.debug("用户[memberId={}]对模板[templateId={}]授权不足，跳过额外下载通知", item.getMemberId(), templateId);
                            return;
                        }

                        ScenicConfigManager configManager = scenicRepository.getScenicConfigManager(scenicId);
                        String configTitle = configManager.getString("second_notification_title");
                        String configContent = configManager.getString("second_notification_content");

                        if (StringUtils.isBlank(configTitle) || StringUtils.isBlank(configContent)) {
                            log.info("景区[{}]未配置第一次通知内容，跳过发送通知", scenic.getName());
                            return;
                        }

                        String title = configTitle.replace("【景区】", scenic.getName());
                        String page;
                        if (configManager.getBoolean("grouping_enable", false)) {
                            page = "pages/travelVideoCenter/index?type=2&scenicId=" + item.getScenicId() + "&faceId=" + item.getFaceId();
                        } else {
                            page = "pages/videoSynthesis/index?type=2&scenicId=" + item.getScenicId() + "&faceId=" + item.getFaceId();
                        }
                        /**
                         * 景区 {{thing1.DATA}}
                         * 备注 {{thing3.DATA}}
                         */
                        Map<String, Object> dataParam = new HashMap<>();
                        dataParam.put("thing1", title);
                        dataParam.put("thing3", configContent);

                        // 构建extra，只包含data和page
                        Map<String, Object> extra = new HashMap<>();
                        extra.put("data", dataParam);
                        extra.put("page", page);

                        // 使用ZT消息服务发送通知（额外下载通知）
                        ZtMessage msg = new ZtMessage();
                        msg.setChannelId(templateId);
                        msg.setTitle(title);
                        msg.setContent("【" + item.getFaceId() + "】"+configContent);
                        msg.setTarget(member.getOpenId());
                        msg.setExtra(extra);
                        msg.setSendReason("景区额外配置：" + scenicConfig.getString("extra_notification_time"));
                        msg.setSendBiz("定时通知");
                        ztMessageProducerService.send(msg);
                    });
        });
    }
}
