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


/***
 * 同步印章数据
 */
@Service("Esb2EsignSyncSealsCron")
public class Esb2EsignSyncSealsCron implements EsbServerlessRpcRemoteInterface {
    private final static Logger log = LoggerFactory.getLogger(Esb2EsignSyncSealsCron.class);

    @Autowired
    SealsManageDao sealsManageDao;

    @Autowired
    Esb2EsignSyncSealsUtil esb2EsignSyncSealsUtil;

    @Autowired
    FormFieldDao formFieldDao;

    @Autowired
    EbuilderOperateUtils ebuilderOperateUtils;

    @Override
    public WeaResult<Map<String, Object>> execute(Map<String, Object> params) {

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

        JSONArray sealsArray = new JSONArray();
        List<Map<String,Object>> organizeList =  sealsManageDao.queryLegalEntityList();
        log.error("organizeList:{}",organizeList.size());
        for(int i=0;i<organizeList.size();i++){
            String organizeNo = organizeList.get(i).get("bh").toString();
            log.error("organizeNo:{}",organizeNo);
            JSONArray itemArray = querySealData(organizeNo);
            log.error("itemArray:{}",itemArray.size());
            sealsArray.addAll(itemArray);
        }


        int effectiveTotal = 0;
        int failTotal = 0;

        List<String> fieldList = new ArrayList<String>();
        fieldList.add("yzzl");
        fieldList.add("sealid");
        fieldList.add("orgno");
        fieldList.add("sealname");
        fieldList.add("sealstatus");
        fieldList.add("sealtype");
        fieldList.add("sealno");

        log.error("sealsArray:{}",sealsArray.size());
        log.error("sealsArray:{}",sealsArray.toJSONString());
        try{
            if(sealsArray.size() > 0){

                Map<String, Object> fieldMap = formFieldDao.queryFromTableField(Constants.sealTable,fieldList);

                List<EBDataReqDto> addDatas = new ArrayList<EBDataReqDto>();
                List<EBDataReqDto> updateDatas = new ArrayList<EBDataReqDto>();
                log.error("fieldMap2:{}",fieldMap.size());
                for(int i=0;i<sealsArray.size();i++){
                    log.error("i:{}",i);
                    JSONObject dataJson = sealsArray.getJSONObject(i);
                    log.error("dataJson2:{}",dataJson.toJSONString());
                    if(dataJson.containsKey("sealid") && StringUtils.isNotBlank(dataJson.getString("sealid"))){
                        String sealid = dataJson.getString("sealid");
                        String ufId = sealsManageDao.querySealsDataBySealId(sealid);
                        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));
                                    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 = formFieldDao.queryTableFormId(Constants.sealTable);
                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.bacthInsertEbForm(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());
                        }

                    }
                }
            }
        }catch (Exception e){
            log.error("e:{}",e);
        }

        Map<String, Object> actionMap = new HashMap<String, Object>();
        actionMap.put("code",200);
        actionMap.put("total",sealsArray.size());
        actionMap.put("effectiveTotal",effectiveTotal);
        actionMap.put("failTotal",failTotal);
        actionMap.put("ebTotal",ebList.size());

        return WeaResult.success(actionMap);
    }


    /***
     * 获取印章数据
     * @param organizeNo
     * @return
     */
    public JSONArray querySealData(String organizeNo){

        JSONArray sealsArray = new JSONArray();

        int pageSize = 30;
        int total = 0;
        JSONArray itemArray = new JSONArray();
        if(StringUtils.isNotBlank(organizeNo)){
            int pageIndex = 1;
            String querySealsUrl = Constants.querySealsUrl+"?pageIndex="+pageIndex+"&pageSize="+pageSize+"&organizeNo="+organizeNo;
            log.error("querySealsUrl:{}",querySealsUrl);
            String msg = esb2EsignSyncSealsUtil.queryEsignSealTemplate(querySealsUrl);
            if(StringUtils.isNotBlank(msg)){
                JSONObject msgJson = JSONObject.parseObject(msg);
                if(msgJson.containsKey("errCode")){
                    String errCode = msgJson.getString("errCode");
                    if("0".equals(errCode)){
                        if(msgJson.containsKey("data")){
                            JSONObject dataJson = msgJson.getJSONObject("data");
                            if(dataJson.containsKey("total")){
                                total = dataJson.getInteger("total");
                            }
                        }
                    }
                }
                itemArray = esb2EsignSyncSealsUtil.querySealsArray(msg,organizeNo);
            }
        }

        if (total <= pageSize) {
            sealsArray = itemArray;
        } else {
            sealsArray.addAll(itemArray);
            int pageCount = (int) Math.floor(total / (pageSize * 1.0));
            log.error("pageCount:" + pageCount);
            for (int i = 1; i < pageCount; i++) {
                int pageIndex = i + 1;

                String querySealsUrl = Constants.querySealsUrl+"?pageIndex="+pageIndex+"&pageSize="+pageSize+"&organizeNo="+organizeNo;
                log.error("querySealsUrl:{}",querySealsUrl);
                String msg = esb2EsignSyncSealsUtil.queryEsignSealTemplate(querySealsUrl);
                JSONArray itemArray2 = esb2EsignSyncSealsUtil.querySealsArray(msg,organizeNo);
                sealsArray.addAll(itemArray2);
            }
        }
        return sealsArray;
    }

//    public String queryEsignSealTemplate(String querySealsUrl,String organizeNo){
//
////        String secretKey = "7f067a08f5c675137e6e72aa298e2c07";
////        String xTimevaleProjectId = "1001003";
////        String eSignHost = "http://110.185.172.132:8086";
//
//        String bodyData = "";
//        String xTimevaleSignature = esb2EsignUtil.encryptionHmacSHA256(bodyData);
//        log.error("xTimevaleSignature:"+xTimevaleSignature);
//        String msg = esb2EsignUtil.doGetEsignQuerySeals(xTimevaleSignature,querySealsUrl);
//        log.error("msg:"+msg);
//        return msg;
//    }


//    public String doHttpPost(String eSignHost,String eSignUrl,String bodyData,String xTimevaleSignature,String xTimevaleProjectId){
//        String msg = "";
//        OkHttpClient client = new OkHttpClient().newBuilder()
//                .build();
//        MediaType mediaType = MediaType.parse("text/plain");
//        System.out.println(eSignHost+eSignUrl);
//        try {
//            Request request = new Request.Builder()
//                    .url(eSignHost+eSignUrl)
//                    .method("GET", null)
//                    .addHeader("x-timevale-project-id", xTimevaleProjectId)
//                    .addHeader("x-timevale-signature", xTimevaleSignature)
//                    .addHeader("Content-Type", "application/json")
//                    .build();
//            Response response = client.newCall(request).execute();
//            int code = response.code();
//            if(code == 200){
//                msg = response.body().string();
//            }
//            log.error("msg:"+msg);
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }
//        return msg;
//    }

//    public static void main(String[] args) {
//        Esb2EsignSyncSealsCron esb2EsignQuerySealsAction = new Esb2EsignSyncSealsCron();
//        String pageIndex = "1";
//        String pageSize = "10";
//        String organizeNo = "91510115MA62QJQJ4N";
//
//        String querySealsUrl = Constants.querySealsUrl+"?pageIndex="+pageIndex+"&pageSize="+pageSize+"&organizeNo="+organizeNo;
//        esb2EsignQuerySealsAction.queryEsignSealTemplate(querySealsUrl,organizeNo);
//    }


//    public String encryptionHmacSHA256(String secretKey,String bodyData){
//        String encryptionData = "";
////        String secretKey = "7f067a08f5c675137e6e72aa298e2c07";
//        // 要签名的数据
////        JSONObject dataObject = new JSONObject();
////        dataObject.put("templateId","JMHT-ZXSJ");
////        String data = "{\"templateId\":\"JMHT-ZXSJ\"}" ;
//        try {
//            // 初始化Mac对象
//            Mac sha256Hmac = Mac.getInstance("HmacSHA256");
//            SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
//            sha256Hmac.init(secretKeySpec);
//            byte[] result = sha256Hmac.doFinal(bodyData.getBytes(StandardCharsets.UTF_8));
//            encryptionData = Hex.encodeHexString(result);
//        } catch (NoSuchAlgorithmException e) {
//            throw new RuntimeException(e);
//        }catch (InvalidKeyException e) {
//            throw new RuntimeException(e);
//        }
//        return encryptionData;
//    }
}
