package com.lutao.cloud.oil;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.google.common.collect.ImmutableMap;
import org.apache.commons.collections4.CollectionUtils;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

/**
 * @description: 台风路径信息同步
 * @author: vincent.zhao
 * @create: 2021-12-07 10:10
 **/
public class TyphoonFindTyphoonThread {

    protected Logger logger = LoggerFactory.getLogger(getClass());

//    @Resource
//    private TyphoonPointInfoService typhoonPointInfoService;

    /**
     * @Description: 数据同步
     * @Param: [java.lang.String]
     * @Return: java.lang.Integer
     * @Author: vincent.zhao
     * @Date: 2021/12/9 11:20
     */
    private Integer syncDataInfo(String str) throws Exception {

        logger.debug("TyphoonFindTyphoonThread threadName:{}， param:{}", threadName, str);
        DataAPIUtils.getSyncTokenIP59255615(); // 获取token

        URL realUrl = new URL("http://" + BusiConstant.IP_59_255_61_5 + ":" + BusiConstant.PORT_9090 + "/service/api/typhoon/findTyphoon");

        // 打开和URL之间的连接
        HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
        conn.setRequestProperty("content-type", "application/json");
        conn.setRequestProperty("client_id", BusiConstant.APP_USER_NAME_01);
        conn.setRequestProperty("access_token", BusiConstant.YJBZYC_TOKEN_59_255_61_5);
        conn.setRequestMethod("POST"); // 设定请求的方法为"POST"，默认是GET
        // 发送POST请求必须设置如下两行
        conn.setReadTimeout(1000 * 60);
        conn.setConnectTimeout(1000 * 60);
        conn.setDoOutput(true); // 允许输入流，即允许下载
        conn.setDoInput(true); // 允许输出流，即允许上传

        // 获取URLConnection对象对应的输出流
        PrintWriter out = new PrintWriter(conn.getOutputStream());

        out.print(JSONUtil.toJsonStr(ImmutableMap.of("tfbh", "202408"))); // 发送请求参数
        out.flush(); // flush输出流的缓冲

        InputStream is = conn.getInputStream();
        BufferedReader bf = new BufferedReader(new InputStreamReader(is));
        String line;
        String result = "";
        while ((line = bf.readLine()) != null) {
            result += line;
        }

        JSONObject jsonObject = JSONUtil.parseObj(result);
        JSONArray jsonArray = jsonObject.getJSONArray("data");
        JSONObject pointses = jsonArray.getJSONObject(0);
        JSONArray array = pointses.getJSONArray("pointses");
        logger.debug("TyphoonFindTyphoonThread threadName:{}， jsonArray:{}", threadName, pointses.size());

        //List<TyphoonPointses> insertList = JSONUtil.string2Obj(array.toString(), List.class, TyphoonPointses.class);
        List<TyphoonPointses> insertList = array.toList(TyphoonPointses.class);

        if (CollectionUtils.isNotEmpty(insertList)) {
            logger.info("TyphoonFindTyphoonThread threadName:{}， 待添加数:{}", threadName, insertList.size());

//            for (TyphoonPointses typhoonPointses : insertList) {
//                //清楚旧数据
//                typhoonPointInfoService.remove(Wrappers.lambdaQuery(TyphoonPointInfo.class).eq(TyphoonPointInfo::getCode, typhoonPointses.getTfbh()));
//                TyphoonPointInfo typhoonPointInfo = new TyphoonPointInfo();
//                typhoonPointInfo.setCode(typhoonPointses.getTfbh());
//                typhoonPointInfo.setLat(typhoonPointses.getLat());
//                typhoonPointInfo.setLon(typhoonPointses.getLng());
//                typhoonPointInfo.setMoveSpeed(typhoonPointses.getMovespeed());
//                typhoonPointInfo.setMoveDir(typhoonPointses.getMovedir());
//                typhoonPointInfo.setPower(Double.valueOf(typhoonPointses.getPower()));
//                typhoonPointInfo.setPressure(Double.valueOf(typhoonPointses.getPressure()));
//                typhoonPointInfo.setRadius7(typhoonPointses.getRadius7());
//                typhoonPointInfo.setRadius10(typhoonPointses.getRadius10());
//                typhoonPointInfo.setRadius12(typhoonPointses.getRadius12());
//                typhoonPointInfo.setSpeed(Double.valueOf(typhoonPointses.getSpeed()));
//                typhoonPointInfo.setStrong(typhoonPointses.getStrong());
//                typhoonPointInfo.setTime(typhoonPointses.getTime());
//                typhoonPointInfo.setType(TyphoonPointInfo.FORECAST_TYPE);
//                typhoonPointInfo.setTyphoonId(typhoonPointses.getTfbh());
//                typhoonPointInfoService.save(typhoonPointInfo);
//            }
            return insertList.size();
        }

        return 0;
    }


    /**
     * 线程名
     */
    private String threadName;
    /**
     * 请求json字符串
     */
    private String tfbh;



    @Test
    public void run() throws Exception {
        logger.debug("threadName:{}", threadName);
        syncData(tfbh);
    }



    /**
     * @Description:递归调用
     * @Param: [java.lang.Integer]
     * @Return:
     * @Author: vincent.zhao
     * @Date: 2021/12/6 11:54
     */
    private Integer syncData(String str) throws Exception {
        logger.debug("threadName:{}", threadName);
        try {
            return syncDataInfo(str);
        } catch (Exception e) {
            logger.error("errorMsg:{}", e.getMessage());
            if (e.getMessage().contains("code: 401")) {
                BusiConstant.YJBZYC_TOKEN_59_255_61_5 = null;
                DataAPIUtils.getSyncTokenIP59255615();
            }
            return syncDataInfo(str);
        }
    }
}
