package com.weaver.seconddev.chapanda.qunjie.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.qunjie.dao.SealsManageDao;
import com.weaver.seconddev.chapanda.qunjie.constant.Constants;
import com.weaver.seconddev.chapanda.qunjie.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 Esb2QunjieQuerySealUtil {
    private final static Logger log = LoggerFactory.getLogger(Esb2QunjieQuerySealUtil.class);

    @Autowired
    FormFieldDao formFieldDao;

    @Autowired
    EbuilderOperateUtils ebuilderOperateUtils;

    @Autowired
    SealsManageDao sealsManageDao;

    /**
     *
     * @param token
     * @return
     */
    public List<String> querySealBaseList(String token){
        List<String> ebList = new ArrayList<String>();

        List<Map<String,Object>> sealList = new ArrayList<Map<String,Object>>();

        List<String> fieldList = new ArrayList<String>();
        fieldList.add("sealid");
        fieldList.add("orgNo");
        fieldList.add("sealName");
        fieldList.add("sealStatus");
        fieldList.add("sealType");
        fieldList.add("sealNo");
        fieldList.add("yzzl");
        try {
            String msg = doPostReqeustByOkHttp(token);
            log.error("msg:"+msg);
           if(StringUtils.isNotBlank(msg)){
                JSONObject msgJson = JSONObject.parseObject(msg);
                if(msgJson.containsKey("status")){
                    String status = msgJson.getString("status");
                    if("0".equals(status)){
                        JSONArray dataArray = msgJson.getJSONArray("data");
                        for (int i = 0; i < dataArray.size(); i++) {
                            JSONObject dataJson = dataArray.getJSONObject(i);

                            String id = dataJson.getString("id");
                            String sealName = dataJson.getString("sealName");
                            String sealStatus = dataJson.getString("sealStatus");
                            String sealShape = dataJson.getString("sealShape");
                            String sealMaterial = dataJson.getString("sealMaterial");
                            String sealType = dataJson.getString("sealType");
                            String createDate = dataJson.getString("createDate");
                            String picId = dataJson.getString("picId");
                            String sealCategory = dataJson.getString("sealCategory");
                            String sealCategoryNew = dataJson.getString("sealCategoryNew");
                            String adminId = dataJson.getString("adminId");
                            String addressStatus = dataJson.getString("addressStatus");
                            String imgHeader = dataJson.getString("imgHeader");
                            String sealNo = dataJson.getString("sealNo");
                            String sealSurroundWord = dataJson.getString("sealSurroundWord");


                            String orgNo = dataJson.getString("orgNo");

                            JSONObject deviceJson = dataJson.getJSONObject("device");
                            String blueNo = deviceJson.getString("blueNo");
                            String deviceTypeValue = deviceJson.getString("deviceTypeValue");
                            String isWarning = deviceJson.getString("isWarning");
                            String isBind = deviceJson.getString("isBind");
                            String warningTime = deviceJson.getString("warningTime");

                            Map<String,Object> sealMap = new HashMap<String,Object>();
                            sealMap.put("sealid",id);
                            sealMap.put("sealName",sealName);
                            sealMap.put("sealStatus",sealStatus);
                            sealMap.put("sealShape",sealShape);
                            sealMap.put("sealMaterial",sealMaterial);
                            sealMap.put("sealType",sealType);
                            sealMap.put("createDate",createDate);
                            sealMap.put("picId",picId);
                            sealMap.put("sealCategory",sealCategory);
                            sealMap.put("sealCategoryNew",sealCategoryNew);
                            sealMap.put("adminId",adminId);
                            sealMap.put("addressStatus",addressStatus);
                            sealMap.put("imgHeader",imgHeader);
                            sealMap.put("sealNo",sealNo);
                            sealMap.put("sealSurroundWord",sealSurroundWord);
                            sealMap.put("orgNo",orgNo);
                            sealMap.put("blueNo",blueNo);
                            sealMap.put("deviceTypeValue",deviceTypeValue);
                            sealMap.put("isWarning",isWarning);
                            sealMap.put("isBind",isBind);
                            sealMap.put("warningTime",warningTime);
                            sealList.add(sealMap);
                        }
                    }
                }
           }

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

           if(sealList.size()>0){
               Map<String, Object> fieldMap = formFieldDao.queryFromTableField(Constants.sealTable,fieldList);

               List<EBDataReqDto> addDatas = new ArrayList<EBDataReqDto>();
               List<EBDataReqDto> updateDatas = new ArrayList<EBDataReqDto>();

               for(int i=0;i<sealList.size();i++){
                   Map<String,Object> dataMap = sealList.get(i);
                   EBDataReqDto ebDataReqDto = new EBDataReqDto();
                   List<EBDataReqDetailDto> mainData = new ArrayList<EBDataReqDetailDto>();

                   String sealid = String.valueOf(dataMap.get("sealid"));
                   String ufId = sealsManageDao.querySealsDataBySealId(sealid);

                   if(StringUtils.isNotBlank(ufId)) {
                       log.error("修改");
                       mainData.add(new EBDataReqDetailDto("id", ufId));
                       for(int n=0;n<fieldList.size();n++){
                           if(fieldList.get(n).equals("yzzl")){
                               String fieldId = fieldMap.get(fieldList.get(n)).toString();
                               mainData.add(new EBDataReqDetailDto(fieldId, "2"));
                           }else{
                               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);
                       updateDatas.add(ebDataReqDto);

                   }else{
                       for(int n=0;n<fieldList.size();n++){
                           if(fieldList.get(n).equals("yzzl")){
                               String fieldId = fieldMap.get(fieldList.get(n)).toString();
                               mainData.add(new EBDataReqDetailDto(fieldId, "2"));
                           }else{
                               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);
                       addDatas.add(ebDataReqDto);
                   }
               }
               log.error("addDatas:{}",addDatas.size());
               log.error("updateDatas:{}",updateDatas.size());

               if(addDatas.size() > 0){
                   EBDataChangeResult addEbDataChangeResult = ebuilderOperateUtils.bacthInsertEbForm(Constants.sealTable,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.sealTable,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;
    }


    public String doPostReqeustByOkHttp(String token){
        String msg = "";

        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();

        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, "{}");

        try {
            Request request = new Request.Builder()
                    .url(Constants.qunjieHost+Constants.querySealUrl)
                    .method("POST", body)
                    .addHeader("Authorization", "Bearer "+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;
    }




}
