package com.yingpai.stock.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yingpai.stock.domain.StockPoolHistory;
import com.yingpai.stock.mapper.StockPoolHistoryMapper;
import com.yingpai.stock.service.IStockPoolAsyncService;
import com.yingpai.stock.service.IStockPoolService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.util.List;

/**
 * 股票池异步处理服务实现类
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class StockPoolAsyncServiceImpl implements IStockPoolAsyncService {

    private final StockPoolHistoryMapper stockPoolHistoryMapper;
    private final IStockPoolService stockPoolService;

    // 异步任务执行标志（静态变量，全局共享）
    private static volatile boolean isProcessing = false;

    /**
     * 检查是否有异步任务正在执行
     */
    public static boolean isProcessing() {
        return isProcessing;
    }

    @Override
    @Async
    public void asyncProcessAfterImport(LocalDate importDate) {
        // 设置处理标志
        isProcessing = true;

        log.info("[异步处理] 开始执行导入后的耗时操作，导入日期: {}, 线程: {}",
            importDate, Thread.currentThread().getName());

        // 调用数据补全功能，将历史数据补全到stock_pool表
        try {
            log.info("[数据补全] 开始补全历史数据到stock_pool表，导入日期: {}", importDate);
            String completeResult = stockPoolService.completeHistoryData(importDate);
            log.info("[数据补全] 补全结果: {}", completeResult);
        } catch (Exception e) {
            log.error("[数据补全] 补全历史数据失败: {}", e.getMessage(), e);
        }

        // 更新强势池10天最高涨幅
        try {
            log.info("[强势池10天涨幅] 开始更新强势池10天最高涨幅，导入日期: {}", importDate);
            String gainResult = stockPoolService.updateStrongPoolTenDayGain(importDate);
            log.info("[强势池10天涨幅] 更新结果: {}", gainResult);
        } catch (Exception e) {
            log.error("[强势池10天涨幅] 更新失败: {}", e.getMessage(), e);
        }

        // 回溯更新过去10天内所有记录的high_trend
        try {
            log.info("[回溯更新high_trend] 开始回溯更新，导入日期: {}", importDate);
            String updateResult = updatePastTenDaysHighTrend(importDate);
            log.info("[回溯更新high_trend] 更新结果: {}", updateResult);
        } catch (Exception e) {
            log.error("[回溯更新high_trend] 更新失败: {}", e.getMessage(), e);
        }

        log.info("[异步处理] 导入后的耗时操作全部完成，导入日期: {}, 线程: {}",
            importDate, Thread.currentThread().getName());

        // 重置处理标志
        isProcessing = false;
    }

    /**
     * 回溯更新过去10天内所有记录的high_trend
     * 当导入新的历史数据后，需要更新过去10天内所有记录的high_trend，
     * 因为这些记录的"未来10天最高价"可能会因为新数据的加入而改变
     *
     * @param importDate 当前导入的日期
     * @return 更新结果信息
     */
    private String updatePastTenDaysHighTrend(LocalDate importDate) {
        log.info("[回溯更新high_trend] 开始更新，导入日期: {}", importDate);

        // 查询过去10天内的所有历史记录（包括今天）
        LocalDate tenDaysAgo = importDate.minusDays(10);
        LambdaQueryWrapper<StockPoolHistory> lqw = Wrappers.lambdaQuery();
        lqw.ge(StockPoolHistory::getRecordDate, tenDaysAgo)
           .le(StockPoolHistory::getRecordDate, importDate);

        List<StockPoolHistory> recordsToUpdate = stockPoolHistoryMapper.selectList(lqw);

        if (recordsToUpdate.isEmpty()) {
            String message = "没有需要回溯更新的历史记录（过去10天内）";
            log.info("[回溯更新high_trend] {}", message);
            return message;
        }

        log.info("[回溯更新high_trend] 找到 {} 条需要更新的记录", recordsToUpdate.size());

        int updatedCount = 0;
        int skippedCount = 0;

        for (StockPoolHistory record : recordsToUpdate) {
            try {
                String stockCode = record.getStockCode();
                LocalDate recordDate = record.getRecordDate();
                BigDecimal dayClosePrice = record.getDayClosePrice();

                if (dayClosePrice == null || dayClosePrice.compareTo(BigDecimal.ZERO) == 0) {
                    log.warn("[回溯更新high_trend] 股票 {} 日期 {} 收盘价为空或为0，跳过",
                        stockCode, recordDate);
                    skippedCount++;
                    continue;
                }

                // 查询从记录日期到当前导入日期的最高价（向后查询，最多10天）
                BigDecimal maxHighPrice = stockPoolHistoryMapper.selectForwardTenDaysHighestPrice(
                    stockCode, recordDate, importDate);

                if (maxHighPrice == null) {
                    log.warn("[回溯更新high_trend] 股票 {} 在 [{}, {}] 范围内没有最高价数据，跳过",
                        stockCode, recordDate, importDate);
                    skippedCount++;
                    continue;
                }

                // 计算涨幅：(最高价 - 当天收盘价) / 当天收盘价 * 100
                BigDecimal highTrend = maxHighPrice.subtract(dayClosePrice)
                    .divide(dayClosePrice, 4, RoundingMode.HALF_UP)
                    .multiply(new BigDecimal("100"))
                    .setScale(2, RoundingMode.HALF_UP);

                // 更新记录
                record.setHighTrend(highTrend);
                stockPoolHistoryMapper.updateById(record);

                updatedCount++;

                log.debug("[回溯更新high_trend] 股票 {} 日期 {} 更新成功，收盘价: {}, 最高价: {}, 涨幅: {}%",
                    stockCode, recordDate, dayClosePrice, maxHighPrice, highTrend);

            } catch (Exception e) {
                log.error("[回溯更新high_trend] 股票 {} 日期 {} 更新失败: {}",
                    record.getStockCode(), record.getRecordDate(), e.getMessage(), e);
                skippedCount++;
            }
        }

        String message = String.format("回溯更新完成！成功更新 %d 条，跳过 %d 条",
            updatedCount, skippedCount);
        log.info("[回溯更新high_trend] {}", message);
        return message;
    }
}
