package com.weaver.seconddev.chapanda.beisen.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.weaver.seconddev.chapanda.beisen.constant.Constants;
import okhttp3.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import java.io.IOException;


@Component
public class Performance2BeiSenUtil {
    private final static Logger log = LoggerFactory.getLogger(Performance2BeiSenUtil.class);

    /***
     *
     * @param token
     * @param page
     * @param capacity
     * @param year
     * @param period
     */
    public String getActivityManagerCount(String token,String page,String capacity,String year,String period){
        String bodyData = "";
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        MediaType mediaType = MediaType.parse("text/plain");
        JSONObject bodyJson = new JSONObject();
        bodyJson.put("page",page);
        bodyJson.put("capacity",capacity);
        bodyJson.put("year",year);
        bodyJson.put("period",period);
        log.error("bodyJson:{}",bodyJson.toJSONString());

        // "{\n  \"page\": 0,\n  \"capacity\": 10,\n  \"year\": 2024,\n  \"period\": 8\n}"
        // "https://openapi.italent.cn/PerformanceCloudOpen/api/v5/ActivityManager/GetActivityManagers"

        RequestBody body = RequestBody.create(mediaType, bodyJson.toJSONString());
        try {
            Request request = new Request.Builder()
                    .url(Constants.beishenHost+Constants.activityManagerUrl)
                    .method("POST", body)
                    .addHeader("Authorization", "Bearer "+token)
                    .addHeader("Content-Type", "text/plain")
                    .build();
            Response response = client.newCall(request).execute();

            int code = response.code();
            log.error("code:{}",code);
            if(code == 200){
                bodyData = response.body().string();
            }else{
                String msg = response.body().string();
                log.error("msg:{}",msg);
            }

            log.error("bodyData:{}",bodyData);
        } catch (IOException e) {
            log.error("e:{}",e.getMessage());
            throw new RuntimeException(e);
        }
        return bodyData ;
    }


    public JSONArray queryActivityManager(String token,String page,String capacity,String year,String period){
        JSONArray performanceArray = new JSONArray();
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        MediaType mediaType = MediaType.parse("text/plain");
        JSONObject bodyJson = new JSONObject();
        bodyJson.put("page",page);
        bodyJson.put("capacity",capacity);
        bodyJson.put("year",year);
        bodyJson.put("period",period);
        log.error("bodyJson:{}",bodyJson.toJSONString());
        // "{\n  \"page\": 0,\n  \"capacity\": 10,\n  \"year\": 2024,\n  \"period\": 8\n}"
        // "https://openapi.italent.cn/PerformanceCloudOpen/api/v5/ActivityManager/GetActivityManagers"

        RequestBody body = RequestBody.create(mediaType, bodyJson.toJSONString());
        try {
            Request request = new Request.Builder()
                    .url(Constants.beishenHost+Constants.activityManagerUrl)
                    .method("POST", body)
                    .addHeader("Authorization", "Bearer "+token)
                    .addHeader("Content-Type", "text/plain")
                    .build();
            Response response = client.newCall(request).execute();

            int code = response.code();
            String msg = response.body().string();
            log.error("code:{}",code);
            log.error("msg:{}",msg);
            if(code == 200){
                if(StringUtils.isNotBlank(msg)){
                    JSONObject returnJson = JSONObject.parseObject(msg);
                    if(returnJson.containsKey("code")){
                        String dataCode = returnJson.getString("code");
                        if("200".equals(dataCode)){
                            JSONObject dataObject = returnJson.getJSONObject("data");
                            if(dataObject.containsKey("items")){
                                JSONArray itemsArray = dataObject.getJSONArray("items");
                                performanceArray.addAll(itemsArray);
                            }
                        }
                    }
                }
            }else{
                log.error("msg:{}",msg);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return performanceArray;
    }


    public String getAssessmentItemCount(String token,String page,String capacity,String activityManagerId){
        String bodyData = "";
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        MediaType mediaType = MediaType.parse("application/json");
        JSONObject bodyJson = new JSONObject();
        bodyJson.put("page",page);
        bodyJson.put("capacity",capacity);
        bodyJson.put("activityManagerId",activityManagerId);
        JSONObject sortJson = new JSONObject();
        sortJson.put("Name",-1);
        bodyJson.put("sort",sortJson);
        log.error("bodyJson:{}",bodyJson.toJSONString());
        // "{\n    \"page\": 0,\n    \"capacity\": 10,\n    \"sort\": {\n        \"Name\": -1\n    },\n    \"activityManagerId\": \"62822578-2bba-4980-9826-00689705c58d\"\n    \n}"
        // "https://openapi.italent.cn/PerformanceCloudOpen/api/v5/AssessmentItem/GetAssessmentItems"
        RequestBody body = RequestBody.create(mediaType, bodyJson.toJSONString());

        try {
            Request request = new Request.Builder()
                    .url(Constants.beishenHost+Constants.assessmentItemUrl)
                    .method("POST", body)
                    .addHeader("Authorization", "Bearer "+token)
                    .addHeader("Content-Type", "application/json")
                    .build();
            Response response = client.newCall(request).execute();
            int code = response.code();
            log.error("code:{}",code);
            if(code == 200){
                bodyData = response.body().string();
            }else{
                String msg = response.body().string();
                log.error("msg:{}",msg);
            }
        } catch (IOException e) {
            log.error("e:{}",e.getMessage());
            throw new RuntimeException(e);
        }

        return bodyData;
    }

    public JSONArray queryAssessmentItem(String token,String page,String capacity,String activityManagerId){
        JSONArray assessmentItemArray = new JSONArray();
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        MediaType mediaType = MediaType.parse("application/json");
        JSONObject bodyJson = new JSONObject();
        bodyJson.put("page",page);
        bodyJson.put("capacity",capacity);
        bodyJson.put("activityManagerId",activityManagerId);
        JSONObject sortJson = new JSONObject();
        sortJson.put("Name",-1);
        bodyJson.put("sort",sortJson);
        log.error("bodyJson:{}",bodyJson.toJSONString());

        RequestBody body = RequestBody.create(mediaType, bodyJson.toJSONString());
        try {
            Request request = new Request.Builder()
                    .url(Constants.beishenHost+Constants.assessmentItemUrl)
                    .method("POST", body)
                    .addHeader("Authorization", "Bearer "+token)
                    .addHeader("Content-Type", "application/json")
                    .build();

            Response response = client.newCall(request).execute();

            int code = response.code();
            String msg = response.body().string();

            log.error("code:{}",code);
            log.error("msg:{}",msg);

            if(code == 200){
                if(StringUtils.isNotBlank(msg)){
                    JSONObject returnJson = JSONObject.parseObject(msg);
                    if(returnJson.containsKey("code")){
                        String dataCode = returnJson.getString("code");
                        if("200".equals(dataCode)){
                            JSONObject dataObject = returnJson.getJSONObject("data");
                            if(dataObject.containsKey("items")){
                                JSONArray itemsArray = dataObject.getJSONArray("items");
                                assessmentItemArray.addAll(itemsArray);
                            }
                        }
                    }
                }
            }else{
                log.error("msg:{}",msg);
            }
        } catch (IOException e) {
            log.error("e:{}",e.getMessage());
            throw new RuntimeException(e);
        }
        return assessmentItemArray;
    }



//    public String getAssessmentCount(String token,String activityManagerId){
//        String bodyData = "";
//        OkHttpClient client = new OkHttpClient().newBuilder()
//                .build();
//        MediaType mediaType = MediaType.parse("application/json");
//        JSONObject bodyJson = new JSONObject();
//        String[] columns = new String[]{"_id","Name","ModifiedTime","ActivityManagerId"};
//        bodyJson.put("columns",columns);
//        String[] assessmentIds = new String[]{activityManagerId};
//        bodyJson.put("assessmentIds",assessmentIds);
//
//        // "{\n    \"columns\":[\n        \"_id\",\n        \"Name\",\n        \"ModifiedTime\",\n        \"ActivityManagerId\"\n    ],\n    \"assessmentIds\" : [\"2e0c22bc-7295-4993-961b-822053f70563\"]\n}"
//        // "https://openapi.italent.cn/PerformanceCloudOpen/api/v5/Assessment/GetAssessmentsByIds"
//
//        RequestBody body = RequestBody.create(mediaType,bodyJson.toJSONString());
//        Request request = new Request.Builder()
//                .url(Constants.beishenHost+Constants.assessmentUrl)
//                .method("POST", body)
//                .addHeader("Authorization", "Bearer "+token)
//                .addHeader("Content-Type", "application/json")
//                .build();
//        try {
//            Response response = client.newCall(request).execute();
//            int code = response.code();
//            log.error("code:{}",code);
//            if(code == 200){
//                bodyData = response.body().string();
//            }else{
//                String msg = response.body().string();
//                log.error("msg:"+msg);
//            }
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }
//        return bodyData;
//    }

    public JSONArray queryAssessment(String token,String activityManagerId){
        JSONArray assessmentArray = new JSONArray();
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        MediaType mediaType = MediaType.parse("application/json");
        JSONObject bodyJson = new JSONObject();
        String[] columns = new String[]{"_id","Name","ModifiedTime","ActivityManagerId"};
        bodyJson.put("columns",columns);
        String[] assessmentIds = new String[]{activityManagerId};
        bodyJson.put("assessmentIds",assessmentIds);

        log.error("bodyJson:{}",bodyJson.toJSONString());

        RequestBody body = RequestBody.create(mediaType, bodyJson.toJSONString());
        try {
            Request request = new Request.Builder()
                    .url(Constants.beishenHost+Constants.assessmentItemUrl)
                    .method("POST", body)
                    .addHeader("Authorization", "Bearer "+token)
                    .addHeader("Content-Type", "application/json")
                    .build();

            Response response = client.newCall(request).execute();

            int code = response.code();
            String msg = response.body().string();

            log.error("code:{}",code);
            log.error("msg:{}",msg);

            if(code == 200){
                if(StringUtils.isNotBlank(msg)){
                    JSONObject returnJson = JSONObject.parseObject(msg);
                    if(returnJson.containsKey("code")){
                        String dataCode = returnJson.getString("code");
                        if("200".equals(dataCode)){
                            JSONObject dataObject = returnJson.getJSONObject("data");
                            if(dataObject.containsKey("items")){
                                JSONArray itemsArray = dataObject.getJSONArray("items");
                                assessmentArray.addAll(itemsArray);
                            }
                        }
                    }
                }
            }else{
                log.error("msg:"+msg);
            }
        } catch (IOException e) {
            log.error("e:{}",e.getMessage());
            throw new RuntimeException(e);
        }
        return assessmentArray;
    }
}
