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

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.weaver.common.base.entity.result.WeaResult;
import com.weaver.esb.api.rpc.EsbServerlessRpcRemoteInterface;
import com.weaver.seconddev.chapanda.beisen.util.Performance2BeiSenUtil;
import com.weaver.seconddev.chapanda.beisen.util.Token2BeiSenUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service("Esb2BeisenPerformanceCronJob")
public class Esb2BeisenPerformanceCronJob implements EsbServerlessRpcRemoteInterface {
    private final static Logger log = LoggerFactory.getLogger(Esb2BeisenPerformanceCronJob.class);

    @Autowired
    Token2BeiSenUtil token2BeiSenUtil ;

    @Autowired
    Performance2BeiSenUtil performance2BeiSenUtil;
    @Override
    public WeaResult<Map<String, Object>> execute(Map<String, Object> params) {

        log.error("Esb2BeisenPerformanceCronJob start");

//        String tokenUrl = "https://openapi.italent.cn/token";
//        String beishenHost = "https://openapi.italent.cn";
//
//        String app_key = "0F0F2B3F6356464EB59FB651E8DAACBA";
//        String app_secret = "AF4A2BFC6BB741FD9D80B7F56DA07F08F703AC14B40C453E8DA5BCABAF43A003";

//        int page = 0;
//        int capacity = 2;
//        int year = 2024;
//        int period = 8;

        String page = String.valueOf(params.get("page")) ;
        String capacity = String.valueOf(params.get("capacity"));
        String year = String.valueOf(params.get("year"));
        String period = String.valueOf(params.get("period"));

//        String activityManagerUrl = "/PerformanceCloudOpen/api/v5/ActivityManager/GetOrgActivityManagers";
//        String assessmentItemUrl = "/PerformanceCloudOpen/api/v5/AssessmentItem/GetAssessmentItemCount";
//        String assessmentUrl = "/PerformanceCloudOpen/api/v5/Assessment/GetAssessmentsByIds";

        String token = token2BeiSenUtil.getToken();
        log.error("token:{}",token);
        JSONArray assessmentArray = new JSONArray();
        JSONArray activityManagerArray = new JSONArray();
        if(StringUtils.isNotBlank(token)){
            activityManagerArray = queryActivityManager(token,page,capacity,year,period);
            log.error("activityManagerArray:{}",activityManagerArray.toJSONString());
            queryAssessmentItem(activityManagerArray,token,page,capacity);
            assessmentArray = queryAssessment(activityManagerArray,token);
        }

        Map<String, Object> actionMap = new HashMap<String, Object>();
        actionMap.put("code",200);
        actionMap.put("msg","Esb2BeisenPerformanceCronJob");
        actionMap.put("assessmentArray",assessmentArray);
        actionMap.put("activityManagerArray",activityManagerArray);
        return WeaResult.success(actionMap);
    }


    public JSONArray queryActivityManager(String token,String page,String capacity,String year,String period){
        int activityTotal = 0;
        JSONArray activityManagerArray = new JSONArray();
        JSONArray performanceArray = new JSONArray();
        String bodyData = performance2BeiSenUtil.getActivityManagerCount(token,page,capacity,year,period);
        if(StringUtils.isNotBlank(bodyData)){
            JSONObject bodyJson = JSONObject.parseObject(bodyData);
            if(bodyJson.containsKey("code")){
                String code = bodyJson.getString("code");
                if("200".equals(code)){
                    JSONObject dataObject = bodyJson.getJSONObject("data");
                    if(dataObject.containsKey("paging")){
                        JSONObject pagingJson = dataObject.getJSONObject("paging");
                        activityTotal = pagingJson.getInteger("total");
                    }
                    if(dataObject.containsKey("items")){
                        performanceArray = dataObject.getJSONArray("items");
                    }
                }
            }

        }

        if(activityTotal <= Integer.valueOf(capacity)){
            activityManagerArray = performanceArray;
        }else{
            activityManagerArray.addAll(performanceArray);
            int pageCount = (int)Math.floor(activityTotal / Integer.valueOf(capacity));
            for(int i = 1; i < pageCount; i++){
                JSONArray itemArray = performance2BeiSenUtil.queryActivityManager(token,String.valueOf(i),capacity,year,period);
                activityManagerArray.addAll(itemArray);
            }
        }
        return activityManagerArray;
    }

    public void queryAssessmentItem(JSONArray activityManagerArray,String token,String page,String capacity){

        for(int i = 0; i < activityManagerArray.size(); i++){
            int itemTotal = 0;
            JSONArray itemsArray = new JSONArray();
            JSONArray assessmentItemArray = new JSONArray();
            String activityManagerId = activityManagerArray.getJSONObject(i).getString("id");
            log.error("activityManagerId:{}",activityManagerId);

            if(StringUtils.isNotBlank(activityManagerId)){
                String bodyData = performance2BeiSenUtil.getAssessmentItemCount(token,page,capacity,activityManagerId);
                log.error("bodyData:{}",bodyData);
                if(StringUtils.isNotBlank(bodyData)){
                    JSONObject bodyJson = JSONObject.parseObject(bodyData);
                    if(bodyJson.containsKey("code")){
                        String code = bodyJson.getString("code");
                        if("200".equals(code)){
                            JSONObject dataObject = bodyJson.getJSONObject("data");
                            if(dataObject.containsKey("paging")){
                                JSONObject pagingJson = dataObject.getJSONObject("paging");
                                itemTotal = pagingJson.getInteger("total");
                            }
                            if(dataObject.containsKey("items")){
                                itemsArray = dataObject.getJSONArray("items");
                            }
                        }
                    }
                }
            }
            log.error("itemTotal:{}",itemTotal);
            if(itemTotal <= Integer.valueOf(capacity)){
                assessmentItemArray = itemsArray;
            }else{
                assessmentItemArray.addAll(itemsArray);
                int pageCount = (int)Math.floor(itemTotal / Integer.valueOf(capacity));
                for(int k = 1; k < pageCount; k++){
                    log.error("K:{}",k);
                    JSONArray itemArray = performance2BeiSenUtil.queryAssessmentItem(token,String.valueOf(k),capacity,activityManagerId);
                    log.error("itemArray:{}",itemArray.size());
                    assessmentItemArray.addAll(itemArray);
                }
            }
            log.error("JSONArray:{}",JSONArray.toJSONString(assessmentItemArray));
        }
    }

    /***
     *
     * @param activityManagerArray
     * @param token
     */
    public JSONArray queryAssessment(JSONArray activityManagerArray,String token){
        JSONArray assessmentArray = new JSONArray();
        for(int i = 0; i < activityManagerArray.size(); i++) {
            String activityManagerId = activityManagerArray.getJSONObject(i).getString("id");
            log.error("activityManagerId:{}",activityManagerId);
            if (StringUtils.isNotBlank(activityManagerId)) {
                JSONArray itemsArray = performance2BeiSenUtil.queryAssessment(token,activityManagerId);
                assessmentArray.addAll(itemsArray);
            }
        }
        return assessmentArray;
    }
}
