package com.weaver.seconddev.chapanda.dmp.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.dmp.constant.Constants;
import com.weaver.seconddev.chapanda.dmp.dao.FormFieldDao;
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.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


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

    @Autowired
    EbuilderOperateUtils ebuilderOperateUtils;

    @Autowired
    FormFieldDao formFieldDao;


    /**
     *
     * @return
     */
    public List<String> queryGmvList(String startDate,String endDate){

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

        List<Map<String,Object>> addList = new ArrayList<Map<String,Object>>();
        List<Map<String,Object>> updateList = new ArrayList<Map<String,Object>>();
        String formTable = "uf_zymdgmv";
        List<String> fieldList = new ArrayList<String>();
        fieldList.add("mdbm");
        fieldList.add("mdmc");
        fieldList.add("gmv");
        fieldList.add("sjsj");
        fieldList.add("hrmdid");
        try {
            Map<String, Object> deptMap = formFieldDao.queryDepartmentList();
            String msg = doHttpPost(startDate,endDate);
            log.error("msg:"+msg);
            if(StringUtils.isNotBlank(msg)){
                JSONObject msgJson = JSONObject.parseObject(msg);
                String dataCode = msgJson.getString("code");
                if("200".equals(dataCode)){
                    JSONArray dataArray = msgJson.getJSONArray("data");
                    for(int i = 0; i < dataArray.size(); i++){
                        JSONObject dataJson = dataArray.getJSONObject(i);
                        String mdbm = dataJson.getString("orgCode");
                        String mdmc = dataJson.getString("orgCodeName");
                        String gmv = dataJson.getString("gmv");
                        String sjsj = dataJson.getString("reportDate");
                        String hrmdid = "";
                        Map<String,Object> gmvMap = new HashMap<String,Object>();
                        gmvMap.put("mdbm",mdbm);
                        if(StringUtils.isNotBlank(mdbm)){
                            if(deptMap.containsKey(mdbm)){
                                hrmdid = String.valueOf(deptMap.get(mdbm));
                            }
                        }
                        gmvMap.put("hrmdid",hrmdid);
                        if(StringUtils.isNotBlank(gmv)){
                            if(!"null".equals(gmv) && gmv !=null){
                                gmvMap.put("gmv",gmv);
                            }else{
                                gmvMap.put("gmv","");
                            }
                        }else{
                            gmvMap.put("gmv","");
                        }
                        gmvMap.put("mdmc",mdmc);
                        gmvMap.put("sjsj",sjsj);

                        String dataId = formFieldDao.getGmvIdByCode(mdbm,formTable,"mdbm");
                        if(StringUtils.isNotBlank(dataId)){
                            gmvMap.put("id",dataId);
                            updateList.add(gmvMap);
                        }else{
                            addList.add(gmvMap);
                        }
                    }
                }
            }

            Map<String,Object> recordMap= formFieldDao.queryTableFormId(formTable);
            String formId = recordMap.get("id").toString();
            String appId = recordMap.get("app_id").toString();
            log.error("formId:{}",formId);
            log.error("appId:{}",appId);

            if(!addList.isEmpty()){

                List<EBDataReqDto> datas = new ArrayList<EBDataReqDto>();

                Map<String, Object> fieldMap = formFieldDao.queryFromTableField(formTable,fieldList);
                for(int i=0;i<addList.size();i++){
                    Map<String,Object> dataMap = addList.get(i);
                    EBDataReqDto ebDataReqDto = new EBDataReqDto();
                    List<EBDataReqDetailDto> mainData = new ArrayList<EBDataReqDetailDto>();
                    for(int n=0;n<fieldList.size();n++){
                        if(dataMap.containsKey(fieldList.get(n)) && fieldMap.containsKey(fieldList.get(n))){
                            String value = dataMap.get(fieldList.get(n)).toString();
                            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);
                    datas.add(ebDataReqDto);
                }

                EBDataChangeResult ebDataChangeResult = ebuilderOperateUtils.bacthInsertDbForm(datas,formId,appId);
                boolean isTrue = ebDataChangeResult.getStatus();
                if(isTrue){
                    ebList = ebDataChangeResult.getDataIds();
                }
            }

            if(!updateList.isEmpty()){

                List<EBDataReqDto> datas = new ArrayList<EBDataReqDto>();
                Map<String, Object> fieldMap = formFieldDao.queryFromTableField(formTable,fieldList);
                for(int i=0;i<addList.size();i++){
                    Map<String,Object> dataMap = addList.get(i);
                    EBDataReqDto ebDataReqDto = new EBDataReqDto();
                    List<EBDataReqDetailDto> mainData = new ArrayList<EBDataReqDetailDto>();
                    String id = dataMap.get("id").toString();
                    mainData.add(new EBDataReqDetailDto("id", id));
                    for(int n=0;n<fieldList.size();n++){
                        if(dataMap.containsKey(fieldList.get(n)) && fieldMap.containsKey(fieldList.get(n))){
                            String value = dataMap.get(fieldList.get(n)).toString();
                            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);
                    datas.add(ebDataReqDto);
                }

                EBDataChangeResult ebDataChangeResult = ebuilderOperateUtils.bacthEditEbForm(datas,formId,appId);
                boolean isTrue = ebDataChangeResult.getStatus();
                if(isTrue){
                    ebList = ebDataChangeResult.getDataIds();
                }
            }
        } catch (Exception e) {
            log.error("e:"+e);
            throw new RuntimeException(e);
        }
        return ebList;
    }


    public String doHttpPost(String startDate,String endDate) {
        String msg = "";
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();

        MediaType mediaType = MediaType.parse("application/json");

        JSONObject bodyJson = new JSONObject();
        bodyJson.put("startDate", startDate);
        bodyJson.put("endDate", endDate);
//        "{\n    \"startDate\": \"2025-07-01\",\n    \"endDate\": \"2025-07-03\"\n}"
        RequestBody body = RequestBody.create(mediaType, bodyJson.toJSONString());
        try {
            Request request = new Request.Builder()
                    .url(Constants.dmpHost + Constants.gmvUrl)
                    .method("POST", body)
                    .addHeader("Authorization", Constants.token)
                    .addHeader("Content-Type", "application/json")
                    .build();

            Response response = client.newCall(request).execute();
            int code = response.code();
            log.error("code:{}", code);
            msg = response.body().string();
            log.error("msg:" + msg);

        } catch (IOException e) {
            log.error("e:" + e);
            throw new RuntimeException(e);
        }
        return msg;
    }

}
