package com.ycwl.basic.task;

import cn.hutool.core.date.DateUtil;
import com.ycwl.basic.mapper.MemberMapper;
import com.ycwl.basic.mapper.ScenicMapper;
import com.ycwl.basic.mapper.VideoMapper;
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.model.pc.scenic.resp.ScenicRespVO;
import com.ycwl.basic.model.pc.template.resp.TemplateRespVO;
import com.ycwl.basic.notify.NotifyFactory;
import com.ycwl.basic.notify.adapters.INotifyAdapter;
import com.ycwl.basic.notify.entity.NotifyContent;
import com.ycwl.basic.notify.enums.NotifyType;
import com.ycwl.basic.repository.ScenicRepository;
import com.ycwl.basic.repository.TemplateRepository;
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.List;
import java.util.Map;

@Component
@EnableScheduling
@Slf4j
@Profile("prod")
public class DownloadNotificationTasker {
    @Autowired
    private ScenicRepository scenicRepository;
    @Autowired
    private VideoMapper videoMapper;
    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private TemplateRepository templateRepository;
    @Autowired
    private ScenicMapper scenicMapper;

    @Scheduled(cron = "0 0 21 * * *")
    public void sendDownloadNotification() {
        log.info("开始执行定时任务");
        videoMapper.listRelationByCreateTime(new Date(System.currentTimeMillis() - 24 * 60 * 60 * 1000), new Date())
                .forEach(item -> {
                    if (item.getIsBuy() == 1) {
                        return;
                    }
                    MemberRespVO member = memberMapper.getById(item.getMemberId());
                    MpConfigEntity scenicMp = scenicRepository.getScenicMpConfig(member.getScenicId());
                    // 发送模板消息
                    String templateId = scenicRepository.getVideoDownloadTemplateId(item.getScenicId());
                    if (StringUtils.isBlank(templateId)) {
                        log.info("模板消息为空");
                        return;
                    }
                    log.info("发送模板消息");
                    ScenicEntity scenic = scenicRepository.getScenic(item.getScenicId());
                    String title = "您在【" + scenic.getName() + "】的专属影像";
                    String page = "pages/videoSynthesis/index?type=2&scenicId=" + item.getScenicId() + "&faceId=" + item.getFaceId();
                    /**
                     * 景区 {{thing1.DATA}}
                     * 备注 {{thing3.DATA}}
                     */
                    Map<String, Object> params = new HashMap<>();
                    Map<String, Object> dataParam = new HashMap<>();
                    Map<String, String> videoMap = new HashMap<>();
                    videoMap.put("value", title);
                    dataParam.put("thing1", videoMap);
                    Map<String, String> remarkMap = new HashMap<>();
                    remarkMap.put("value", "系统删除前，请下载好您的旅行视频");
                    dataParam.put("thing3", remarkMap);
                    params.put("data", dataParam);
                    params.put("page", page);
                    params.put("template_id", templateId);
                    log.info("视频下载通知模板参数：{}，用户ID：{}", params, member.getOpenId());
                    INotifyAdapter adapter = NotifyFactory.get(NotifyType.WX_MP_SRV, scenicMp.toMap());
                    adapter.sendTo(new NotifyContent(title, page, params), member.getOpenId());
                });
    }

    @Scheduled(cron = "0 0 20 * * *")
    public void sendExpireNotification() {
        log.info("开始执行定时任务");
        videoMapper.listRelationByCreateTime(new Date(System.currentTimeMillis() - 3 * 24 * 60 * 60 * 1000), new Date(System.currentTimeMillis() - 2 * 24 * 60 * 60 * 1000))
                .forEach(item -> {
                    if (item.getIsBuy() == 1) {
                        return;
                    }
                    MemberRespVO member = memberMapper.getById(item.getMemberId());
                    MpConfigEntity scenicMp = scenicRepository.getScenicMpConfig(member.getScenicId());
                    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;
                    }
                    log.info("发送模板消息");
                    ScenicEntity scenic = scenicRepository.getScenic(item.getScenicId());
                    String title = "您在【" + scenic.getName() + "】的专属影像";
                    String page = "pages/videoSynthesis/index?type=3&scenicId=" + item.getScenicId() + "&faceId=" + item.getFaceId();
                    /**
                     * 影像名称 {{thing1.DATA}}
                     * 过期时间 {{time2.DATA}}
                     * 备注 {{thing3.DATA}}
                     */
                    Map<String, Object> params = new HashMap<>();
                    Map<String, Object> dataParam = new HashMap<>();
                    Map<String, String> videoMap = new HashMap<>();
                    videoMap.put("value", title);
                    dataParam.put("thing1", videoMap);
                    Map<String, String> dateMap = new HashMap<>();
                    Date expireDate = new Date(item.getCreateTime().getTime() + videoStoreDay * 24 * 60 * 60 * 1000);
                    dateMap.put("value", DateUtil.format(expireDate, "yyyy-MM-dd HH:mm"));
                    dataParam.put("time2", dateMap);
                    Map<String, String> remarkMap = new HashMap<>();
                    remarkMap.put("value", "视频即将删除，花点小钱买下回忆");
                    dataParam.put("thing3", remarkMap);
                    params.put("data", dataParam);
                    params.put("page", page);
                    params.put("template_id", templateId);
                    log.info("视频下载通知模板参数：{}，用户ID：{}", params, member.getOpenId());
                    INotifyAdapter adapter = NotifyFactory.get(NotifyType.WX_MP_SRV, scenicMp.toMap());
                    adapter.sendTo(new NotifyContent(title, page, params), member.getOpenId());
                });
    }

    @Scheduled(cron = "0 0 * * * *")
    public void sendExtraDownloadNotification() {
        log.info("开始执行定时任务");
        List<ScenicRespVO> scenicList = scenicMapper.list(new ScenicReqQuery());
        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 = scenic.getId();
            ScenicConfigEntity scenicConfig = scenicRepository.getScenicConfig(scenicId);
            if (scenicConfig == null) {
                return;
            }
            if (StringUtils.isEmpty(scenicConfig.getExtraNotificationTime())) {
                return;
            }
            List<String> timeList = Arrays.asList(StringUtils.split(scenicConfig.getExtraNotificationTime(), ","));
            if (!timeList.contains(String.valueOf(currentHour))) {
                return;
            }
            log.info("当前景区{}，配置了{}", scenic.getName(), scenicConfig.getExtraNotificationTime());

            videoMapper.listRelationByCreateTime(DateUtil.beginOfDay(new Date()), new Date())
                    .stream()
                    .filter(item -> item.getIsBuy() == 0)
                    .filter(item -> item.getScenicId().equals(scenicId))
                    .parallel()
                    .forEach(item -> {
                        MemberRespVO member = memberMapper.getById(item.getMemberId());
                        MpConfigEntity scenicMp = scenicRepository.getScenicMpConfig(member.getScenicId());
                        // 发送模板消息
                        String templateId = scenicRepository.getVideoDownloadTemplateId(item.getScenicId());
                        if (StringUtils.isBlank(templateId)) {
                            log.info("模板消息为空");
                            return;
                        }
                        log.info("发送模板消息");
                        String title = "您在【" + scenic.getName() + "】的专属影像";
                        String page = "pages/videoSynthesis/index?type=2&scenicId=" + item.getScenicId() + "&faceId=" + item.getFaceId();
                        /**
                         * 景区 {{thing1.DATA}}
                         * 备注 {{thing3.DATA}}
                         */
                        Map<String, Object> params = new HashMap<>();
                        Map<String, Object> dataParam = new HashMap<>();
                        Map<String, String> videoMap = new HashMap<>();
                        videoMap.put("value", title);
                        dataParam.put("thing1", videoMap);
                        Map<String, String> remarkMap = new HashMap<>();
                        remarkMap.put("value", "请及时购买并下载好您的旅行视频");
                        dataParam.put("thing3", remarkMap);
                        params.put("data", dataParam);
                        params.put("page", page);
                        params.put("template_id", templateId);
                        log.info("视频下载通知模板参数：{}，用户ID：{}", params, member.getOpenId());
                        INotifyAdapter adapter = NotifyFactory.get(NotifyType.WX_MP_SRV, scenicMp.toMap());
                        adapter.sendTo(new NotifyContent(title, page, params), member.getOpenId());
                    });
        });
    }
}
