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

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
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.seconddev.chapanda.sap.constant.Constants;
import com.weaver.seconddev.chapanda.sap.dao.Esb2SapUpdateIncorporatedDao;
import com.weaver.seconddev.chapanda.sap.dao.FormFieldDao;
import com.weaver.seconddev.chapanda.sap.entity.OkHttpDto;
import okhttp3.*;
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.Component;

import java.io.IOException;
import java.util.*;


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

    @Autowired
    FormFieldDao formFieldDao;

    @Autowired
    EbuilderOperateUtils ebuilderOperateUtils;

    @Autowired
    Esb2SapUpdateIncorporatedDao esb2SapUpdateIncorporatedDao;

    /**
     *
     * @return
     */
    public OkHttpDto queryIF311List(){
        OkHttpDto okHttpDto = doPostReqeustByOkHttp();
        return okHttpDto;
    }

    public OkHttpDto doPostReqeustByOkHttp(){
        String msg = "";
        OkHttpDto okHttpDto = new OkHttpDto();
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
//        JSONObject bodyJson = new JSONObject();
//        JSONObject dataJson = new JSONObject();
//        dataJson.put("DATA",BUMEN);
//        bodyJson.put("data",dataJson);

        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, "{}");
        String authorization = Base64.getUrlEncoder().encodeToString((Constants.Username + ":" + Constants.Password).getBytes());
        try {
            log.error(Constants.sapHost+Constants.queryIF311);
            Request request = new Request.Builder()
                    .url(Constants.sapHost+Constants.queryIF311)
                    .method("POST", body)
                    .addHeader("Content-Type", "application/json")
                    .addHeader("Authorization", "Basic "+authorization)
                    .build();
            Response response = client.newCall(request).execute();
            int code = response.code();
            log.error("code:{}",code);
            msg = response.body().string();
            log.error("msg:"+msg);

            okHttpDto.setResponseCode(code);
            okHttpDto.setResponseBody(msg);
            convertData(msg,okHttpDto);

        } catch (IOException e) {
            okHttpDto.setResponseCode(500);
            okHttpDto.setDataMsg("请求异常:"+e.getMessage());
            log.error("e:"+e);
        }
        return okHttpDto;
    }


    public void convertData(String reposponseBody, OkHttpDto okHttpDto){
        JSONArray bodyArray = new JSONArray();

        if(StringUtils.isNotBlank(reposponseBody)){
            JSONObject msgJson = JSONObject.parseObject(reposponseBody);
            if(msgJson.containsKey("RETURN")){
                String returnStr = msgJson.getString("RETURN");
                if(!"[]".equals(returnStr)){
                    JSONArray returnArray = msgJson.getJSONArray("RETURN");
                    for (int i = 0; i < returnArray.size(); i++) {
                        JSONObject dataJson = returnArray.getJSONObject(i);

                        String P_ID = dataJson.getString("P_ID");
                        String BUMEN = dataJson.getString("BUMEN");
                        String KOSTL = dataJson.getString("KOSTL");
                        String BUKRS = dataJson.getString("BUKRS");
                        String KOSTL_T = dataJson.getString("KOSTL_T");
                        String BUKRS_T = dataJson.getString("BUKRS_T");

                        log.error("KOSTL:{}",KOSTL);
                        log.error("BUKRS:{}",BUKRS);
                        log.error("BUMEN:{}",BUMEN);
                        log.error("BUKRS_T:{}",BUKRS_T);

                        JSONObject dataMap = new JSONObject();
                        dataMap.put("P_ID",P_ID);
                        dataMap.put("BUMEN",BUMEN);
                        dataMap.put("KOSTL",KOSTL);
                        dataMap.put("BUKRS",BUKRS);
                        dataMap.put("KOSTL_T",KOSTL_T);
                        dataMap.put("BUKRS_T",BUKRS_T);
                        bodyArray.add(dataMap);
                    }
                }
            }
        }

        log.error("bodyArray:{}",bodyArray.size());
        JSONObject responseDataJson = new JSONObject();
        responseDataJson.put("data",bodyArray);
        okHttpDto.setDataJson(responseDataJson);
    }


    /***
     * 批量更新法人代表
     * @param costCenterList
     */
    public void updateIncorporatedCompany(JSONArray costCenterList){
        log.error("costCenterList:{}",costCenterList.size());
        for(int i=0;i<costCenterList.size();i++){

            JSONObject dataMap = costCenterList.getJSONObject(i);

            String BUKRS_T = String.valueOf(dataMap.get("BUKRS_T"));
            String BUKRS = String.valueOf(dataMap.get("BUKRS"));
            log.error("BUKRS_T:{}",BUKRS_T);
            log.error("BUKRS:{}",BUKRS);
            esb2SapUpdateIncorporatedDao.updateIncorporatedCompany(BUKRS_T,BUKRS);
        }
    }

    /***
     * 批量新增/更新成本中心
     * @param costCenterList
     */
    public List<String> updateCostCenter(JSONArray costCenterList){
        List<String> ebList = new ArrayList<String>();

        List<String> fieldList = new ArrayList<String>();
        fieldList.add("bh");
        fieldList.add("mc");
        try {
            log.error("costCenterList:"+costCenterList.size());
            if(costCenterList.size()>0){
                JSONArray costCenterArray = convertData2CostCenter(costCenterList);
                Map<String, Object> fieldMap = formFieldDao.queryFromTableField(Constants.cosCenterTable,fieldList);
                List<EBDataReqDto> addDatas = new ArrayList<EBDataReqDto>();
                List<EBDataReqDto> updateDatas = new ArrayList<EBDataReqDto>();

                for(int i=0;i<costCenterArray.size();i++){
                    JSONObject dataMap = costCenterArray.getJSONObject(i);
                    EBDataReqDto ebDataReqDto = new EBDataReqDto();
                    List<EBDataReqDetailDto> mainData = new ArrayList<EBDataReqDetailDto>();

                    String KOSTL = String.valueOf(dataMap.getString("KOSTL"));
                    String ufId = esb2SapUpdateIncorporatedDao.queryCostCenterDataId(KOSTL);
                    log.error("ufId:{}",ufId);

                    if(StringUtils.isNotBlank(ufId)) {
                        log.error("修改");
                        mainData.add(new EBDataReqDetailDto("id", ufId));
                        for(int n=0;n<fieldList.size();n++) {
                            if (dataMap.containsKey(fieldList.get(n)) && fieldMap.containsKey(fieldList.get(n))) {
                                String value = dataMap.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{
                        for(int n=0;n<fieldList.size();n++){
                            if(dataMap.containsKey(fieldList.get(n)) && fieldMap.containsKey(fieldList.get(n))){
                                String value = dataMap.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);
                    }
                }
                log.error("addDatas:{}",addDatas.size());
                log.error("updateDatas:{}",updateDatas.size());

                if(addDatas.size() > 0){
                    EBDataChangeResult addEbDataChangeResult = ebuilderOperateUtils.bacthInsertEbForm(Constants.cosCenterTable,addDatas);
                    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(Constants.cosCenterTable,updateDatas);
                    boolean isTrue = updateEbDataChangeResult.getStatus();
                    log.error("isTrue2:{}",isTrue);
                    log.error("message2:{}",updateEbDataChangeResult.getMessage());
                    if(isTrue){
                        ebList.addAll(updateEbDataChangeResult.getDataIds());
                    }
                }
            }
        } catch (Exception e) {
            log.error("e:"+e);
        }
        return ebList;
    }


    /***
     * 批量更新部门成本中心
     * @param costCenterList
     * @return
     */
    public void updateDeptEmployeeCostCenter(JSONArray costCenterList){
        try {
            log.error("costCenterList:"+costCenterList.size());
            if(costCenterList.size()>0){
                for(int i=0;i<costCenterList.size();i++){
                    JSONObject dataMap = costCenterList.getJSONObject(i);
                    String BUMEN = String.valueOf(dataMap.getString("BUMEN"));  //oId
                    String KOSTL = String.valueOf(dataMap.getString("KOSTL"));
                    String BUKRS_T = String.valueOf(dataMap.getString("BUKRS_T"));

                    log.error("BUMEN:{}",BUMEN);
                    log.error("KOSTL:{}",KOSTL);
                    log.error("BUKRS_T:{}",BUKRS_T);

                    String deptFormDataId = "";
                    if(StringUtils.isNotBlank(BUMEN)){
                        deptFormDataId = esb2SapUpdateIncorporatedDao.queryHrmDepartmentCustomId(BUMEN);
                    }
                    String costCenterId = "";
                    if(StringUtils.isNotBlank(KOSTL)){
                        costCenterId = esb2SapUpdateIncorporatedDao.queryCostCenterDataId(KOSTL);
                    }
                    String companyId = "";
                    if(StringUtils.isNotBlank(BUKRS_T)){
                        companyId = esb2SapUpdateIncorporatedDao.queryHrmIncorporatedCompany(BUKRS_T);
                    }
                    log.error("deptFormDataId:{},costCenterId:{},companyId:{}",deptFormDataId,costCenterId,companyId);
                    if(StringUtils.isNotBlank(deptFormDataId)){
                        esb2SapUpdateIncorporatedDao.updateHrmDepartment(deptFormDataId,costCenterId,companyId);

                        esb2SapUpdateIncorporatedDao.updateHrmEmployee(deptFormDataId,costCenterId,companyId);
                    }
                }
            }
        } catch (Exception e) {
            log.error("e:"+e);
        }
    }


//    public void updateEmployeeCostCenter(List<Map<String,Object>> costCenterList){
//        try {
//            log.error("costCenterList:"+costCenterList.size());
//            if(costCenterList.size()>0){
//                for(int i=0;i<costCenterList.size();i++){
//                    Map<String,Object> dataMap = costCenterList.get(i);
//                    String BUMEN = String.valueOf(dataMap.get("BUMEN"));  //oId
//                    String KOSTL = String.valueOf(dataMap.get("KOSTL"));
//                    String BUKRS_T = String.valueOf(dataMap.get("BUKRS_T"));
//                    String deptFormDataId = "";
//                    if(StringUtils.isNotBlank(BUMEN)){
//                        deptFormDataId = esb2SapUpdateIncorporatedDao.queryHrmDepartmentCustomId(BUMEN);
//                    }
//                    String costCenterId = "";
//                    if(StringUtils.isNotBlank(KOSTL)){
//                        costCenterId = esb2SapUpdateIncorporatedDao.queryCostCenterDataId(KOSTL);
//                    }
//                    String companyId = "";
//                    if(StringUtils.isNotBlank(BUKRS_T)){
//                        companyId = esb2SapUpdateIncorporatedDao.queryHrmIncorporatedCompany(BUKRS_T);
//                    }
//                    log.error("deptFormDataId:{},costCenterId:{},companyId:{}",deptFormDataId,costCenterId,companyId);
//                    if(StringUtils.isNotBlank(deptFormDataId)){
//                        esb2SapUpdateIncorporatedDao.updateHrmEmployee(deptFormDataId,costCenterId,companyId);
//                    }
//                }
//            }
//        } catch (Exception e) {
//            log.error("e:"+e);
//        }
//    }


    public JSONArray convertData2CostCenter(JSONArray costCenterList){
        JSONArray dataArray = new JSONArray();

        for(int i=0;i<costCenterList.size();i++){
            JSONObject costCenterMap = costCenterList.getJSONObject(i);
            String KOSTL = String.valueOf(costCenterMap.getString("KOSTL"));
            String KOSTL_T = String.valueOf(costCenterMap.getString("KOSTL_T"));
            JSONObject dataJson = new JSONObject();
            dataJson.put("bh",KOSTL);
            dataJson.put("mc",KOSTL_T);
            dataArray.add(dataJson);
        }
        return dataArray;
    }


}
