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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.weaver.common.base.entity.result.WeaResult;
import com.weaver.ebuilder.form.client.entity.data.EBDataChangeResult;
import com.weaver.ebuilder.form.client.entity.data.EBDataReqDetailDto;
import com.weaver.ebuilder.form.client.entity.data.EBDataReqDto;
import com.weaver.esb.api.rpc.EsbServerlessRpcRemoteInterface;
import com.weaver.seconddev.chapanda.beisen.constant.Constants;
import com.weaver.seconddev.chapanda.beisen.dao.HrmFormFieldDao;
import com.weaver.seconddev.chapanda.beisen.dao.HrmDepartmentDao;
import com.weaver.seconddev.chapanda.beisen.dao.HrmPerformanceDao;
import com.weaver.seconddev.chapanda.beisen.util.EbuilderOperateUtils;
import com.weaver.seconddev.chapanda.beisen.util.Esb2BeiSenAssessmentUtil;
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.*;

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

    @Autowired
    Token2BeiSenUtil token2BeiSenUtil ;

    @Autowired
    Esb2BeiSenAssessmentUtil esb2BeiSenAssessmentUtil;

    @Autowired
    HrmFormFieldDao hrmFormFieldDao;

    @Autowired
    EbuilderOperateUtils ebuilderOperateUtils;

    @Autowired
    HrmDepartmentDao hrmDepartmentDao;

    @Autowired
    HrmPerformanceDao hrmPerformanceDao;

    @Override
    public WeaResult<Map<String, Object>> execute(Map<String, Object> params) {
        log.error("Esb2BeisenPerformanceCronJobNew start");
        int capacity = Integer.valueOf(String.valueOf(params.get("capacity")));
        String modifiedAfter = String.valueOf(params.get("modifiedAfter"));
        String modifiedBefore = String.valueOf(params.get("modifiedBefore"));

        int page = 1;
        if(params.containsKey("page")){
            page = Integer.valueOf(String.valueOf(params.get("page")));
        }

        List<String> ebList = new ArrayList<String>();

//        String activityManagerUrl = "/PerformanceCloudOpen/api/v5/ActivityManager/GetOrgActivityManagers";
//        String assessmentItemUrl = "/PerformanceCloudOpen/api/v5/AssessmentItem/GetAssessmentItemCount";
//        String assessmentUrl = "/PerformanceCloudOpen/api/v5/Assessment/GetAssessmentsByIds";
        List<String> fieldList = new ArrayList<String>();
        fieldList.add("khnf");
        fieldList.add("khzq");
        fieldList.add("gh");
        fieldList.add("mc");
        fieldList.add("yx");
        fieldList.add("bm");
        fieldList.add("jxxbmmc");
        fieldList.add("jxhdmc");
        fieldList.add("zzdf");
        fieldList.add("jxxs");
        fieldList.add("bkhr");
        fieldList.add("khzqlx");
        fieldList.add("ppdj");
        fieldList.add("jxhdid");

        fieldList.add("rzrq");
        fieldList.add("lzrq");
        fieldList.add("zzrq");
        fieldList.add("ryzt");
        fieldList.add("gs");
        fieldList.add("bm1");
        fieldList.add("bm2");
        fieldList.add("bm3");
        fieldList.add("bm4");
        fieldList.add("gzdd");
        
        String token = token2BeiSenUtil.getToken();
        log.error("token:{}",token);
        JSONArray assessmentArray = getAssessmentArray(token,page, capacity, modifiedAfter, modifiedBefore);
        log.error("assessmentArray:"+assessmentArray.size());
//        if(StringUtils.isNotBlank(token)){
//            int total = 0;
//            JSONArray itemArray = new JSONArray();
//            String bodyData = esb2BeiSenAssessmentUtil.getAssessmentsByFilters(token, page, capacity, modifiedAfter, modifiedBefore);
//            if(StringUtils.isNotBlank(bodyData)){
//                JSONObject bodyJson = JSONObject.parseObject(bodyData);
//                if(bodyJson.containsKey("code")){
//                    JSONObject dataObject = bodyJson.getJSONObject("data");
//                    if(dataObject.containsKey("paging")){
//                        JSONObject pagingJson = dataObject.getJSONObject("paging");
//                        total = pagingJson.getInteger("total");
//                    }
//                    if(dataObject.containsKey("items")){
//                        itemArray = dataObject.getJSONArray("items");
//                    }
//                }
//            }
//
//            log.error("itemArray:"+itemArray.size());
//
//            if(total <= capacity){
//                assessmentArray.addAll(itemArray) ;
//            }else{
//                assessmentArray.addAll(itemArray);
//                int pageCount = (int)Math.floor(total/(capacity*1.0));
//                log.error("pageCount:"+pageCount);
//                for(int i = 1; i < pageCount; i++){
//                    int page2 = i+1;
//                    JSONArray itemArray2 = esb2BeiSenAssessmentUtil.queryAssessmentsByPage(token,page2,capacity,modifiedAfter, modifiedBefore);
//                    assessmentArray.add(itemArray2);
//                }
//            }
//        }

        int effectiveTotal = 0;
        int failTotal = 0;

        if(assessmentArray.size() > 0){
            JSONArray dataArray = convertAssessmentList(assessmentArray);
            log.error("dataArray:"+dataArray.size());

            Map<String, Object> fieldMap = hrmFormFieldDao.queryFromTableField(Constants.assessmentFormTable,fieldList);

            List<EBDataReqDto> addDatas = new ArrayList<EBDataReqDto>();
            List<EBDataReqDto> updateDatas = new ArrayList<EBDataReqDto>();
            for(int i=0;i<dataArray.size();i++){
                JSONObject dataJson = dataArray.getJSONObject(i);
                log.error("dataJson2:{}",dataJson.toJSONString());
                if(dataJson.containsKey("bkhr") && StringUtils.isNotBlank(dataJson.getString("bkhr"))){
                    String khnf = dataJson.getString("khnf");
                    String khzq = dataJson.getString("khzq");
                    String bkhr = dataJson.getString("bkhr");
                    String jxhdid = dataJson.getString("jxhdid");
                    String ufId = hrmPerformanceDao.getAssessmentData(khnf,khzq,jxhdid,bkhr);
                    log.error("ufId:{}",ufId);

                    String zzdf = dataJson.getString("zzdf");
                    log.error("zzdf:{}",zzdf);

                    if(StringUtils.isNotBlank(ufId)){
                        log.error("修改");
                        EBDataReqDto ebDataReqDto = new EBDataReqDto();
                        List<EBDataReqDetailDto> mainData = new ArrayList<EBDataReqDetailDto>();
                        mainData.add(new EBDataReqDetailDto("id", ufId));
                        for(int n=0;n<fieldList.size();n++){
                            if(dataJson.containsKey(fieldList.get(n)) && fieldMap.containsKey(fieldList.get(n))){
                                String value = dataJson.getString(fieldList.get(n));
                                String fieldId = fieldMap.get(fieldList.get(n)).toString();
                                log.error("fieldId:{}",fieldId);
                                log.error("value:{}",value);
                                mainData.add(new EBDataReqDetailDto(fieldId, value));
                                effectiveTotal++;
                            }
                        }
                        ebDataReqDto.setMainDatas(mainData);
                        updateDatas.add(ebDataReqDto);
                    }else{
                        log.error("新增");
                        EBDataReqDto ebDataReqDto = new EBDataReqDto();
                        List<EBDataReqDetailDto> mainData = new ArrayList<EBDataReqDetailDto>();
                        for(int n=0;n<fieldList.size();n++){
                            if(dataJson.containsKey(fieldList.get(n)) && fieldMap.containsKey(fieldList.get(n))){
                                String value = dataJson.getString(fieldList.get(n));
                                String fieldId = fieldMap.get(fieldList.get(n)).toString();

                                log.error("fieldId:{}",fieldId);
                                log.error("value:{}",value);
                                mainData.add(new EBDataReqDetailDto(fieldId, value));
                                effectiveTotal++;
                            }
                        }
                        ebDataReqDto.setMainDatas(mainData);
                        addDatas.add(ebDataReqDto);
                    }
                }else{
                    failTotal++;
                }
            }
            log.error("addDatas:{}",addDatas.size());
            log.error("updateDatas:{}",updateDatas.size());

            Map<String,Object> recordMap = hrmFormFieldDao.queryTableFormId(Constants.assessmentFormTable);
            String formId = recordMap.get("id").toString();
            String appId = recordMap.get("app_id").toString();
            log.error("formId:{}",formId);
            log.error("appId:{}",appId);
            if(StringUtils.isNotBlank(formId) && StringUtils.isNotBlank(appId)){
                if(addDatas.size() > 0){
                    EBDataChangeResult addEbDataChangeResult = ebuilderOperateUtils.bacthInsertDbForm(addDatas,formId,appId);
                    boolean isTrue = addEbDataChangeResult.getStatus();
                    log.error("message:{}",addEbDataChangeResult.getMessage());
                    log.error("isTrue1:{}",isTrue);
                    if(isTrue){
                        ebList.addAll(addEbDataChangeResult.getDataIds());
                    }
                }

                if(updateDatas.size() > 0){

                    EBDataChangeResult updateEbDataChangeResult = ebuilderOperateUtils.bacthEditEbForm(updateDatas,formId,appId);
                    boolean isTrue = updateEbDataChangeResult.getStatus();
                    log.error("isTrue2:{}",isTrue);
                    log.error("message2:{}",updateEbDataChangeResult.getMessage());
                    if(isTrue){
                        ebList.addAll(updateEbDataChangeResult.getDataIds());
                    }
                }
            }
        }

        for(String ebId:ebList){

            String rylb = "";
            String bm1 = "";
            if("2".equals(rylb)){

            }else if("".equals(bm1)){

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


        Map<String, Object> actionMap = new HashMap<String, Object>();
        actionMap.put("code",200);
        actionMap.put("msg","同步成功");
        actionMap.put("total",assessmentArray.size());
        actionMap.put("effectiveTotal",effectiveTotal);
        actionMap.put("failTotal",failTotal);
        actionMap.put("ebTotal",ebList.size());
        return WeaResult.success(actionMap);
    }

    /***
     *
     * @param token
     * @param page
     * @param capacity
     * @param modifiedAfter
     * @param modifiedBefore
     * @return
     */
    public JSONArray getAssessmentArray(String token,int page, int capacity, String modifiedAfter, String modifiedBefore) {
        JSONArray assessmentArray = new JSONArray();
        if (StringUtils.isNotBlank(token)) {
            int total = 0;
            JSONArray itemArray = new JSONArray();
            String bodyData = esb2BeiSenAssessmentUtil.getAssessmentsByFilters(token, page, capacity, modifiedAfter, modifiedBefore);
            if (StringUtils.isNotBlank(bodyData)) {
                JSONObject bodyJson = JSONObject.parseObject(bodyData);
                if (bodyJson.containsKey("code")) {
                    JSONObject dataObject = bodyJson.getJSONObject("data");
                    if (dataObject.containsKey("paging")) {
                        JSONObject pagingJson = dataObject.getJSONObject("paging");
                        total = pagingJson.getInteger("total");
                    }
                    if (dataObject.containsKey("items")) {
                        itemArray = dataObject.getJSONArray("items");
                    }
                }
            }

            log.error("itemArray:" + itemArray.size());

            if (total <= capacity) {
                assessmentArray.addAll(itemArray);
            } else {
                assessmentArray.addAll(itemArray);
                int pageCount = (int) Math.floor(total / (capacity * 1.0));
                log.error("pageCount:" + pageCount);
                for (int i = 1; i < pageCount; i++) {
                    int page2 = i + 1;
                    JSONArray itemArray2 = esb2BeiSenAssessmentUtil.queryAssessmentsByPage(token, page2, capacity, modifiedAfter, modifiedBefore);
                    assessmentArray.addAll(itemArray2);
                }
            }
        }
        return assessmentArray;
    }

    /***
     *
     * @param assessmentArray
     * @return
     */
    public JSONArray convertAssessmentList(JSONArray assessmentArray) {

        JSONArray dataArray = new JSONArray();
        Map<String,Object> departmentMap = hrmDepartmentDao.queryDepartmentData();
        Map<String,Object> employeeMap = hrmDepartmentDao.queryEmployeeData();
        log.error("departmentMap:"+departmentMap.size());
        log.error("employeeMap:"+employeeMap.size());


        for(int i=0;i<assessmentArray.size();i++) {
            JSONObject assessmentJson = assessmentArray.getJSONObject(i);
            String id = assessmentJson.getString("id");
            JSONArray fieldDatas = assessmentJson.getJSONArray("fieldDatas");

            JSONObject dataJson = new JSONObject();
            dataJson.put("bsjxid",id);



            for(int n=0;n<fieldDatas.size();n++){
                JSONObject fieldDataJson = fieldDatas.getJSONObject(n);
                log.error("fieldDataJson:{}",fieldDataJson.toJSONString());

                String name = fieldDataJson.getString("name");
                String value = fieldDataJson.getString("value");
                String text = fieldDataJson.getString("text");

                if("ActivityManagerId".equals(name)){
                    dataJson.put("jxhdmc",text);
                    dataJson.put("jxhdid",value);
                }

//                    if("Employee".equals(name)){
//                        dataJson.put("jxhdmc",value);
//                    }
//                    if("DeptId".equals(name)){
//                        dataJson.put("jxhdmc",value);
//                    }

                if("Year".equals(name)){
                    dataJson.put("khnf",value);
                }
                if("Period".equals(name)){
                    dataJson.put("khzq",value);

                    if("-1".equals(value)){
                        dataJson.put("khzqlx","4"); //年度考核
                    }else if("1".equals(value) || "2".equals(value)
                            || "3".equals(value)
                            || "4".equals(value)
                            || "5".equals(value)
                            || "6".equals(value)
                            || "7".equals(value)
                            || "8".equals(value)
                            || "9".equals(value)
                            || "10".equals(value)
                            || "11".equals(value)
                            || "12".equals(value)
                    ){
                        dataJson.put("khzqlx","1"); //月度考核
                    }else if("31".equals(value) || "22".equals(value)
                    ){
                        dataJson.put("khzqlx","3"); //半年度考核
                    }else if("21".equals(value) || "22".equals(value)  || "23".equals(value) || "24".equals(value)
                    ){
                        dataJson.put("khzqlx","2"); //季度考核
                    }
                }

                if("Name".equals(name)){
                    dataJson.put("mc",value);
                }

                if("Email".equals(name)){
                    dataJson.put("yx",value);
                }

                if("StaffCode".equals(name)){
                    dataJson.put("gh",value);
                    log.error("gh:{}",value);
                    if(StringUtils.isNotBlank(value)){
                        if(employeeMap.containsKey(value)){
                            String employeeid = String.valueOf(employeeMap.get(value));
                            log.error("employeeid:{}",employeeid);
                            dataJson.put("bkhr",employeeid);
                            if(StringUtils.isNotBlank(employeeid)){
                                Map<String,Object> otherMap = hrmPerformanceDao.queryEmployeeAssessmentOtherInfo(employeeid);
                                Iterator<Map.Entry<String, Object>> iterator = otherMap.entrySet().iterator();
                                while (iterator.hasNext()) {
                                    Map.Entry<String, Object> entry = iterator.next();
                                    String emKey = entry.getKey();
                                    String emValue = entry.getValue().toString();
                                    log.error("emKey:{}",emKey);
                                    log.error("emValue:{}",emValue);
                                    dataJson.put(emKey,emValue);
                                }
                            }
                        }
                    }
                }

                if("StaffDep".equals(name)){
                    dataJson.put("jxxbmmc",text);
                    if(StringUtils.isNotBlank(value)){
                        if(departmentMap.containsKey(value)){
                            String departmentid = String.valueOf(departmentMap.get(value));
                            dataJson.put("bm",departmentid);
                        }
                    }
                }

                if("FinalScore".equals(name)){
                    dataJson.put("zzdf",value);
                }

                if("TotalScoreRuleIdLookup".equals(name)){
                    dataJson.put("ppdj",text);
                }

            }
            dataArray.add(dataJson);
            log.error("dataJson:{}",dataJson.toJSONString());
        }
        return dataArray;
    }

}
