package com.ruoyi.oa.service.impl;

import com.ruoyi.oa.service.IExchangeRateService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Service
public class ExchangeRateServiceImpl implements IExchangeRateService {

    @Autowired
    private RestTemplate restTemplate;

    // 汇率缓存，避免重复调用API
    private final ConcurrentHashMap<String, BigDecimal> rateCache = new ConcurrentHashMap<>();

    // 缓存过期时间（1小时）
    private static final long CACHE_EXPIRE_TIME = 60 * 60 * 1000;

    // 缓存时间记录
    private final ConcurrentHashMap<String, Long> cacheTimeMap = new ConcurrentHashMap<>();

    @Override
    public BigDecimal getCurrentUsdExchangeRate() {
        String today = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        return getUsdExchangeRate(new Date());
    }

    @Override
    public BigDecimal getUsdExchangeRate(Date date) {
        String dateStr = new SimpleDateFormat("yyyy-MM-dd").format(date);

        // 检查缓存
        if (isCacheValid(dateStr)) {
            return rateCache.get(dateStr);
        }

        try {
            // 调用汇率API
            BigDecimal rate = callExchangeRateAPI(dateStr);

            // 更新缓存
            rateCache.put(dateStr, rate);
            cacheTimeMap.put(dateStr, System.currentTimeMillis());

            log.info("获取汇率成功，日期：{}，汇率：{}", dateStr, rate);
            return rate;
        } catch (Exception e) {
            log.error("获取汇率失败，日期：{}，使用默认汇率", dateStr, e);
            // 返回默认汇率
            return new BigDecimal("7.2");
        }
    }

    /**
     * 检查缓存是否有效
     */
    private boolean isCacheValid(String dateStr) {
        Long cacheTime = cacheTimeMap.get(dateStr);
        if (cacheTime == null) {
            return false;
        }
        return (System.currentTimeMillis() - cacheTime) < CACHE_EXPIRE_TIME;
    }

    /**
     * 调用汇率API
     */
    private BigDecimal callExchangeRateAPI(String dateStr) {
        // 方式1：使用免费的汇率API
        String url = "https://api.exchangerate-api.com/v4/latest/USD";

        try {
            String response = restTemplate.getForObject(url, String.class);
            JSONObject json = JSON.parseObject(response);

            // 解析汇率数据
            JSONObject rates = json.getJSONObject("rates");
            BigDecimal rate = rates.getBigDecimal("CNY");

            if (rate != null) {
                return rate;
            }
        } catch (Exception e) {
            log.warn("调用汇率API失败，尝试备用API", e);
        }

        // 备用方案：使用其他免费API
        try {
            String backupUrl = "https://api.frankfurter.app/latest?from=USD&to=CNY";
            String response = restTemplate.getForObject(backupUrl, String.class);
            JSONObject json = JSON.parseObject(response);

            JSONObject rates = json.getJSONObject("rates");
            BigDecimal rate = rates.getBigDecimal("CNY");

            if (rate != null) {
                return rate;
            }
        } catch (Exception e) {
            log.warn("备用API也失败，使用默认汇率", e);
        }

        // 最终备用方案：使用默认汇率
        return getDefaultExchangeRate(dateStr);
    }

    /**
     * 获取默认汇率
     */
    private BigDecimal getDefaultExchangeRate(String dateStr) {
        // 根据当前年份返回不同的默认汇率
        if (dateStr.startsWith("2024")) {
            return new BigDecimal("7.2");
        } else if (dateStr.startsWith("2023")) {
            return new BigDecimal("7.1");
        } else if (dateStr.startsWith("2022")) {
            return new BigDecimal("6.9");
        } else {
            return new BigDecimal("7.0");
        }
    }
}