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.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.HrmBeisenPositionDao;
import com.weaver.seconddev.chapanda.beisen.util.EbuilderOperateUtils;
import com.weaver.seconddev.chapanda.beisen.util.Esb2BeiSenPositionUtil;
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("Esb2BeisenPositionFullCronJob")
public class Esb2BeisenPositionFullCronJob implements EsbServerlessRpcRemoteInterface {
    private final static Logger log = LoggerFactory.getLogger(Esb2BeisenPositionFullCronJob.class);

    @Autowired
    Esb2BeiSenPositionUtil esb2BeiSenPositionUtil;

    @Autowired
    HrmFormFieldDao hrmFormFieldDao;

    @Autowired
    HrmBeisenPositionDao hrmBeisenPositionDao;

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

        log.error("Esb2BeisenPositionFullCronJob");
        List<String> ebList = new ArrayList<String>();

        JSONArray positionArray = new JSONArray();

        String startDate = String.valueOf(params.get("startDate"));
        String endDate = String.valueOf(params.get("endDate"));
        int capacity = 100;
        int total = 0;
        String scrollId = "";
        JSONArray firstArray = new JSONArray();
        String msg = esb2BeiSenPositionUtil.queryPositionByDate(startDate, endDate,capacity);
        if(StringUtils.isNotBlank(msg)){
            JSONObject msgJson = JSONObject.parseObject(msg);
            if(msgJson.containsKey("total")){
                total = msgJson.getInteger("total");
            }
            if(msgJson.containsKey("data")){
                firstArray = msgJson.getJSONArray("data");
            }

            if(msgJson.containsKey("scrollId")){
                scrollId = msgJson.getString("scrollId");
            }
        }

        log.error("total:{}",total);
        log.error("firstArray:{}",firstArray.size());
        log.error("scrollId:{}",scrollId);

        if(total <= capacity){
            positionArray = firstArray;
        }else{
            if(firstArray.size() > 0){
                positionArray.addAll(firstArray);
            }
            int pageCount = (int)Math.floor(total / capacity*1.0);
            log.error("pageCount:{}",pageCount);
            int count = 0;
            while(StringUtils.isNotBlank(scrollId) && !"null".equals(scrollId)){
                String positionData = esb2BeiSenPositionUtil.queryPositionByscrollId(startDate, endDate,scrollId,capacity);
                if(StringUtils.isNotBlank(positionData)){
                    JSONObject msgJson = JSONObject.parseObject(positionData);

                    if(msgJson.containsKey("data")){
                        JSONArray itemArray = msgJson.getJSONArray("data");
                        log.error("itemArray:{}",itemArray.size());
                        if(itemArray.size() > 0){
                            positionArray.addAll(itemArray);
                        }else{
                            scrollId = "";
                        }
                    }

                    if(msgJson.containsKey("scrollId")){
                        scrollId = msgJson.getString("scrollId");
                    }else{
                        scrollId = "";
                    }
                }else{
                    scrollId = "";
                }

                log.error("scrollId:{}",scrollId);
                log.error("count:{}",count);

                count++;
                if(count > (pageCount+5)){
                    break;
                }
            }
        }
        log.error("positionArray:{}",positionArray.size());

        List<String> fieldList = new ArrayList<String>();
        fieldList.add("bs_gwid");
        fieldList.add("bs_gwmc");
        fieldList.add("bs_gwbm");

        if(positionArray.size() > 0){
            updateHrmPosition(positionArray);
            doSavePositionData(positionArray);
        }


        Map<String, Object> actionMap = new HashMap<String, Object>();
        actionMap.put("code",200);
        actionMap.put("msg","同步成功");
        return WeaResult.success(actionMap);
    }


    public JSONArray convertPositionList(JSONArray positionArray){
        JSONArray dataArray = new JSONArray();

        for(int i=0;i<positionArray.size();i++) {
            JSONObject positionJson = positionArray.getJSONObject(i);
            String name = positionJson.getString("name");
            String code = positionJson.getString("code");
            String objectId = positionJson.getString("objectId");

            log.error("name:{}",name);
            log.error("objectId:{}",objectId);

            if(StringUtils.isNotBlank(code) && StringUtils.isNotBlank(objectId)){
                JSONObject dataJson = new JSONObject();
                dataJson.put("bs_gwid",objectId);
                dataJson.put("bs_gwmc",name);
                dataJson.put("bs_gwbm",code);
                dataArray.add(dataJson);
            }
        }
        return dataArray;
    }

    public List<String> doSavePositionData(JSONArray positionArray){
        List<String> ebList = new ArrayList<String>();

        List<String> fieldList = new ArrayList<String>();
        fieldList.add("bs_gwid");
        fieldList.add("bs_gwmc");
        fieldList.add("bs_gwbm");

        if(positionArray.size() > 0){
            JSONArray dataArray = convertPositionList(positionArray);
            log.error("dataArray:"+dataArray.size());
            Map<String, Object> fieldMap = hrmFormFieldDao.queryFromTableField(Constants.beisenPostionTable,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("bs_gwid") && StringUtils.isNotBlank(dataJson.getString("bs_gwid"))){
                    String bs_gwid = dataJson.getString("bs_gwid");
                    String bs_gwmc = dataJson.getString("bs_gwmc");
                    String bs_gwbm = dataJson.getString("bs_gwbm");
                    String ufId = hrmBeisenPositionDao.getPositionIdByGwId(bs_gwid);
                    log.error("ufId:{}",ufId);

                    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));
                            }
                        }
                        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));
                            }
                        }
                        ebDataReqDto.setMainDatas(mainData);
                        addDatas.add(ebDataReqDto);
                    }
                }else{
                }
            }
            log.error("addDatas:{}",addDatas.size());
            log.error("updateDatas:{}",updateDatas.size());

            Map<String,Object> recordMap = hrmFormFieldDao.queryTableFormId(Constants.beisenPostionTable);
            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());
                    }
                }
            }
        }
        return ebList;
    }


    public Map<String,String> updateHrmPosition(JSONArray positionArray){
        Map<String,String> resultMap = new HashMap<String,String>();
        int failCount = 0;
        int successCount = 0;
        int total = positionArray.size() ;
        if(positionArray.size() > 0){
            for(int i=0;i<positionArray.size();i++){
                JSONObject dataJson = positionArray.getJSONObject(i);
                log.error("dataJson2:{}",dataJson.toJSONString());
                if(dataJson.containsKey("objectId") && StringUtils.isNotBlank(dataJson.getString("objectId"))){
                    String objectId = dataJson.getString("objectId");
                    String code = dataJson.getString("code");
                    String oIdOrganization = dataJson.getString("oIdOrganization");
                    Map<String, Object> result = hrmBeisenPositionDao.updateHrmPositionByBensen(code,objectId,oIdOrganization);
                    if (result.containsKey("code")) {
                        code = String.valueOf(result.get("code"));
                        log.error("code:" + code);
                        if ("200".equals(code)) {
                            successCount++;
                        }else{
                            failCount++;
                        }
                    }
                }
            }
        }

        resultMap.put("failCount",String.valueOf(failCount));
        resultMap.put("successCount",String.valueOf(successCount));
        resultMap.put("total",String.valueOf(total));
        return resultMap;
    }

}
