package com.fs.app.task;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.fs.common.annotation.DistributeLock;
import com.fs.newAdv.domain.Lead;
import com.fs.newAdv.service.ILeadService;
import com.fs.newAdv.service.ISiteStatisticsService;
import com.fs.qw.domain.QwAssignRuleUser;
import com.fs.qw.domain.QwGroupLiveCode;
import com.fs.qw.service.IQwAssignRuleUserService;
import com.fs.qw.service.IQwGroupLiveCodeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 数据同步定时任务
 * 每2小时执行一次，拉取各平台账户数据
 *
 * @author zhangqin
 * @date 2025-11-03
 */
@Slf4j
@Component
public class DataSyncTask {


    @Autowired
    private ISiteStatisticsService statisticsService;
    @Autowired
    private ILeadService leadService;
    @Autowired
    private IQwGroupLiveCodeService qwGroupLiveCodeService;
    @Autowired
    private IQwAssignRuleUserService qwAssignRuleUserService;


    /**
     * 数据同步任务->同步昨日数据
     * cron: 每天00:10
     */
    @Scheduled(cron = "0 10 0 * * ?")
    @DistributeLock(scene = "task", key = "sync_yesterday_data", waitTime = 0, errorMsg = "sync_yesterday_data任务已执行")
    public void syncYesterdayData() {
        String batchNo = DateUtil.format(LocalDateTime.now().minusDays(1), "yyyy-MM-dd");
        statisticsService.syncData(batchNo, 1);
    }

    /**
     * 数据同步任务->当日数据
     * cron: 每1小时统计站点数据
     */
    @Scheduled(cron = "0 0 0/1 * * ?")
    @DistributeLock(scene = "task", key = "sync_today_data", waitTime = 0, errorMsg = "sync_today_data任务已执行")
    public void syncTodayData() throws InterruptedException {
        String batchNo = DateUtil.format(LocalDateTime.now(), "yyyy-MM-dd");
        statisticsService.syncData(batchNo, 1);
    }


    /**
     * 今日加群数据
     * cron: 每1小时统计站点数据
     */
    @Scheduled(cron = "0 0 0/1 * * ?")
    @DistributeLock(scene = "task", key = "wei_chat_group_to_day_data", waitTime = 0, errorMsg = "wei_chat_group_to_day_data任务已执行")
    public void weiChatGroupToDayData() {
        // 统计今日加群数量
        Optional.ofNullable(leadService.getToDayGroupNum())
                .orElse(Collections.emptyList())
                .stream()
                .map(Lead::getQwGroupLiveCodeId)
                .filter(Objects::nonNull)
                .collect(Collectors.groupingBy(
                        Function.identity(),
                        Collectors.counting()
                ))
                .forEach((k, v) -> {
                    if (v > 0) {
                        qwGroupLiveCodeService.update(
                                new LambdaUpdateWrapper<QwGroupLiveCode>()
                                        .eq(QwGroupLiveCode::getId, k)
                                        .set(QwGroupLiveCode::getToDayNum, v)
                        );
                    }
                });
    }

    /**
     * 累计加群数据
     * cron: 每天00:20
     */
    @Scheduled(cron = "0 20 0 * * ?")
    @DistributeLock(scene = "task", key = "wei_chat_group_count_data", waitTime = 0, errorMsg = "wei_chat_group_count_data任务已执行")
    public void weiChatGroupCountData() {
        // 统计累积加群数量
        Optional.ofNullable(leadService.getYesterdayGroupNum())
                .orElse(Collections.emptyList())
                .stream()
                .map(Lead::getQwGroupLiveCodeId)
                .filter(Objects::nonNull)
                .collect(Collectors.groupingBy(
                        Function.identity(),
                        Collectors.counting()
                ))
                .forEach((k, v) -> {
                    if (v > 0) {
                        QwGroupLiveCode byId = qwGroupLiveCodeService.getById(k);
                        byId.setCountNum(byId.getCountNum() + v.intValue());
                        qwGroupLiveCodeService.updateById(byId);
                    }
                });
    }


    /**
     * 微信当天数据
     * cron: 一小时执行一次
     */
    @Scheduled(cron = "0 0 0/1 * * ?")
    @DistributeLock(scene = "task", key = "wei_chat_to_day_data", waitTime = 0, errorMsg = "wei_chat_to_day_data任务已执行")
    public void weiChatToDayData() {
        // 统计累积加微数量
        Optional.ofNullable(leadService.getToDayWeiChatNum())
                .ifPresent(item -> {
                            // 统计分配数
                            item.stream()
                                    .map(Lead::getQwAssignRuleUserId)
                                    .filter(Objects::nonNull)
                                    .collect(Collectors.groupingBy(
                                            Function.identity(),
                                            Collectors.counting()
                                    ))
                                    .forEach((k, v) -> {
                                        if (v > 0) {
                                            qwAssignRuleUserService.update(
                                                    new LambdaUpdateWrapper<QwAssignRuleUser>()
                                                            .eq(QwAssignRuleUser::getId, k)
                                                            .set(QwAssignRuleUser::getAssignNumToDay, v)
                                            );
                                        }
                                    });
                            // 统计添加数
                            item.stream()
                                    .filter(data -> data.getAddContactQw().equals(1))
                                    .map(Lead::getQwAssignRuleUserId)
                                    .filter(Objects::nonNull)
                                    .collect(Collectors.groupingBy(
                                            Function.identity(),
                                            Collectors.counting()
                                    ))
                                    .forEach((k, v) -> {
                                        if (v > 0) {
                                            qwAssignRuleUserService.update(
                                                    new LambdaUpdateWrapper<QwAssignRuleUser>()
                                                            .eq(QwAssignRuleUser::getId, k)
                                                            .set(QwAssignRuleUser::getAddNumToDay, v)
                                            );
                                        }
                                    });
                        }
                );
    }

    /**
     * 微信累计数据
     * cron: 每天00:30
     */
    @Scheduled(cron = "0 30 0 * * ?")
    @DistributeLock(scene = "task", key = "wei_chat_count_data", waitTime = 0, errorMsg = "wei_chat_count_data任务已执行")
    public void weiChatCountData() {
        // 统计累积加微数量
        Optional.ofNullable(leadService.getYesterdayWeiChatNum())
                .ifPresent(item -> {
                            // 统计分配数
                            item.stream()
                                    .map(Lead::getQwAssignRuleUserId)
                                    .filter(Objects::nonNull)
                                    .collect(Collectors.groupingBy(
                                            Function.identity(),
                                            Collectors.counting()
                                    ))
                                    .forEach((k, v) -> {
                                        if (v > 0) {
                                            QwAssignRuleUser byId = qwAssignRuleUserService.getById(k);
                                            qwAssignRuleUserService.update(
                                                    new LambdaUpdateWrapper<QwAssignRuleUser>()
                                                            .eq(QwAssignRuleUser::getId, k)
                                                            .set(QwAssignRuleUser::getAssignNumCount, v + byId.getAssignNumCount())
                                            );
                                        }
                                    });
                            // 统计添加数
                            item.stream()
                                    .filter(data -> data.getAddContactQw().equals(1))
                                    .map(Lead::getQwAssignRuleUserId)
                                    .filter(Objects::nonNull)
                                    .collect(Collectors.groupingBy(
                                            Function.identity(),
                                            Collectors.counting()
                                    ))
                                    .forEach((k, v) -> {
                                        if (v > 0) {
                                            QwAssignRuleUser byId = qwAssignRuleUserService.getById(k);
                                            qwAssignRuleUserService.update(
                                                    new LambdaUpdateWrapper<QwAssignRuleUser>()
                                                            .eq(QwAssignRuleUser::getId, k)
                                                            .set(QwAssignRuleUser::getAddNumCount, v + byId.getAddNumCount())
                                            );
                                        }
                                    });
                        }
                );
    }
}

