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

import com.alibaba.fastjson.JSON;
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.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PostMapping;
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.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @Author: xiang
 * @Date: 2025-07-31 18:10
 */
@Component
@Slf4j
@RestController
@RequiredArgsConstructor
public class FundMsgReportJob {

    private final FundService fundService;
    private final DingTalkRobotService dingTalkService;
    private static final Integer TYPE_A = 1;
    private static final Integer TYPE_M = 3;
    private static final Integer TYPE_G = 2;

    @Scheduled(cron = "0 1,31 9,10,11,13,14 * * ?")
    @PostMapping("/asdasda")
    public void fundReport4A() {
        log.info("===========A股基金变化通知！===========");
        // 周六周日过滤
        if (Objects.equals(LocalDateTime.now().getDayOfWeek(), DayOfWeek.SATURDAY) ||
                Objects.equals(LocalDateTime.now().getDayOfWeek(), DayOfWeek.SUNDAY)) {
            log.info("当前时间为：{}", LocalDateTime.now());
            return;
        }
        List<XbFundList> fundLists = fundService.queryFundList(TYPE_A);
        if (CollectionUtils.isEmpty(fundLists)) {
            log.info("查询配置的A股信息为空");
            return;
        }
        Map<String, XbFundList> fundMap = fundLists.stream().collect(Collectors.toMap(XbFundList::getCode, Function.identity(), (a, b) -> a));
        String date = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        List<FundList> funds = fundService.queryTodayList(date, "2", Boolean.TRUE, new ArrayList<>(fundMap.keySet()));
        if (CollectionUtils.isEmpty(funds)) {
            log.info("http请求查询基金信息为空");
            return;
        }
        log.info("http查询基金信息:{}", JSON.toJSONString(funds));
        StringBuilder msg = new StringBuilder(date).append("===》A股基金变化通知:\n");
        buildMsg(funds, fundMap, msg);
        dingTalkService.sendXbMsg(msg.toString());
    }

    @Scheduled(cron = "0 1,31 9,10,11,13,14,15 * * ?")
    public void fundReport4G() {
        log.info("===========港股基金变化通知！===========");
        // 周六周日过滤
        if (Objects.equals(LocalDateTime.now().getDayOfWeek(), DayOfWeek.SATURDAY) ||
                Objects.equals(LocalDateTime.now().getDayOfWeek(), DayOfWeek.SUNDAY)) {
            log.info("当前时间为：{}", LocalDateTime.now());
            return;
        }
        List<XbFundList> fundLists = fundService.queryFundList(TYPE_G);
        if (CollectionUtils.isEmpty(fundLists)) {
            log.info("查询配置的港股信息为空");
            return;
        }
        Map<String, XbFundList> fundMap = fundLists.stream().collect(Collectors.toMap(XbFundList::getCode, Function.identity(), (a, b) -> a));
        String date = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        List<FundList> funds = fundService.queryTodayList(date, "2", Boolean.TRUE, new ArrayList<>(fundMap.keySet()));
        if (CollectionUtils.isEmpty(funds)) {
            log.info("http请求查询基金信息为空");
            return;
        }
        log.info("http查询港股基金信息:{}", JSON.toJSONString(funds));
        StringBuilder msg = new StringBuilder(date).append("===》港股基金变化通知:\n");
        buildMsg(funds, fundMap, msg);
        dingTalkService.sendXbMsg(msg.toString());
    }

    @Scheduled(cron = "0 0 9 * * ?")
    public void fundReport4M() {
        log.info("===========美股基金变化通知！===========");
        // 周六周日过滤
        if (Objects.equals(LocalDateTime.now().getDayOfWeek(), DayOfWeek.SATURDAY) ||
                Objects.equals(LocalDateTime.now().getDayOfWeek(), DayOfWeek.SUNDAY)) {
            log.info("当前时间为：{}", LocalDateTime.now());
            return;
        }
        List<XbFundList> fundLists = fundService.queryFundList(TYPE_M);
        if (CollectionUtils.isEmpty(fundLists)) {
            log.info("查询配置的美股信息为空");
            return;
        }
        Map<String, XbFundList> fundMap = fundLists.stream().collect(Collectors.toMap(XbFundList::getCode, Function.identity(), (a, b) -> a));
        String date = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        List<FundList> funds = fundService.queryTodayList(date, "2", Boolean.TRUE, new ArrayList<>(fundMap.keySet()));
        if (CollectionUtils.isEmpty(funds)) {
            log.info("http请求查询基金信息为空");
            return;
        }
        log.info("http查询美股基金信息:{}", JSON.toJSONString(funds));
        StringBuilder msg = new StringBuilder(date).append("===》美股基金变化通知:\n");
        buildMsg(funds, fundMap, msg);
        dingTalkService.sendXbMsg(msg.toString());
    }

    private static void buildMsg(List<FundList> funds, Map<String, XbFundList> fundMap, StringBuilder msg) {
        funds = funds.stream().sorted(Comparator.comparing(FundList::getChange).reversed())
                .collect(Collectors.toList());
        for (FundList fund : funds) {
            if (fundMap.containsKey(fund.getCode())) {
                XbFundList fundList = fundMap.get(fund.getCode());
                msg.append("基金名称:")
                        .append(fundList.getName())
                        .append("涨跌幅:")
                        .append(fund.getChange()
                                .multiply(new BigDecimal("100"))
                                .setScale(2, RoundingMode.HALF_UP))
                        .append("\n");
            }
        }
    }
}
