package com.jxy.marketall.Therad;

import com.alibaba.fastjson.JSONObject;
import com.jxy.common.core.utils.DateUtils;
import com.jxy.common.core.utils.SpringUtils;
import com.jxy.common.core.utils.StringUtils;
import com.jxy.common.core.web.Result.AjaxResult;
import com.jxy.marketall.entity.BiAn;
import com.jxy.marketall.enums.SymbolType;
import com.jxy.marketall.service.impl.BiAnServiceImpl;
import com.jxy.marketall.utils.EnumUtils;
import com.jxy.marketall.utils.MyWebSocketClient;
import com.jxy.marketall.vo.BiAnVo;
import com.jxy.marketall.websocket.WebSocketService;
import org.java_websocket.client.WebSocketClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @Description TODO
 * @Date 2022/6/30 18:49
 * @Author 杜懿
 */
public class SocketThread implements Runnable {

    private Logger log = LoggerFactory.getLogger(SocketThread.class);

    private BiAnServiceImpl biAnService;

    private WebSocketService webSocketService;
    private MyWebSocketClient myWebSocketClient = new MyWebSocketClient();
    private String message;
    private BiAnVo biAnVo;

    public SocketThread(WebSocketService webSocketService, String message) {
        this.webSocketService = webSocketService;
        this.message = message;
        //构造条件
        BiAnVo biAnVo = new BiAnVo();
        String[] params = message.split(",");

        String interval = params[0];
        String symbol = params[1];

        biAnVo.setSymbol(symbol);
        biAnVo.setTimeInterval(params[0]);

        //根据时间间隔设置查询的开始时间
        Date date = this.webSocketService.getDate();
        Calendar ca = new GregorianCalendar();
        ca.setTime(date);
        //Date end = ca.getTime();
        //biAnVo.setEnd(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,end));
        ca.add(ca.MINUTE,-1);
        biAnVo.setStart(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,ca.getTime()));

        this.biAnVo = biAnVo;
    }

    @Override
    public void run() {
        biAnService = SpringUtils.getBean("biAnService");
        String intetval = biAnVo.getTimeInterval().replace("min","m");
        String symbol = biAnVo.getSymbol();
        if(!EnumUtils.isInclude(SymbolType.class,symbol)){
            if("1INCHUSDT".equals(symbol) || "1000SHIBUSDT".equals(symbol) || "1000XECUSDT".equals(symbol)){
               symbol = symbol.toLowerCase();
            }else {
                throw new RuntimeException("交易对不存在");
            }
        }else{
            SymbolType symbolType = (SymbolType) EnumUtils.get(SymbolType.class, symbol);
            symbol = symbolType.getInfo();
        }
        String url = "wss://fstream.binance.com/stream?streams="+symbol.toLowerCase()+"@kline_"+intetval;
        WebSocketClient client = myWebSocketClient.getWS(url);
        try {
            List<BiAn> biAnList = null;
            while (!Thread.currentThread().isInterrupted()){
                BiAnVo vo = new BiAnVo();
                BeanUtils.copyProperties(this.biAnVo,vo);
                //获取实时数据
                biAnList = getData(vo);
                if(biAnList.size() > 0){
                    //System.out.println(message+"将要推送的信息："+biAnList);
                    webSocketService.sendMessage(webSocketService.getUserName(),JSONObject.toJSONString(AjaxResult.success(biAnList)));
                }
                Thread.sleep(1000);
            }

        }catch (InterruptedException e){
            //断开币安提供的websocket
            myWebSocketClient.setBiAn(null);
            client.close();
            Thread curr = Thread.currentThread();
            //再次调用interrupt方法中断自己，将中断状态设置为“中断”
            try {
                Thread.sleep(1000);
            } catch (InterruptedException interruptedException) {
                interruptedException.printStackTrace();
            }
            curr.interrupt();
        }
    }
    public List<BiAn> getData(BiAnVo biAnVo){
        //System.out.println("查询条件："+biAnVo+"时间"+biAnVo.getStart());

        List<BiAn> realTimeData = biAnService.getRealTimeData(biAnVo);
        BiAn biAn = myWebSocketClient.getData();

        if(StringUtils.isNotNull(biAn.getSymbol())){
            realTimeData.add(biAn);
        }
        return realTimeData;
    }

}
