package com.yingxin.prms.service.asyncTask;

import com.yingxin.prms.domain.Server_Host_Info;
import com.yingxin.prms.utils.SendHttpUtil;
import net.sf.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.util.EntityUtils;
import org.kairosdb.client.HttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestClientException;

import org.apache.http.client.methods.CloseableHttpResponse;

import java.io.IOException;
import java.net.SocketException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class HttpTask extends BasicTask{

    private final HttpClient httpClient;


    private static Logger logger = LoggerFactory.getLogger(HttpTask.class);

    @Autowired
    public HttpTask(HttpClient httpClient) {
        SimpleClientHttpRequestFactory httpRequestFactory = new SimpleClientHttpRequestFactory();
        httpRequestFactory.setConnectTimeout(5000);
        httpRequestFactory.setReadTimeout(5000);
        this.httpClient = httpClient;
    }

    /**
     * 查询服务状态，添加到kairosDB数据库
     * @param hostInfo
     * @param alarmHost
     */
    @Async("asyncTaskPool")
    public void doTask(Server_Host_Info hostInfo, ConcurrentHashMap<String, String> alarmHost) {
        Map<String,String> map = new HashMap();
        long dur = 0;
        long start = System.currentTimeMillis();


        try {
            if (hostInfo.getService_method().equals("post") && !hostInfo.getCluster_name().equals("网证开通接口")) {
                if(hostInfo.getRequest_body()== null){
                    map = SendHttpUtil.doPost(hostInfo.getService_path(),"");
                }else {
                    map = SendHttpUtil.doPost(hostInfo.getService_path(),hostInfo.getRequest_body());
                }
            }
            if (hostInfo.getService_method().equals("get")) {
                map = SendHttpUtil.doGet(hostInfo.getService_path());
            }
            dur = System.currentTimeMillis() - start;
        } catch (RestClientException e) {
            insertToKairos(httpClient, hostInfo.getService_path(), dur, false);
            logger.info("httpTask to {}", hostInfo.getService_path());
            logger.info(e.getMessage());
            return;
        }

        boolean flag = false;
        switch (hostInfo.getCluster_name()){
            case "VPN方式接入服务":
                flag = checkStatusCode(map);
                break;
            case "token方式接入服务":
                flag = checkStatusCode(map);
                break;
            case "日志采集服务":
                flag = checkStatusCode(map);
                break;
            case "核心调度服务":
                flag = checkStatusCode(map);
                break;
            case "token核验服务":
                flag = checkStatusCode(map);
                break;
            case "平台业务权限配置管理服务":
                flag = checkStatusCode(map);
                break;
            case "权限核验服务facl":
                flag = checkStatus(map);
                break;
            case "账户应用管理服务":
                flag = checkStatusCode(map);
                break;
            case "1比1比对(图片+图片)":
                flag = checkStatusCode(map);
                break;
            case "1比1比对(图片+特征)":
                flag = checkStatusCode(map);
                break;
            case "1比1比对（特征+特征）":
                flag = checkStatusCode(map);
                break;
            case "1比N比对(特征)":
                flag = checkStatusCode(map);
                break;
            case "1比N比对（图片）":
                flag = checkStatusCode(map);
                break;
            case "图片生成特征值":
                flag = checkStatusCode(map);
                break;
            case "依图":
                flag = checkCode(map);
                break;
            case "云从":
                flag = checkCode(map);
                break;
            default:
                flag = checkStatusCode(map);
        }
        if (map.get("body") != null && !map.get("body").isEmpty() ) {
            insertToKairos(httpClient,  hostInfo.getService_path(), dur, flag);
            logger.info("httpTask to {}|{}", hostInfo.getHost_ip(), flag);
            if (flag) {
                alarmHost.remove(hostInfo.getService_path());
            }
            return;
        }
        insertToKairos(httpClient,  hostInfo.getService_path(), dur, false);
    }

    /* 针对不同服务集群 返回结果 作不同校验  */
    private boolean checkStatusCode(Map<String,String> map) {
        if(map.containsKey("status")&&map.get("status").equals("200")){
            return true;
        }
        return false;
    }
    private boolean checkCode(Map<String,String> map) {
        JSONObject jsonObject = JSONObject.fromObject( map.get("body"));
        if(map.containsKey("body")&&map.containsKey("body")){
            String code = jsonObject.getString("code");
            if(code.equals("0")){
                return true;
            }
        }
        return false;
    }

    private boolean checkErrorCode(CloseableHttpResponse response) {
        JSONObject jsonObject = null;
        try {
            if(response == null){
                return false;
            }
            jsonObject = JSONObject.fromObject( EntityUtils.toString(response.getEntity(),"utf-8"));
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        String code = jsonObject.getString("error_code");
        if(code.equals("0")){
            return true;
        }
        return false;
    }

    private boolean checkStatus(Map<String,String> map) {
        JSONObject jsonObject = null;
        if(map.containsKey("body")&&map.containsKey("body")){
            jsonObject = JSONObject.fromObject(map.get("body"));
            String status = jsonObject.getString("status");
            if(status.equals("true")){
                return true;
            }
        }
        return false;
    }


}
