package com.weaver.seconddev.chapanda.esign.esb;

import com.alibaba.fastjson.JSON;
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.SealTemplateDao;
import com.weaver.seconddev.chapanda.esign.util.EbuilderOperateUtils;
import com.weaver.seconddev.chapanda.esign.util.Esb2EsignSealTemplateUtil;
import com.weaver.seconddev.chapanda.esign.util.Esb2EsignTemplateFormUtil;
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("Esb2EsignSyncTemplateCron")
public class Esb2EsignSyncTemplateCron implements EsbServerlessRpcRemoteInterface {
    private final static Logger log = LoggerFactory.getLogger(Esb2EsignSyncTemplateCron.class);


    @Autowired
    FormFieldDao formFieldDao;

    @Autowired
    EbuilderOperateUtils ebuilderOperateUtils;

    @Autowired
    Esb2EsignSealTemplateUtil esb2EsignSealTemplateUtil;

    @Autowired
    SealTemplateDao sealTemplateDao;

    @Autowired
    Esb2EsignTemplateFormUtil esb2EsignTemplateFormUtil;

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

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

        JSONArray templateArray = queryTemplateData();

        int effectiveTotal = 0;
        int failTotal = 0;

        log.error("templateArray:{}",templateArray.size());
        if(templateArray.size() > 0){

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

            for(int i=0;i<templateArray.size();i++){
                JSONObject dataJson = templateArray.getJSONObject(i);
                log.error("dataJson2:{}",dataJson.toJSONString());
                if(dataJson.containsKey("mbid") && StringUtils.isNotBlank(dataJson.getString("mbid"))){
                    String mbid = dataJson.getString("mbid");
                    log.error("mbid:{}",mbid);
                    String ufId = sealTemplateDao.queryTemplateDataByTemplateId(mbid);
                    log.error("ufId:{}",ufId);
                    if(StringUtils.isBlank(ufId)){
                        log.error("新增");
                        EBDataReqDto ebDataReqDto = new EBDataReqDto();
                        List<EBDataReqDetailDto> mainData = appendMainData(dataJson);
                        if(mainData.size() > 0){
                            ebDataReqDto.setMainDatas(mainData);
                            Map<Long, List<List<EBDataReqDetailDto>>> detailDatas = appendDetailData(mbid);
                            ebDataReqDto.setDetailDatas(detailDatas);
                            addDatas.add(ebDataReqDto);
                        }
                    }
//
//                    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());

            Map<String,Object> recordMap = formFieldDao.queryTableFormId(Constants.templateTable);
            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){

                    for(int i=0;i<addDatas.size();i++){
                        EBDataReqDto ebdatareqdto = addDatas.get(i);
                        log.error("ebdatareqdto:{}",JSON.toJSON(ebdatareqdto).toString());
                    }
                    EBDataChangeResult addEbDataChangeResult = ebuilderOperateUtils.bacthInsertEbDetailForm(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());
//                    }
//                }
            }
        }

        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);
    }


    /***
     *
     * @return
     */
    public JSONArray queryTemplateData(){

        JSONArray templateArray = new JSONArray();

        int pageSize = 30;
        int totalCount = 0;
        JSONArray itemArray = new JSONArray();
        int pageIndex = 1;
        String msg = esb2EsignSealTemplateUtil.queryTemplateData(pageIndex,pageSize);
        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("totalCount")){
                            totalCount = dataJson.getInteger("totalCount");
                        }
                    }
                }
            }
            itemArray = esb2EsignSealTemplateUtil.queryTemplateArray(msg);
        }

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

        if (totalCount <= pageSize) {
            templateArray.addAll(itemArray);
        } else {
            templateArray.addAll(itemArray);
            int pageCount = (int) Math.floor(totalCount / (pageSize * 1.0));
            log.error("pageCount:" + pageCount);
            for (int i = 1; i < pageCount; i++) {
                int pageIndex2 = i + 1;
                String msg2 = esb2EsignSealTemplateUtil.queryTemplateData(pageIndex2,pageSize);
                JSONArray itemArray2 = esb2EsignSealTemplateUtil.queryTemplateArray(msg2);
                templateArray.addAll(itemArray2);
            }
        }

        log.error("templateArray:" + templateArray.size());
        return templateArray;
    }



    /**
     *
     * @param mbid
     * @return
     */
    public Map<Long, List<List<EBDataReqDetailDto>>> appendDetailData(String mbid){
        Map<Long, List<List<EBDataReqDetailDto>>> detailDatas = new HashMap<Long, List<List<EBDataReqDetailDto>>>();
        List<String> detailList = new ArrayList<String>();
        detailList.add("zdm");
        detailList.add("zdmc");

        long subformId = formFieldDao.queryTableFormIdByEb(Constants.templateTableZdb);
        log.error("subformId:{}",subformId);
        Map<String, Object> detailFieldMap = formFieldDao.queryDetailTableField(Constants.templateTable,Constants.templateTableZdb, detailList);
        log.error("detailFieldMap:{}",detailFieldMap.size());
        JSONArray formArray = esb2EsignTemplateFormUtil.queryTemplateFormData(mbid);
        // 明细数据参数
        log.error("formArray:{}",formArray.size());

        List<List<EBDataReqDetailDto>> subFormDatas = new ArrayList<List<EBDataReqDetailDto>>();
        for(int i=0;i<formArray.size();i++){
            JSONObject formJson = formArray.getJSONObject(i);
            log.error("formJson:{}",formJson.toJSONString());
            List<EBDataReqDetailDto> subFormRowData = new ArrayList<>();
            for(int n=0;n<detailList.size();n++){
                if(formJson.containsKey(detailList.get(n)) && detailFieldMap.containsKey(detailList.get(n))){
                    String value = formJson.getString(detailList.get(n));
                    String fieldId = detailFieldMap.get(detailList.get(n)).toString();

                    log.error("fieldId2:{}",fieldId);
                    log.error("value2:{}",value);
                    subFormRowData.add(new EBDataReqDetailDto(fieldId, value));
                }
            }
            subFormDatas.add(subFormRowData);
        }
        detailDatas.put(subformId, subFormDatas);

        return detailDatas;
    }


    public List<EBDataReqDetailDto> appendMainData(JSONObject dataJson){

        List<EBDataReqDetailDto> mainData = new ArrayList<EBDataReqDetailDto>();
        List<String> fieldList = new ArrayList<String>();
        fieldList.add("mbid");
        fieldList.add("mbmc");
        fieldList.add("sfqy");

        Map<String, Object> fieldMap = formFieldDao.queryFromTableField(Constants.templateTable,fieldList);
        log.error("fieldMap:{}",fieldMap.size());
        log.error("sfqy:{}",String.valueOf(fieldMap.get("sfqy")));

        mainData.add(new EBDataReqDetailDto(String.valueOf(fieldMap.get("sfqy")), "1"));

        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));

            }
        }
        return mainData;
    }



}
