package com.xiang.xservice.application.script.xb.schedule.xb;

import com.alibaba.fastjson2.JSONObject;
import com.google.common.collect.Lists;
import com.xiang.xservice.basic.utils.DateUtils;
import com.xiang.xservice.application.script.xb.entity.pojo.xb.XbFundCount;
import com.xiang.xservice.application.script.xb.entity.pojo.xb.XbFundList;
import com.xiang.xservice.application.script.xb.entity.response.xbyj.fund.FundList;
import com.xiang.xservice.application.script.xb.service.DingTalkRobotService;
import com.xiang.xservice.application.script.xb.service.FundService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Author: xiang
 * @Date: 2025-05-21 13:59
 */
@Component
@RequiredArgsConstructor
@Slf4j
@RestController
public class FundCountJob {

    private final FundService fundService;
    private final DingTalkRobotService dingTalkService;
    @Scheduled(cron = "0 0 22 * * ?")
    public void countFundJob() {
        // 周六周日过滤
        if (Objects.equals(LocalDateTime.now().getDayOfWeek(), DayOfWeek.SATURDAY) ||
                Objects.equals(LocalDateTime.now().getDayOfWeek(), DayOfWeek.SUNDAY)) {
            return;
        }
        log.info("==========================[基金统计] 基金统计定时任务启动！==========================");
        List<XbFundList> lists = fundService.queryFundList();
        if (CollectionUtils.isEmpty(lists)) {
            return;
        }
        List<XbFundCount> counts = Lists.newCopyOnWriteArrayList();
        String date = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        lists.parallelStream().forEach(xbFundList -> {
            List<FundList> fund = fundService.queryTodayList(date, "2", Boolean.TRUE, Collections.singletonList(xbFundList.getCode()));
            if (CollectionUtils.isNotEmpty(fund)) {
                XbFundCount xbFundCount = new XbFundCount();
                xbFundCount.setLId(xbFundList.getId());
                xbFundCount.setCode(xbFundList.getCode());
                xbFundCount.setName(xbFundList.getName());
                xbFundCount.setChange(fund.get(0).getChange().multiply(new BigDecimal("100")).setScale(2, RoundingMode.HALF_UP));
                xbFundCount.setUpdateTime(LocalDateTime.now());
                counts.add(xbFundCount);
            }
        });
        if (CollectionUtils.isNotEmpty(counts)) {
            log.info("[基金统计] 基金统计记录，需要插入的数据:{}", JSONObject.toJSONString(counts));
            fundService.addCounts(counts);
        }
        log.info("==========================[基金统计] 基金统计定时任务结束！==========================");
    }

    @Scheduled(cron = "0 40 14 * * ? ")
    public void countFundInWeek() throws Exception {
        if (DateUtils.validWeekTime()) return;
        log.info("==========================[基金统计] 基金本周涨跌幅消息发送定时任务启动！==========================");
        List<XbFundCount> xbFundCounts = fundService.queryFundCountInWeek();
        if (CollectionUtils.isEmpty(xbFundCounts)) {
            return;
        }
        StringBuilder sb = new StringBuilder();
        Map<String, List<XbFundCount>> map = xbFundCounts.stream().collect(Collectors.groupingBy(XbFundCount::getCode));
        map.forEach((k, v) -> {
            List<XbFundCount> fundCounts = map.get(k);
            if (CollectionUtils.isEmpty(fundCounts)) {
                return;
            }
            List<BigDecimal> decimals = fundCounts.stream().map(XbFundCount::getChange).collect(Collectors.toList());
            BigDecimal sum = BigDecimal.ZERO;
            for (BigDecimal decimal : decimals) {
                sum = sum.add(decimal);
            }
            BigDecimal avg = sum.divide(BigDecimal.valueOf(decimals.size()), 2, RoundingMode.HALF_UP);
            sb.append("【").append(fundCounts.get(0).getName()).append("】本周平均涨跌幅为：").append(avg).append("\n");
        });
        if (StringUtils.isNotBlank(sb)) {
            dingTalkService.sendXbMsg(sb.toString());
        }
        log.info("==========================[基金统计] 基金本周涨跌幅消息发送定时任务结束！==========================");
    }

}
