package com.hzya.frame.sysnew.comparison.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.hzya.frame.basedao.service.impl.BaseService;
import com.hzya.frame.mdm.mdmModule.dao.IMdmModuleDao;
import com.hzya.frame.mdm.mdmModule.entity.MdmModuleEntity;
import com.hzya.frame.mdm.mdmModuleDb.entity.MdmModuleDbEntity;
import com.hzya.frame.mdm.mdmModuleDbFileds.entity.MdmModuleDbFiledsEntity;
import com.hzya.frame.mdm.mdmModuleView.dao.IMdmModuleViewDao;
import com.hzya.frame.mdm.mdmModuleView.entity.MdmModuleViewEntity;
import com.hzya.frame.mdm.service.impl.MdmServiceCache;
import com.hzya.frame.sysnew.application.entity.SysApplicationEntity;
import com.hzya.frame.sysnew.application.entity.SysExtensionApiEntity;
import com.hzya.frame.sysnew.comparison.controlsLog.dao.impl.ControlsLogDaoImpl;
import com.hzya.frame.sysnew.comparison.dao.IComparisonDao;
import com.hzya.frame.sysnew.comparison.dao.IComparisonDetailsDao;
import com.hzya.frame.sysnew.comparison.entity.ComparisonDetailsEntity;
import com.hzya.frame.sysnew.comparison.entity.ComparisonEntity;
import com.hzya.frame.sysnew.comparison.service.IComparisonService;
import com.hzya.frame.uuid.UUIDLong;
import com.hzya.frame.web.entity.BaseResult;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service(value = "comparisonServiceImpl")
public class ComparisonServiceImpl extends BaseService<ComparisonEntity, String> implements IComparisonService {

    private IComparisonDao comparisonDao;
    @Autowired
    private IMdmModuleDao mdmModuleDao;

    @Autowired
    private IComparisonDetailsDao comparisonDetailsDao;

    @Autowired
    private ControlsLogDaoImpl controlsLogDaoimpl;

    @Autowired
    private MdmServiceCache mdmServiceCache;

    @Autowired
    private IMdmModuleViewDao mdmModuleViewDao;

    @Autowired
    public void setGeneralDataDao(IComparisonDao dao) {
        this.comparisonDao = dao;
        this.dao = dao;
    }

    //分页查询通用数据数据
    @Override
    public Object queryEntityPage(JSONObject json) {
        JSONObject jsonObject = json.getJSONObject("jsonStr");
        JSONObject json1 = new JSONObject();
        if (jsonObject == null) {
            return BaseResult.getFailureMessageEntity("数据为空，请先传递数据");
        }
        if (!checkStr(jsonObject.getString("mdmCode"))) {
            return BaseResult.getFailureMessageEntity("主数据编码为空");
        }
        ComparisonEntity comparisonEntity = jsonObject.toJavaObject(ComparisonEntity.class);
        ComparisonDetailsEntity comparisonDetailsEntity=new ComparisonDetailsEntity();
        List<ComparisonEntity> comparisonEntities=new ArrayList<>();
        try {
            //根据主数据编码查询表名称，字段名称等信息 10001
            //comparisonEntities = comparisonDao.queryComparison(comparisonEntity);

            //comparisonEntities=getComparisonEntity(comparisonEntity);
            comparisonEntities=getComparisonEntityCache(comparisonEntity,"main");
        }catch (Exception e){
            logger.info("根据主数据编码查询信息错误:{}",e.getMessage());
            return BaseResult.getFailureMessageEntity("查询失败");
        }
        Map<String, Object> map = new HashMap<>();//将主表数据存到map中
        if (comparisonEntities != null && comparisonEntities.size() > 0) {
            for (ComparisonEntity entity : comparisonEntities) {
                //遍历主表下面的所有key,字段名
                for (String key : jsonObject.keySet()) {
                    if (entity.getDbType().equals("1")) {
                        comparisonEntity.setDbName(entity.getDbName());
                        if(!"mdmCode".equals(key)){
                            map.put(key, jsonObject.getString(key));
                            map.remove("appName");
                            map.remove("appCode");
                        }
                    }
                    if (entity.getDbType().equals("2")) {
                        comparisonDetailsEntity.setDbName(entity.getDbName());
                    }
                }
            }
            comparisonEntity.setMap(map);
            try {
                List<JSONObject> list=new ArrayList<>();
                //查询所有列
                List<String> fields = getFields(comparisonEntity);
                comparisonEntity.setFields(fields);
                //查询主表数据
                List<Map<String,Object>> comparisonEntitiePages = comparisonDao.queryComparisonPage(comparisonEntity);

                //递归查询组织树
                if(comparisonEntities.get(0).getViewName().equals("1")){
                     return  recursiveQueryComparison(comparisonEntitiePages,comparisonEntity);
                }

                if(CollectionUtils.isNotEmpty(comparisonEntitiePages)){
                    for (Map<String, Object> comparisonEntitiePage : comparisonEntitiePages) {
                        JSONObject jsonObjects=new JSONObject();
                        jsonObjects.put(comparisonEntity.getDbName(),comparisonEntitiePage);
                        if(comparisonDetailsEntity.getDbName()!=null){
                            comparisonDetailsEntity.setFormmainId(String.valueOf(comparisonEntitiePage.get("id")));
                            //查询明细表数据
                            List<Map<String, Object>> maps = comparisonDetailsDao.queryComparisonDetailsPage(comparisonDetailsEntity);
                            if(CollectionUtils.isNotEmpty(maps)){
                                jsonObjects.put(comparisonDetailsEntity.getDbName(),maps);
                            }else {
                                jsonObjects.put(comparisonDetailsEntity.getDbName(),new JSONArray());
                            }
                        }
                        list.add(jsonObjects);
                    }
                }
                PageInfo pageInfo = new PageInfo(list);

                json1.put("status","200");
                json1.put("pageInfo",pageInfo);
                return json1;
            } catch (Exception e) {
                logger.info("查询通用数据错误:{}", e.getMessage());
                return BaseResult.getFailureMessageEntity("查询失败");
            }
        }
        return BaseResult.getFailureMessageEntity("查询失败","请检查传递参数");
    }

    //新增通用数据数据
    @Override
    public Object saveEntity(JSONObject json) {
        JSONObject jsonObject = json.getJSONObject("jsonStr");
        if (jsonObject == null) {
            return BaseResult.getFailureMessageEntity("数据为空，请先传递数据");
        }
        if (!checkStr(jsonObject.getString("mdmCode"))) {
            return BaseResult.getFailureMessageEntity("主数据编码为空");
        }
        if (!checkStr(jsonObject.getString("optionName"))) {
            return BaseResult.getFailureMessageEntity("操作人为空");
        }
        ComparisonEntity comparisonEntity = jsonObject.toJavaObject(ComparisonEntity.class);
        ComparisonDetailsEntity comparisonDetailsEntity=new ComparisonDetailsEntity();
            List<ComparisonEntity> comparisonEntities=new ArrayList<>();
        String uuid= String.valueOf(UUIDLong.longUUID());
            try {
                //根据主数据编码查询表名称，字段名称等信息 10001
                // comparisonEntities = comparisonDao.queryComparison(comparisonEntity);

                //comparisonEntities=getComparisonEntity(comparisonEntity);
                comparisonEntities=getComparisonEntityCache(comparisonEntity,"main");
            }catch (Exception e){
                logger.info("根据主数据编码查询信息错误:{}",e.getMessage());
                return BaseResult.getFailureMessageEntity("保存失败");
            }
            JSONObject jsonObjectMain=new JSONObject();
            JSONArray jsonArray=new JSONArray();
            List<JSONArray> arrayList=new ArrayList<>();

        String tableName=null;
        //根据dbtype和dbname分组，拿到表名称和表类型
        Map<String, Map<String, List<ComparisonEntity>>> collect = comparisonEntities.stream().collect(Collectors.groupingBy(ComparisonEntity::getDbName, Collectors.groupingBy(ComparisonEntity::getDbType)));
        List<Map.Entry<String, String>> keyPairs = collect.entrySet().stream()
                .flatMap(e1 -> e1.getValue().keySet().stream()
                        .map(dbname -> new AbstractMap.SimpleEntry<>(e1.getKey(), dbname)))
                .collect(Collectors.toList());
        // keyPairs 得值为键值对，键是表名称，值是类型，避免多个子表得键一样，比如：mdm_customer:1,mdm_customer_bank:2,mdm_customer_option_log:2
        for (Map.Entry<String, String> keyPair : keyPairs) {
            //如果是1，就是主表，根据查询出来得主表是否是传输传递得主表
           if(keyPair.getValue().equals("1")){
               String main = jsonObject.getString(keyPair.getKey());
               tableName=keyPair.getKey();
               if(main!=null){
                   jsonObjectMain = JSONObject.parseObject(main);
                   if(!checkStr(jsonObjectMain.getString("data_id"))){
                       //保存操作日志
                       controlsLogDaoimpl.saveControlsLog(uuid,jsonObject.getString("appName"),jsonObject.getString("appCode"),jsonObject.toJSONString(),"接口新增",jsonObject.getString("optionName"),tableName+"_option_log","2");
                       return BaseResult.getFailureMessageEntity("新增时候主表data_id不能为空");
                   }
               }
           }
            //如果是2，就是明细表，根据查询出来得子表是否是传输传递得子表
           if(keyPair.getValue().equals("2")){
               jsonArray= jsonObject.getJSONArray(keyPair.getKey());
               if(jsonArray!= null) {
                   for (int i = 0; i < jsonArray.size(); i++) {
                       JSONObject jsonObjectDetails = jsonArray.getJSONObject(i);
                       jsonObjectDetails.put("table_name", keyPair.getKey());
                       if(!checkStr(jsonObjectDetails.getString("data_id"))){
                           //保存操作日志
                           controlsLogDaoimpl.saveControlsLog(uuid,jsonObject.getString("appName"),jsonObject.getString("appCode"),jsonObject.toJSONString(),"接口新增",jsonObject.getString("optionName"),tableName+"_option_log","2");
                           return BaseResult.getFailureMessageEntity("新增时候明细data_id不能为空");
                       }
                   }
                   arrayList.add(jsonArray);
               }
           }
        }
        if(jsonObjectMain!=null && jsonObjectMain.size()>0) {
              Map<String, Object> map = new HashMap<>();//将主表数据存到map中
              List<List<Map<String, Object>>> mapDetails = new ArrayList<>();//将子表数据存到map中
              if (comparisonEntities != null && comparisonEntities.size() > 0) {
                  map = spliceMainMap(comparisonEntities, jsonObjectMain, map, comparisonEntity, comparisonDetailsEntity);

                  //根据data_id判断数据是否已经保存在相关表中,避免重复保存
                  List<String> fields = getFields(comparisonEntity);
                  Map<String, Object> mapDataId = new HashMap<>();
                  mapDataId.put("data_id", jsonObjectMain.getString("data_id"));
                  ComparisonEntity comparisonDataId = new ComparisonEntity();
                  comparisonDataId.setMap(mapDataId);
                  comparisonDataId.setDbName(comparisonEntity.getDbName());
                  comparisonDataId.setFields(fields);
                  List<Map<String, Object>> listDataId = comparisonDao.queryComparisonPage(comparisonDataId);
                  if (CollectionUtils.isNotEmpty(listDataId)) {
                      //return BaseResult.getFailureMessageEntity(comparisonEntity.getDbName()+"表中已经存在data_id为:"+jsonObjectMain.getString("data_id")+"的数据");
                      return updateEntity(json);
                  } else {

                      //如果是树形结构，查询不存在，新增时候需要得到parent_id,根据parent_id查询data_id是否有，之后将查询得父id设置到mdm_up_id中
                      if(comparisonEntities.get(0).getViewName().equals("1")){
                          List<String> fieldParent = getFields(comparisonEntity);
                          Map<String, Object> mapParentId = new HashMap<>();
                          mapDataId.put("data_id", jsonObjectMain.getString("parent_id"));
                          ComparisonEntity comparisonParentId = new ComparisonEntity();
                          comparisonParentId.setMap(mapParentId);
                          comparisonParentId.setDbName(comparisonEntity.getDbName());
                          comparisonParentId.setFields(fieldParent);
                          List<Map<String, Object>> listParentId = comparisonDao.queryComparisonPage(comparisonDataId);
                          //如果根据parentid查询数据不为空，将dataid为parenti得id值设置到mdm_up_id中
                          if(CollectionUtils.isNotEmpty(listParentId)){
                              map.put("mdm_up_id",listParentId.get(0).get("id"));
                          }
                      }

                      //判断输入的主表字段是否是必填项
                      for (ComparisonEntity entity : comparisonEntities) {
                          //如果必填字段不为空
                          if (entity.getRuleValue() != null && entity.getDbType().equals("1")) {
                              //如果值为空，说明没有传这个字段或者这个字段的值为空
                              if (jsonObjectMain.getString(entity.getEnName()) == null || jsonObjectMain.getString(entity.getEnName()).equals("")) {
                                  //保存操作日志
                                  controlsLogDaoimpl.saveControlsLog(uuid, jsonObject.getString("appName"), jsonObject.getString("appCode"), jsonObject.toJSONString(), "接口新增", jsonObject.getString("optionName"), tableName + "_option_log", "2");
                                  return BaseResult.getFailureMessageEntity(entity.getDbName() + "表的" + entity.getEnName() + "字段不能为空");
                              }
                          }
                      }

                      map.put("id", uuid);
                      map.put("create_user_id", "c796fd9ba4c9f5ff3cc2fa41a040e443");
                      map.put("modify_user_id", "c796fd9ba4c9f5ff3cc2fa41a040e443");
                      map.put("org_id", "0");
                      map.put("create_time", new Date());
                      map.put("modify_time", new Date());
                      map.put("sts", "Y");
                      map.put("data_status", "Y");//新增状态
                      map.put("add_status", "0");//新增状态
                      map.put("update_status", "1");//修改状态
                      map.put("delete_status", "1");//删除状态
                      ComparisonEntity comparisonEntityRule = comparisonEntities.get(0);
                      //查询单据规则  只查询主表得，明细表不用
                      try {
                          ComparisonEntity comparisonEntityRules = comparisonDao.queryComparisonById(comparisonEntityRule);
                          String documentRule = comparisonEntityRules.getDocumentRule();//"KH-2024-05-30-1";
                          logger.info("通用数据保存接口中根据mId查询出来的单据规则为:{}", documentRule);
                          if (documentRule != null) {
                              //获取规则前缀 CK
                              String rulePrefix = documentRule.substring(0, documentRule.indexOf("-"));
                              //获取规则中间日期 yyyy-MM-dd
                              String ruleDate = documentRule.substring(documentRule.indexOf("-") + 1, documentRule.lastIndexOf("-"));
                              String ruleMiddle = getRuleDate(ruleDate);
                              //获取规则后缀
                              String ruleSuffixLength = documentRule.substring(documentRule.lastIndexOf("-") + 1);
                              int ruleSuffix = ruleSuffixLength.length();
                              //生成单据规则
                              comparisonEntityRule.setRulePrefix(rulePrefix);
                              comparisonEntityRule.setRuleMiddle(ruleMiddle);
                              comparisonEntityRule.setRuleSuffix(ruleSuffix);
                              try {
                                  //新生成单据规则保存到数据库
                                  ComparisonEntity comparisonEntityRuleGz = comparisonDao.queryComparisonRule(comparisonEntityRule);
                                  map.put("document_rule", comparisonEntityRuleGz.getDocumentRule());//单据规则
                                  map.put("document_rule_num", comparisonEntityRuleGz.getDocumentRuleNum());//单据规则流水号
                                  comparisonEntityRule.setMap(map);
                              } catch (Exception e) {
                                  logger.info("保存通用数据时候生成单据规则错误:{}", e.getMessage());
                                  //保存操作日志
                                  controlsLogDaoimpl.saveControlsLog(uuid, jsonObject.getString("appName"), jsonObject.getString("appCode"), jsonObject.toJSONString(), "接口新增", jsonObject.getString("optionName"), tableName + "_option_log", "2");

                                  return BaseResult.getFailureMessageEntity("保存失败");
                              }
                          }
                      } catch (Exception e) {
                          logger.info("通用数据保存接口中查询单据规则错误:{}", e.getMessage());
                          //保存操作日志
                          controlsLogDaoimpl.saveControlsLog(uuid, jsonObject.getString("appName"), jsonObject.getString("appCode"), jsonObject.toJSONString(), "接口新增", jsonObject.getString("optionName"), tableName + "_option_log", "2");

                          return BaseResult.getFailureMessageEntity("保存失败");
                      }
                      try {
                          List<JSONObject> list = new ArrayList<>();
                          JSONObject jsonObjectList = new JSONObject();

                          //判断明细表字段是否是必填项
                          if (arrayList != null && arrayList.size() > 0) {
                              for (JSONArray jsonArrayDetails : arrayList) {
                                  for (Object object : jsonArrayDetails) {
                                      JSONObject jsonObjectDetails = (JSONObject) JSON.toJSON(object);
                                      for (ComparisonEntity entity : comparisonEntities) {
                                          if (entity.getRuleValue() != null && entity.getDbType().equals("2")) {
                                              //如果值为空，说明没有传这个字段或者这个字段的值为空
                                              if (jsonObjectDetails.getString(entity.getEnName()) == null || jsonObjectDetails.getString(entity.getEnName()).equals("")) {
                                                  //保存操作日志
                                                  controlsLogDaoimpl.saveControlsLog(uuid, jsonObject.getString("appName"), jsonObject.getString("appCode"), jsonObject.toJSONString(), "接口新增", jsonObject.getString("optionName"), tableName + "_option_log", "2");
                                                  return BaseResult.getFailureMessageEntity(entity.getDbName() + "表的" + entity.getEnName() + "字段不能为空");
                                              }
                                          }
                                      }
                                  }
                              }
                          }

                          //保存主表数据
                          ComparisonEntity comparisonEntityOne = comparisonDao.saveComparison(comparisonEntityRule);
                          jsonObjectList.put(comparisonEntityOne.getDbName(), map);
                          //保存子表数据
                          if (arrayList != null && arrayList.size() > 0) {
                              mapDetails = spliceDetailMap(comparisonEntities, mapDetails, arrayList);
                              if (mapDetails.size() > 0 && mapDetails != null) {
                                  for (List<Map<String, Object>> mapDetail : mapDetails) {
                                      for (Map<String, Object> stringObjectMap : mapDetail) {
                                          stringObjectMap.put("id", UUIDLong.longUUID());
                                          stringObjectMap.put("formmain_id", uuid);
                                          stringObjectMap.put("create_user_id", "c796fd9ba4c9f5ff3cc2fa41a040e443");
                                          stringObjectMap.put("modify_user_id", "c796fd9ba4c9f5ff3cc2fa41a040e443");
                                          stringObjectMap.put("org_id", "0");
                                          stringObjectMap.put("create_time", new Date());
                                          stringObjectMap.put("modify_time", new Date());
                                          stringObjectMap.put("sts", "Y");
                                          stringObjectMap.put("data_status", "Y");//新增状态
                                          comparisonDetailsEntity.setMapDetails(stringObjectMap);
                                          comparisonDetailsEntity.setDbName(String.valueOf(stringObjectMap.get("table_name")));
                                          stringObjectMap.remove("table_name");
                                          ComparisonDetailsEntity comparisonDetailsEntityOne = comparisonDetailsDao.saveComparisonDetails(comparisonDetailsEntity);
                                          comparisonEntityOne.setComparisonDetailsEntity(comparisonDetailsEntityOne);
                                          //保存操作日志
                                          //controlsLogDaoimpl.saveControlsLog(uuidDetail,jsonObject.getString("appName"),jsonObject.getString("appCode"),jsonObject.toJSONString(),"接口新增",jsonObject.getString("optionName"),comparisonDetailsEntity.getDbName()+"_option_log");
                                      }
                                  }
                                  jsonObjectList.put(comparisonDetailsEntity.getDbName(), mapDetails);
                              }
                          } else {
                              jsonObjectList.put(comparisonDetailsEntity.getDbName(), new ArrayList<>());
                          }
                          jsonObjectList.remove(null);
                          list.add(jsonObjectList);
                          //保存操作日志
                          controlsLogDaoimpl.saveControlsLog(uuid, jsonObject.getString("appName"), jsonObject.getString("appCode"), jsonObject.toJSONString(), "接口新增", jsonObject.getString("optionName"), tableName + "_option_log", "1");
                          JSONObject json1 = new JSONObject();
                          json1.put("status", "200");
                          json1.put("list", list);
                          return json1;
                      } catch (Exception e) {
                          logger.info("保存通用数据时候错误:{}", e.getMessage());
                          //保存操作日志
                          controlsLogDaoimpl.saveControlsLog(uuid, jsonObject.getString("appName"), jsonObject.getString("appCode"), jsonObject.toJSONString(), "接口新增", jsonObject.getString("optionName"), tableName + "_option_log", "2");

                          return BaseResult.getFailureMessageEntity("保存失败");
                      }
                  }
              }
          }
        return BaseResult.getFailureMessageEntity("保存失败","请检查传递参数");
    }

    //更新通用数据数据
    @Override
    public Object updateEntity(JSONObject json) {
        JSONObject jsonObject = json.getJSONObject("jsonStr");
        if (jsonObject == null) {
            return BaseResult.getFailureMessageEntity("数据为空，请先传递数据");
        }
        if (!checkStr(jsonObject.getString("mdmCode"))) {
            return BaseResult.getFailureMessageEntity("主数据编码为空");
        }
        if (!checkStr(jsonObject.getString("optionName"))) {
            return BaseResult.getFailureMessageEntity("操作人为空");
        }
        ComparisonEntity comparisonEntity = jsonObject.toJavaObject(ComparisonEntity.class);
        ComparisonDetailsEntity comparisonDetailsEntity=new ComparisonDetailsEntity();
        List<ComparisonEntity> comparisonEntities=new ArrayList<>();
        //根据主数据编码查询表名称，字段名称等信息 10001
        try {
           // comparisonEntities = comparisonDao.queryComparison(comparisonEntity);

            //comparisonEntities=getComparisonEntity(comparisonEntity);
            comparisonEntities=getComparisonEntityCache(comparisonEntity,"main");
        }catch (Exception e){
            logger.info("根据主数据编码查询信息错误:{}",e.getMessage());
            return BaseResult.getFailureMessageEntity("更新失败");
        }
        JSONObject jsonObjectMain=new JSONObject();
        JSONArray jsonArray=new JSONArray();
        List<JSONArray> arrayList=new ArrayList<>();
        //根据dbtype和dbname分组，拿到表名称和表类型
        Map<String, Map<String, List<ComparisonEntity>>> collect = comparisonEntities.stream().collect(Collectors.groupingBy(ComparisonEntity::getDbName, Collectors.groupingBy(ComparisonEntity::getDbType)));
        List<Map.Entry<String, String>> keyPairs = collect.entrySet().stream()
                .flatMap(e1 -> e1.getValue().keySet().stream()
                        .map(dbname -> new AbstractMap.SimpleEntry<>(e1.getKey(), dbname)))
                .collect(Collectors.toList());
        for (Map.Entry<String, String> keyPair : keyPairs) {
            if(keyPair.getValue().equals("1")){
                String main = jsonObject.getString(keyPair.getKey());
                if(main!=null){
                    jsonObjectMain = JSONObject.parseObject(main);
                    if(!checkStr(jsonObjectMain.getString("data_id"))){
                        return BaseResult.getFailureMessageEntity("更新时候主表data_id不能为空");
                    }
                }
            }
            if(keyPair.getValue().equals("2")){
                jsonArray= jsonObject.getJSONArray(keyPair.getKey());
                if(jsonArray!= null) {
                    for (int i = 0; i < jsonArray.size(); i++) {
                        JSONObject jsonObjectDetails = jsonArray.getJSONObject(i);
                        if(!checkStr(jsonObjectDetails.getString("data_id"))){
                            return BaseResult.getFailureMessageEntity("更新明细表时候明细表data_id不能为空");
                        }
                        jsonObjectDetails.put("table_name", keyPair.getKey());
                    }
                    arrayList.add(jsonArray);
                }
            }
        }
        Map<String,Object> map=new HashMap<>();//将主表数据存到map中
        List<List<Map<String,Object>>> mapDetails=new ArrayList<>();//将子表数据存到map中
        if(comparisonEntities !=null && comparisonEntities.size()>0) {
            map=spliceMainMap(comparisonEntities,jsonObjectMain,map,comparisonEntity,comparisonDetailsEntity);
            //查询所有列
            List<String> fields = getFields(comparisonEntity);
            //根据data_id查询id.根据id更新主表数据,然后再根据主表id和明细表的data_id,删除明细表数据
            Map<String,Object> mapId=new HashMap<>();
            mapId.put("data_id",jsonObjectMain.getString("data_id"));
            ComparisonEntity comparison=new ComparisonEntity();
            comparison.setDbName(comparisonEntity.getDbName());
            comparison.setMap(mapId);
            comparison.setFields(fields);
            List<Map<String,Object>> comparisonEntitiePages = comparisonDao.queryComparisonPage(comparison);
            if(CollectionUtils.isEmpty(comparisonEntitiePages)){
                return BaseResult.getFailureMessageEntity("根据data_id查询id数据为空，请检查data_id");
            }

            //判断是否是树形结构
            if(comparisonEntities.get(0).getViewName().equals("1")){
                //根据data_id查询出parent_id，再根据parent_id得值查询data_id字段中为这个得值,如果有，将data_id为parent_id得id值保存到mdm_up_id中
                Map<String,Object> mapParent=new HashMap<>();
                mapParent.put("data_id",comparisonEntitiePages.get(0).get("parent_id"));
                ComparisonEntity comparisonParent=new ComparisonEntity();
                comparisonParent.setDbName(comparisonEntity.getDbName());
                comparisonParent.setMap(mapId);
                comparisonParent.setFields(fields);
                List<Map<String,Object>> comparisonEntitieParent = comparisonDao.queryComparisonPage(comparisonParent);
                if(!CollectionUtils.isEmpty(comparisonEntitieParent)){
                    map.put("mdm_up_id",comparisonEntitieParent.get(0).get("id"));
                }
            }

            String id = String.valueOf(comparisonEntitiePages.get(0).get("id"));
            map.put("create_user_id", "c796fd9ba4c9f5ff3cc2fa41a040e443");
            map.put("modify_user_id", "c796fd9ba4c9f5ff3cc2fa41a040e443");
            map.put("org_id", "0");
            map.put("modify_time", new Date());
            map.put("sts", "Y");
            map.put("data_status","F");//数据状态
            map.put("update_status","0");//修改状态
            map.remove("id");
            comparisonEntity.setMap(map);
            comparisonEntity.setId(id);
            try {
                List<JSONObject> jsonObjects=new ArrayList<>();
                JSONObject jsonObjectList=new JSONObject();
                //更新主表数据
                Integer integer = comparisonDao.updateComparisonByType(comparisonEntity);
                jsonObjectList.put(comparisonEntity.getDbName(),map);
                if (integer>0) {
                    //保存子表数据
                    if (arrayList != null && arrayList.size() > 0) {
                        mapDetails=spliceDetailMap(comparisonEntities,mapDetails,arrayList);
                        for (List<Map<String, Object>> mapDetail : mapDetails) {
                            for (Map<String, Object> stringObjectMap : mapDetail) {
                                stringObjectMap.put("create_user_id", "c796fd9ba4c9f5ff3cc2fa41a040e443");
                                stringObjectMap.put("modify_user_id", "c796fd9ba4c9f5ff3cc2fa41a040e443");
                                stringObjectMap.put("org_id", "0");
                                stringObjectMap.put("modify_time", new Date());
                                stringObjectMap.put("sts", "Y");
                                stringObjectMap.put("data_status","F");//数据状态
                                stringObjectMap.remove("id");
                                comparisonDetailsEntity.setDataId(String.valueOf(stringObjectMap.get("data_id")));
                                comparisonDetailsEntity.setFormmainId(id);
                                comparisonDetailsEntity.setMapDetails(stringObjectMap);
                                comparisonDetailsEntity.setDbName(String.valueOf(stringObjectMap.get("table_name")));
                                stringObjectMap.remove("table_name");
                                comparisonDetailsDao.updateComparisonDetailsByType(comparisonDetailsEntity);
                            }
                        }
                        jsonObjectList.put(comparisonDetailsEntity.getDbName(),mapDetails);
                    }else{
                        jsonObjectList.put(comparisonDetailsEntity.getDbName(),new ArrayList<>());
                    }
                    jsonObjectList.remove(null);
                    jsonObjects.add(jsonObjectList);
                    //保存操作日志
                    controlsLogDaoimpl.saveControlsLog(comparisonEntity.getId(),jsonObject.getString("appName"),jsonObject.getString("appCode"),jsonObject.toJSONString(),"接口更新",jsonObject.getString("optionName"),comparisonEntity.getDbName()+"_option_log","1");
                    JSONObject json1 = new JSONObject();
                    json1.put("status","200");
                    json1.put("list",jsonObjects);
                    return json1;
                }else{
                    return BaseResult.getFailureMessageEntity("更新失败");
                }
            } catch (Exception e) {
                logger.info("更新通用数据时候错误:{}", e.getMessage());
                //保存操作日志
                controlsLogDaoimpl.saveControlsLog(comparisonEntity.getId(),jsonObject.getString("appName"),jsonObject.getString("appCode"),jsonObject.toJSONString(),"接口更新",jsonObject.getString("optionName"),comparisonEntity.getDbName()+"_option_log","2");
                return BaseResult.getFailureMessageEntity("更新失败");
            }
        }
        return BaseResult.getFailureMessageEntity("更新失败","请检查传递参数");
    }

    private List<String> getFields(ComparisonEntity comparisonEntity) {
        HashMap<String, Object> maps = new HashMap<>();
        maps.put("tableName",comparisonEntity.getDbName());
        return mdmModuleDao.queryMdMFields(maps);
    }

    //删除通用数据
    @Override
    public Object deleteEntity(JSONObject json) {
        JSONObject jsonObject = json.getJSONObject("jsonStr");
        if (jsonObject == null) {
            return BaseResult.getFailureMessageEntity("数据为空，请先传递数据");
        }
        if (!checkStr(jsonObject.getString("mdmCode"))) {
            return BaseResult.getFailureMessageEntity("主数据编码为空");
        }
        if (!checkStr(jsonObject.getString("optionName"))) {
            return BaseResult.getFailureMessageEntity("操作人为空");
        }
        ComparisonEntity comparisonEntity = jsonObject.toJavaObject(ComparisonEntity.class);
        ComparisonDetailsEntity comparisonDetailsEntity=new ComparisonDetailsEntity();
        List<ComparisonEntity> comparisonEntities=new ArrayList<>();
        //根据主数据编码查询表名称，字段名称等信息 10001
        try {
           // comparisonEntities = comparisonDao.queryComparison(comparisonEntity);

            //comparisonEntities=getComparisonEntity(comparisonEntity);
            comparisonEntities=getComparisonEntityCache(comparisonEntity,"main");
        }catch (Exception e){
            logger.info("根据主数据编码查询信息错误:{}",e.getMessage());
            return BaseResult.getFailureMessageEntity("删除失败");
        }
        JSONObject jsonObjectMain=new JSONObject();
        //根据dbtype和dbname分组，拿到表名称和表类型
        Map<String, Map<String, List<ComparisonEntity>>> collect = comparisonEntities.stream().collect(Collectors.groupingBy(ComparisonEntity::getDbName, Collectors.groupingBy(ComparisonEntity::getDbType)));
        List<Map.Entry<String, String>> keyPairs = collect.entrySet().stream()
                .flatMap(e1 -> e1.getValue().keySet().stream()
                        .map(dbname -> new AbstractMap.SimpleEntry<>(e1.getKey(), dbname)))
                .collect(Collectors.toList());
        for (Map.Entry<String, String> keyPair : keyPairs) {
            if(keyPair.getValue().equals("1")){
                String main = jsonObject.getString(keyPair.getKey());
                if(main!=null){
                    jsonObjectMain = JSONObject.parseObject(main);
                    if(!checkStr(jsonObjectMain.getString("data_id"))){
                        return BaseResult.getFailureMessageEntity("更新时候主表data_id不能为空");
                    }
                }
            }
        }

        Map<String,Object> map=new HashMap<>();
        if(comparisonEntities !=null && comparisonEntities.size()>0) {
            for (ComparisonEntity entity : comparisonEntities) {
                //遍历主表下面的所有key,字段名
                for (String key : jsonObjectMain.keySet()) {
                    if (entity.getDbType().equals("1")) {
                        comparisonEntity.setDbName(entity.getDbName());
                        if(entity.getEnName().equals(key)){
                            map.put(key, jsonObjectMain.getString(key));
                        }
                    }
                    if(entity.getDbType().equals("2")){
                        comparisonDetailsEntity.setDbName(entity.getDbName());
                    }
                }
            }
            //查询所有列
            List<String> fields = getFields(comparisonEntity);
            //根据data_id查询主表id.根据id删除主表数据，然后再根据主表id和明细表data_id删除明细表数据
            Map<String,Object> mapId=new HashMap<>();
            mapId.put("data_id",jsonObjectMain.getString("data_id"));
            ComparisonEntity comparison=new ComparisonEntity();
            comparison.setDbName(comparisonEntity.getDbName());
            comparison.setMap(mapId);
            comparison.setFields(fields);
            List<Map<String,Object>> comparisonEntitiePages = comparisonDao.queryComparisonPage(comparison);
            if(CollectionUtils.isEmpty(comparisonEntitiePages)){
                return BaseResult.getFailureMessageEntity("根据data_id查询id数据为空，请检查data_id");
            }

            //递归删除树结构  1.树  2.列表
            if(comparisonEntities.get(0).getViewName().equals("1")){
               return recursiveDeleteComparison(comparisonEntitiePages,comparisonEntity);
            }

            String id = String.valueOf(comparisonEntitiePages.get(0).get("id"));

            map.remove("id");
            comparisonEntity.setId(id);
            comparisonEntity.setModify_user_id("c796fd9ba4c9f5ff3cc2fa41a040e443");
            comparisonEntity.setMap(map);
            try {
                Integer integer = comparisonDao.deleteComparison(comparisonEntity);
                if(integer>0){
                    if(comparisonDetailsEntity.getDbName()!=null){
                        comparisonDetailsEntity.setFormmainId(id);
                        comparisonDetailsEntity.setModify_user_id("c796fd9ba4c9f5ff3cc2fa41a040e443");
                        comparisonDetailsDao.deleteComparisonDetails(comparisonDetailsEntity);
                        // controlsLogDaoimpl.saveControlsLog(comparisonDetailsEntity.getId(),jsonObject.getString("appName"),jsonObject.getString("appCode"),jsonObject.toJSONString(),"接口删除",jsonObject.getString("optionName"),comparisonEntity.getDbName()+"_option_log");
                    }
                    controlsLogDaoimpl.saveControlsLog(comparisonEntity.getId(),jsonObject.getString("appName"),jsonObject.getString("appCode"),jsonObject.toJSONString(),"接口删除",jsonObject.getString("optionName"),comparisonEntity.getDbName()+"_option_log","1");
                    JSONObject json1 = new JSONObject();
                    json1.put("status","200");
                    json1.put("integer",integer);
                    return json1;
                }else{
                    return BaseResult.getFailureMessageEntity("删除失败","请查看data_id是否在表中存在");
                }
            }catch (Exception e){
                logger.info("删除通用数据数据错误:{}",e.getMessage());
                controlsLogDaoimpl.saveControlsLog(comparisonEntity.getId(),jsonObject.getString("appName"),jsonObject.getString("appCode"),jsonObject.toJSONString(),"接口删除",jsonObject.getString("optionName"),comparisonEntity.getDbName()+"_option_log","2");
                return BaseResult.getFailureMessageEntity("删除失败");
            }
        }
        return BaseResult.getFailureMessageEntity("删除失败","请检查传递参数");
    }

    //递归删除组织树
    private Object recursiveDeleteComparison(List<Map<String,Object>> list,ComparisonEntity comparisonEntity){
        for(int i=0;i<list.size();i++){
            List<String> fields = getFields(comparisonEntity);
            Map<String,Object> mapId=new HashMap<>();
            mapId.put("mdm_up_id",list.get(0).get("id"));
            ComparisonEntity comparison=new ComparisonEntity();
            comparison.setDbName(comparisonEntity.getDbName());
            comparison.setMap(mapId);
            comparison.setFields(fields);
            List<Map<String,Object>> comparisonEntitiePages = comparisonDao.queryComparisonPage(comparison);
            if(CollectionUtils.isNotEmpty(comparisonEntitiePages)){
                recursiveDeleteComparison(comparisonEntitiePages,comparisonEntity);
            }
            comparisonEntity.setId(String.valueOf(list.get(0).get("id")));
            Integer integer = comparisonDao.deleteComparison(comparisonEntity);
            JSONObject json1 = new JSONObject();
            json1.put("status","200");
            json1.put("integer",integer);
            return json1;
        }
        return null;
    }

    //递归查询组织树
    private Object recursiveQueryComparison(List<Map<String,Object>> list,ComparisonEntity comparisonEntity){
      if(CollectionUtils.isNotEmpty(list)) {
          for (int i = 0; i < list.size(); i++) {
              List<String> fields = getFields(comparisonEntity);
              Map<String,Object> mapId=new HashMap<>();
              mapId.put("mdm_up_id",list.get(0).get("id"));
              ComparisonEntity comparison=new ComparisonEntity();
              comparison.setDbName(comparisonEntity.getDbName());
              comparison.setMap(mapId);
              comparison.setFields(fields);
              List<Map<String,Object>> comparisonEntitiePages = comparisonDao.queryComparisonPage(comparison);
              if(CollectionUtils.isNotEmpty(comparisonEntitiePages)){
                  recursiveQueryComparison(comparisonEntitiePages,comparisonEntity);
                  for (Map<String, Object> map : list) {
                      map.put("comparisonEntities",comparisonEntitiePages);
                  }
              }
              PageInfo pageInfo = new PageInfo(list);
              JSONObject json1=new JSONObject();
              json1.put("status","200");
              json1.put("pageInfo",pageInfo);
              return json1;
          }
      }
      return null;
    }

    //根据应用key和应用密钥获取应用编码和应用名称
    @Override
    public SysExtensionApiEntity getAppNameAndCode(SysExtensionApiEntity sysExtensionApiEntity) {
        String bodys = sysExtensionApiEntity.getBodys();
        SysApplicationEntity sendApp = sysExtensionApiEntity.getSendApp();
        JSONObject jsonObject = JSON.parseObject(bodys);
        jsonObject.put("appName",sendApp.getName());
        jsonObject.put("appCode",sendApp.getAppId());
        sysExtensionApiEntity.setBodys(jsonObject.toJSONString());
        return sysExtensionApiEntity;
    }

    //根据不同的日期格式，返回不同的值
    private String getRuleDate(String str){
        switch (str){
            case "yyyy-MM-dd":
                return "%Y-%m-%d";
            case "yyyyMMdd":
                return "%Y%m%d";
            case "yyyy-MM-dd HH:mm:ss":
                return "Y-%m-%d %H:%i:%s";
            case "yyyyMMddHHmmss":
                return "%Y%m%d%H%i%s";
            case "yyyyMMddHHmmssSSS":
                return "%Y%m%d%H%i%s%f";
            default:
                return null;
        }
    }

    //得到主表数据
    private Map<String,Object> spliceMainMap(List<ComparisonEntity> comparisonEntities,JSONObject jsonObjectMain,Map<String, Object> map,ComparisonEntity comparisonEntity,ComparisonDetailsEntity comparisonDetailsEntity){
        for (ComparisonEntity entity : comparisonEntities) {
            //遍历主表下面的所有key,字段名
            for (String key : jsonObjectMain.keySet()) {
                if (entity.getDbType().equals("1")) {
                    comparisonEntity.setDbName(entity.getDbName());
                    //如果表中得字段与输入得字段相等，则存起来
                    if(entity.getEnName().equals(key)){
                        map.put(key, jsonObjectMain.getString(key));
                    }
                }
                if(entity.getDbType().equals("2")){
                    comparisonDetailsEntity.setDbName(entity.getDbName());
                }
            }
        }
        return map;
    }

    //得到明细表数据
    private List<List<Map<String, Object>>> spliceDetailMap(List<ComparisonEntity> comparisonEntities,List<List<Map<String, Object>>> mapDetails,List<JSONArray> arrayList){
        if (arrayList != null && arrayList.size() > 0) {
            for (JSONArray jsonArray : arrayList) {
                List<Map<String,Object>> list=new ArrayList<>();
                for (Object object : jsonArray) {
                    JSONObject jsonObject = new JSONObject();
                    JSONObject jsonObjectDetails = (JSONObject) JSON.toJSON(object);
                    //遍历主表下面的所有key,字段名
                    for (String key : jsonObjectDetails.keySet()) {
                        for (ComparisonEntity entity : comparisonEntities) {
                            if (entity.getDbType().equals("2") && entity.getEnName().equals(key)) {
                                jsonObject.put(key, jsonObjectDetails.getString(key));
                            }
                            if(key.equals("table_name")){
                                jsonObject.put(key,jsonObjectDetails.getString(key));
                            }
                        }
                    }
                    list.add(jsonObject);
                }
                mapDetails.add(list);
            }
        }
        return mapDetails;
    }

    //根据主数据编码获取主表和明细表表名称，表字段信息
    public List<ComparisonEntity> getComparisonEntityCache(ComparisonEntity comparison,String type){
        List<ComparisonEntity> comparisonEntities = new ArrayList<>();
        //根据主数据编号获取模板主表
        MdmModuleEntity mdmModuleEntity = mdmServiceCache.getMdmModuleEntity(Long.valueOf(comparison.getMdmCode()));
        //根据模板主表id获取模版表数据
        if(mdmModuleEntity!=null){
            //根据mdm_id查询mdm_module_db_fileds_rule中的必填项字段
            ComparisonEntity comparisonEntity=new ComparisonEntity();
            comparisonEntity.setmId(mdmModuleEntity.getId());
            List<ComparisonEntity> comparisonEntitiesFieldRule = comparisonDao.queryComparisonBymdmIdDbIdFiledId(comparisonEntity);

            //根据mdm_module得id判断是树结构还是列表结构
            MdmModuleViewEntity mdmModuleViewEntity=new MdmModuleViewEntity();
            mdmModuleViewEntity.setMdmId(mdmModuleEntity.getId());
            List<MdmModuleViewEntity> mdmModuleViewEntities = mdmModuleViewDao.query(mdmModuleViewEntity);

            //根据mdm_id查询mdm_module_db的信息
            MdmModuleDbEntity mdmModuleDbEntity = new MdmModuleDbEntity();
            mdmModuleDbEntity.setMdmId(mdmModuleEntity.getId());
            List<MdmModuleDbEntity> mdmModuleDbEntities = mdmServiceCache.queryMdmModuleDb(mdmModuleDbEntity);
            if(CollectionUtils.isNotEmpty(mdmModuleDbEntities)){
                for (MdmModuleDbEntity moduleDbEntity : mdmModuleDbEntities) {
                    switch (type){
                        case "main":
                            //获取主表和明细表的字段信息
                            if(moduleDbEntity.getDbType().equals("1") || moduleDbEntity.getDbType().equals("2")){
                                MdmModuleDbFiledsEntity mdmModuleDbFiledsEntity=new MdmModuleDbFiledsEntity();
                                mdmModuleDbFiledsEntity.setMdmId(mdmModuleEntity.getId());
                                List<MdmModuleDbFiledsEntity> mdmModuleDbFiledsEntities = mdmServiceCache.queryMdmModuleDbFileds(mdmModuleDbFiledsEntity);
                                if(CollectionUtils.isNotEmpty(mdmModuleDbFiledsEntities)){
                                    for (MdmModuleDbFiledsEntity moduleDbFiledsEntity : mdmModuleDbFiledsEntities) {
                                        if (moduleDbFiledsEntity.getDbId().equals(moduleDbEntity.getId())) {
                                            ComparisonEntity comparisonEntityFile = new ComparisonEntity();
                                            comparisonEntityFile.setChName(moduleDbFiledsEntity.getChName());
                                            comparisonEntityFile.setEnName(moduleDbFiledsEntity.getEnName());
                                            comparisonEntityFile.setFiledType(moduleDbFiledsEntity.getFiledType());
                                            comparisonEntityFile.setAddType(moduleDbFiledsEntity.getAddType());
                                            comparisonEntityFile.setUpdateType(moduleDbFiledsEntity.getUpdateType());
                                            comparisonEntityFile.setShowType(moduleDbFiledsEntity.getShowType());
                                            comparisonEntityFile.setQueryType(moduleDbFiledsEntity.getQueryType());
                                            comparisonEntityFile.setListType(moduleDbFiledsEntity.getListType());
                                            comparisonEntityFile.setViewType(moduleDbFiledsEntity.getViewType());
                                            comparisonEntityFile.setDbName(moduleDbEntity.getDbName());
                                            comparisonEntityFile.setDbType(moduleDbEntity.getDbType());
                                            comparisonEntityFile.setDbId(moduleDbEntity.getId());
                                            comparisonEntityFile.setmId(mdmModuleEntity.getId());
                                            comparisonEntityFile.setMdmName(mdmModuleEntity.getMdmName());
                                            comparisonEntityFile.setMdmCode(String.valueOf(mdmModuleEntity.getMdmCode()));
                                            comparisonEntityFile.setViewName(CollectionUtils.isNotEmpty(mdmModuleViewEntities)?mdmModuleViewEntities.get(0).getViewName():null);
                                            if(CollectionUtils.isNotEmpty(comparisonEntitiesFieldRule)){
                                                for (ComparisonEntity entity : comparisonEntitiesFieldRule) {
                                                    if(entity.getEnName().equals(moduleDbFiledsEntity.getEnName()) && entity.getDbType().equals(moduleDbEntity.getDbType())){
                                                        //设置rule_code和rule_value，用于判断字段是否是必填项
                                                        comparisonEntityFile.setRuleCode(entity.getRuleCode());
                                                        comparisonEntityFile.setRuleValue(entity.getRuleValue());
                                                    }
                                                }
                                            }
                                            comparisonEntities.add(comparisonEntityFile);
                                        }
                                    }
                                }
                            }
                            break;
                        case "option":
                            if(moduleDbEntity.getDbType().equals("3")){
                                MdmModuleDbFiledsEntity mdmModuleDbFiledsEntity=new MdmModuleDbFiledsEntity();
                                mdmModuleDbFiledsEntity.setDbId(moduleDbEntity.getId());
                                List<MdmModuleDbFiledsEntity> mdmModuleDbFiledsEntities = mdmServiceCache.queryMdmModuleDbFileds(mdmModuleDbFiledsEntity);
                                if(CollectionUtils.isNotEmpty(mdmModuleDbFiledsEntities)){
                                    for (MdmModuleDbFiledsEntity moduleDbFiledsEntity : mdmModuleDbFiledsEntities) {
                                        if (moduleDbFiledsEntity.getDbId().equals(moduleDbEntity.getId())) {
                                            ComparisonEntity comparisonEntityFile = new ComparisonEntity();
                                            comparisonEntityFile.setChName(moduleDbFiledsEntity.getChName());
                                            comparisonEntityFile.setEnName(moduleDbFiledsEntity.getEnName());
                                            comparisonEntityFile.setFiledType(moduleDbFiledsEntity.getFiledType());
                                            comparisonEntityFile.setAddType(moduleDbFiledsEntity.getAddType());
                                            comparisonEntityFile.setUpdateType(moduleDbFiledsEntity.getUpdateType());
                                            comparisonEntityFile.setShowType(moduleDbFiledsEntity.getShowType());
                                            comparisonEntityFile.setQueryType(moduleDbFiledsEntity.getQueryType());
                                            comparisonEntityFile.setListType(moduleDbFiledsEntity.getListType());
                                            comparisonEntityFile.setViewType(moduleDbFiledsEntity.getViewType());
                                            comparisonEntityFile.setDbName(moduleDbEntity.getDbName());
                                            comparisonEntityFile.setDbType(moduleDbEntity.getDbType());
                                            comparisonEntityFile.setDbId(moduleDbEntity.getId());
                                            comparisonEntityFile.setmId(mdmModuleEntity.getId());
                                            comparisonEntityFile.setMdmName(mdmModuleEntity.getMdmName());
                                            comparisonEntityFile.setMdmCode(String.valueOf(mdmModuleEntity.getMdmCode()));
                                            comparisonEntities.add(comparisonEntityFile);
                                        }
                                    }
                                }
                            }
                            break;
                        default:
                            break;
                    }

                }
            }
            return comparisonEntities;
        }
        return null;
    }



}
