package com.jxy.marketall.task;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jxy.common.core.utils.DateUtils;
import com.jxy.common.redis.service.RedisService;
import com.jxy.marketall.dto.CirculatingSupplyDataDto;
import com.jxy.marketall.mapper.ETHRTMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.math.BigDecimal;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URI;
import java.time.Instant;
import java.util.*;

import static com.jxy.common.core.utils.DateUtils.getZeroTimeOfToday;


/**
 * @Description 稳定币流通量
 * @Date 2022/7/7 18:03
 * @Author 杜懿
 */
@Configuration
@EnableScheduling
public class CSupplyTask {

    private static final Logger log = LoggerFactory.getLogger(CSupplyTask.class);

    @Autowired
    private ETHRTMapper ethrtMapper;

    @Autowired
    private RedisService redisService;

    /**                        调用api拿取当天数据                              */
    /**
     * USDT累积流通量
     */
    //@Scheduled(cron = "0/2 3 1,8,12,14,16,17 * * ?")
    @Scheduled(cron = "0 2 0/1 * * ?")
    public void CSUSDTToDB(){
        String id = "tether";
        List<CirculatingSupplyDataDto> list = getDatasFromCoingeckoApi(id);

        System.out.println("usdt入库数据:"+list);
        //数据批量入库
        ethrtMapper.batchInsertCSUSDT(list);
    }

    /**
     * USDC累积流通量
     */
    //@Scheduled(cron = "0/2 3 1,8,12,14,16,17 * * ?")
    @Scheduled(cron = "0 2 0/1 * * ?")
    public void CSUSDCToDB(){
        String id = "usd-coin";
        List<CirculatingSupplyDataDto> list = getDatasFromCoingeckoApi(id);
        System.out.println("usdc入库数据:"+list);
        //数据批量入库
        ethrtMapper.batchInsertCSUSDC(list);
    }

    /**
     * BUSD累积流通量
     */
    //@Scheduled(cron = "0/2 3 1,8,12,14,16,17 * * ?")
    @Scheduled(cron = "0 2 0/1 * * ?")
    public void CSBUSDToDB(){
        String id = "binance-usd";
        List<CirculatingSupplyDataDto> list = getDatasFromCoingeckoApi(id);
        System.out.println("busd入库数据:"+list);
        //数据批量入库
        ethrtMapper.batchInsertCSBUSD(list);
    }




    private static final String[] COINS = {"tether", "usd-coin", "binance-usd"};
    private static final String[] SYMBOLS = {"USDT", "USDC", "BUSD"};
    private static final String API_URL = "https://api.coingecko.com/api/v3/coins/";

    /**
     * 从Coingecko第三方获取币种流通量
     * @param coinId
     * @return
     */
    public  List<CirculatingSupplyDataDto> getDatasFromCoingeckoApi(String coinId) {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type","application/json");
        headers.add("x-cg-demo-api-key","CG-kNuNBTKBcQREBSQKqgj2uua4");
        headers.add("User-Agent", "Mozilla/5.0");
        HttpEntity<String> httpEntity = new HttpEntity<String>(null, headers);
        StringBuffer paramsURL = new StringBuffer(API_URL+coinId);
        String s = HttpUtil.get(paramsURL.toString());

        JSONObject jsonObject = JSONObject.parseObject(s);
        //币种流通量字段
        JSONObject marketData = jsonObject.getJSONObject("market_data");
        //String dateString;
        //try {
        //    //币种流通量最后更新时间
        //    dateString = (String) marketData.get("last_updated");
        //}catch (Exception e){
        //    return null;
        //}
        //Instant instant = Instant.parse(dateString);
        //Date date = Date.from(instant);
        Date zeroTimeOfToday = getZeroTimeOfToday();
        double doubleValue = marketData.getDoubleValue("circulating_supply");
        List<CirculatingSupplyDataDto> circulatingSupplyDataDtos = new ArrayList<>();
        CirculatingSupplyDataDto circulatingSupplyDataDto = new CirculatingSupplyDataDto();
        circulatingSupplyDataDto.setValue(BigDecimal.valueOf(doubleValue));
        circulatingSupplyDataDto.setDate(zeroTimeOfToday);
        circulatingSupplyDataDtos.add(circulatingSupplyDataDto);
        log.info("获取{}币流通量数据成功,最新时间{},流通量{}", coinId, zeroTimeOfToday, doubleValue);
        return circulatingSupplyDataDtos;
    }


    /**
     * 第三方api接口已弃用
     * @param id
     * @return
     */
    @Deprecated
    public List<CirculatingSupplyDataDto> getDatasFromMessariApi(String id){
        //入参及头文件
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type","application/json");
        headers.add("x-messari-api-key","mo8F5l6ccOBfADlA6G-JcsajXHNb3AYrAoswtFP5VEmOqLum");
        HttpEntity<String> httpEntity = new HttpEntity<String>(null, headers);
        StringBuffer paramsURL = new StringBuffer("https://data.messari.io/api/v1/assets/"+id+"/metrics/sply-circ/time-series");

        Calendar calendar = Calendar.getInstance(Locale.CHINA);
        calendar.add(Calendar.DATE,-7);
        Date time = calendar.getTime();
        paramsURL.append("?beg="+DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD,time));

        //calendar.add(Calendar.DATE,3);
        //Date endDate = calendar.getTime();
        //
        //paramsURL.append("&end="+ DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD,endDate));
        paramsURL.append("&interval="+"1d");

        URI uri = URI.create(paramsURL.toString());

        String s = HttpUtil.get(paramsURL.toString());

        JSONObject jsonObject = JSONObject.parseObject(s);


        String data = jsonObject.get("data").toString();


        JSONObject dataJson = JSONObject.parseObject(data);

        JSONArray values = dataJson.getJSONArray("values");

        List<CirculatingSupplyDataDto> list = new ArrayList<>();

        for(int i = 0 ; i < values.size(); i++){
            JSONArray value = values.getJSONArray(i);
            Long dateLong = value.getLong(0);
            Date date = new Date(dateLong);
            BigDecimal v = value.getBigDecimal(1);
            CirculatingSupplyDataDto dto = new CirculatingSupplyDataDto();
            dto.setDate(date);
            dto.setValue(v);
            list.add(dto);
        }

        return  list;
    }



}
