package com.chenyang.nse.bussiness.controller.core;

import com.chenyang.nse.bussiness.commmon.json.RespHelper;
import com.chenyang.nse.bussiness.commmon.json.Response;
import com.chenyang.nse.bussiness.dao.table.core.TCoreDatasystemDao;
import com.chenyang.nse.bussiness.dao.table.core.encryption.ColumnPrimaryKeyInfoDao;
import com.chenyang.nse.bussiness.dao.table.core.encryption.TCoreDigestMainDao;
import com.chenyang.nse.bussiness.entity.db.ColumnInfo;
import com.chenyang.nse.bussiness.entity.orm.table.core.TCoreDatasystem;
import com.chenyang.nse.bussiness.entity.orm.table.core.TCoreDigestMain;
import com.chenyang.nse.bussiness.entity.vo.encyption.EncryptionConfigVO;
import com.chenyang.nse.bussiness.entity.vo.maskingtask.ColumnInfoVO;
import com.chenyang.nse.bussiness.service.core.TCoreDigestMainService;
import com.chenyang.nse.bussiness.service.core.encryption.EncryptionConfigService;
import com.chenyang.nse.bussiness.service.core.impl.TCoreDigestMainServiceImpl;
import com.chenyang.nse.bussiness.service.core.strategy.MaksingAppDataRuleService;
import com.chenyang.nse.bussiness.tools.propertyutil.PropertyGhcaUtil;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping({"/core/digestmain"})
public class TCoreDigestMainController {
   @Autowired
   private TCoreDigestMainService tCoreDigestMainService;
   @Autowired
   private MaksingAppDataRuleService maksingAppDataRuleService;
   @Autowired
   private TCoreDigestMainDao tCoreDigestMainDao;
   @Autowired
   EncryptionConfigService encryptionConfigService;
   @Autowired
   ColumnPrimaryKeyInfoDao columnPrimaryKeyInfoDao;
   @Autowired
   TCoreDatasystemDao tCoreDatasystemDao;

   @ResponseBody
   @RequestMapping({"/save"})
   public Response save(@RequestBody Map<String, Object> params) {
      String projectId = (String)params.get("projectid");
      String datasystemid = (String)params.get("datasystemid");
      String schema = (String)params.get("schema");
      String tablename = (String)params.get("table");
      String digestfield = (String)params.get("digestfield");
      TCoreDigestMain tCoreDigestMain = new TCoreDigestMain();
      tCoreDigestMain.setProjectid(projectId);
      tCoreDigestMain.setSchemaname(schema);
      tCoreDigestMain.setDatasystemid(datasystemid);
      tCoreDigestMain.setTablename(tablename);
      tCoreDigestMain.setDigestfield(digestfield);
      this.tCoreDigestMainService.save(tCoreDigestMain);
      return RespHelper.successResp();
   }

   @PostMapping({"/getfield"})
   @ResponseBody
   public Response getFieldByTablename(@RequestBody Map<String, Object> params) {
      String projectId = (String)params.get("projectid");
      String datasystemid = (String)params.get("datasystemid");
      String schema = (String)params.get("schema");
      String tablename = (String)params.get("tablename");
      List<ColumnInfoVO> columnInfoVOS = this.maksingAppDataRuleService.queryColumnInfo(datasystemid, schema, tablename);
      columnInfoVOS = (List)columnInfoVOS.stream().filter((cx) -> !cx.getColumnname().contains(PropertyGhcaUtil.copySuffix)).collect(Collectors.toList());
      columnInfoVOS.sort(Comparator.comparing(ColumnInfo::getColumnname));
      TCoreDigestMain digestMain = (TCoreDigestMain)this.tCoreDigestMainDao.queryUnique(new Criterion[]{Restrictions.eq("projectid", projectId), Restrictions.eq("datasystemid", datasystemid), Restrictions.eq("schemaname", schema), Restrictions.eq("tablename", tablename)});
      TCoreDatasystem datasystem = (TCoreDatasystem)this.tCoreDatasystemDao.get(datasystemid);
      if (!"MONGODB".equals(datasystem.getDbtype())) {
         for(ColumnInfoVO c : columnInfoVOS) {
            c.setTypename(c.getTypename().toUpperCase(Locale.ROOT));
         }
      }

      if (digestMain != null && StringUtils.isNotBlank(digestMain.getDigestfield())) {
         List<String> digestStrings = Arrays.asList(digestMain.getDigestfield().split("#"));

         for(ColumnInfoVO c : columnInfoVOS) {
            if (digestStrings.contains(c.getColumnname())) {
               c.setIsDigest("1");
            }
         }
      }

      Map<String, Object> map = new HashMap();
      map.put("list", columnInfoVOS);
      TCoreDigestMain DigestMain = this.tCoreDigestMainService.query(datasystemid, projectId, schema, tablename);
      if (null != DigestMain) {
         map.put("flag", DigestMain.getFlag());
      } else {
         map.put("list", "0");
      }

      return RespHelper.successResp(map);
   }

   @ResponseBody
   @RequestMapping({"/query"})
   public Response query(@RequestBody Map<String, String> map) {
      String dataSystemId = (String)map.get("datasystemid");
      String projectId = (String)map.get("projectid");
      String tableName = (String)map.get("table");
      String schema = (String)map.get("schema");
      TCoreDigestMain DigestMain = this.tCoreDigestMainService.query(dataSystemId, projectId, schema, tableName);
      return RespHelper.successResp(DigestMain);
   }

   @ResponseBody
   @RequestMapping({"/queryDatasystemInfo"})
   public Response queryDatasystemInfo(@RequestBody Map<String, String> map) {
      String dataSystemId = (String)map.get("datasystemid");
      String projectId = (String)map.get("projectid");
      Map<String, Object> result = this.tCoreDigestMainService.queryDatasystemInfo(projectId, dataSystemId);
      return RespHelper.successResp(result);
   }

   @ResponseBody
   @RequestMapping({"/querytableInfo"})
   public Response querytableInfo(@RequestBody Map<String, String> map) {
      String dataSystemId = (String)map.get("datasystemid");
      String projectId = (String)map.get("projectid");
      String tableName = (String)map.get("table");
      String schema = (String)map.get("schema");
      Map<String, Object> result = this.tCoreDigestMainService.querytableInfo(dataSystemId, projectId, schema, tableName);
      return RespHelper.successResp(result);
   }

   @ResponseBody
   @RequestMapping({"/generatedigest"})
   public Response generatedigest(@RequestBody Map<String, String> map) {
      String dataSystemId = (String)map.get("datasystemid");
      String projectId = (String)map.get("projectid");
      String tableName = (String)map.get("table");
      String schema = (String)map.get("schema");
      EncryptionConfigVO proEncryptionConfigVO = new EncryptionConfigVO();
      proEncryptionConfigVO.setDatasystem_id(dataSystemId);
      proEncryptionConfigVO.setSchema(schema);
      proEncryptionConfigVO.setTable_name(tableName);
      proEncryptionConfigVO.setProjectId(projectId);
      String tableString = projectId + "_" + dataSystemId + "_" + schema + "_" + tableName;
      if (TCoreDigestMainServiceImpl.tasktables != null && TCoreDigestMainServiceImpl.tasktables.contains(tableString)) {
         return RespHelper.createResp("POP_000153", "表正在被修改，无法生成校验列");
      } else {
         List<ColumnInfoVO> proColumnInfoVOList = this.encryptionConfigService.queryOriginalList(proEncryptionConfigVO);
         boolean hasPrimaryKey = false;
         int pt = proColumnInfoVOList.size();

         for(int y = 0; y < pt; ++y) {
            String proKey = ((ColumnInfoVO)proColumnInfoVOList.get(y)).getPrimarykey();
            if (proKey.equals("1")) {
               hasPrimaryKey = true;
               break;
            }
         }

         if (!hasPrimaryKey) {
            return RespHelper.createResp("POP_000153", "没有主键");
         } else {
            TCoreDigestMain digestMain = (TCoreDigestMain)this.tCoreDigestMainDao.queryUnique(new Criterion[]{Restrictions.eq("projectid", projectId), Restrictions.eq("datasystemid", dataSystemId), Restrictions.eq("schemaname", schema), Restrictions.eq("tablename", tableName)});
            if (digestMain != null && StringUtils.isBlank(digestMain.getDigestfield())) {
               return RespHelper.createResp("POP_000153", "没有设置校验列");
            } else {
               try {
                  this.tCoreDigestMainService.generatedigest(dataSystemId, projectId, schema, tableName);
               } catch (Exception e) {
                  e.printStackTrace();
                  return RespHelper.createResp("POP_000153", e.getMessage());
               }

               return RespHelper.successResp();
            }
         }
      }
   }

   @ResponseBody
   @RequestMapping({"/deletedigest"})
   public Response deletedigest(@RequestBody Map<String, String> map) {
      String dataSystemId = (String)map.get("datasystemid");
      String projectId = (String)map.get("projectid");
      String tableName = (String)map.get("table");
      String schema = (String)map.get("schema");
      String tableString = projectId + "_" + dataSystemId + "_" + schema + "_" + tableName;
      if (TCoreDigestMainServiceImpl.tasktables != null && TCoreDigestMainServiceImpl.tasktables.contains(tableString)) {
         return RespHelper.createResp("POP_000153", "表正在被修改，无法删除列");
      } else {
         try {
            this.tCoreDigestMainService.deletedigest(dataSystemId, projectId, schema, tableName);
         } catch (Exception e) {
            e.printStackTrace();
            return RespHelper.createResp("POP_000153", e.getMessage());
         }

         return RespHelper.successResp();
      }
   }

   @ResponseBody
   @RequestMapping({"/checkdigest"})
   public Response checkdigest(@RequestBody Map<String, String> map) {
      String dataSystemId = (String)map.get("datasystemid");
      String projectId = (String)map.get("projectid");
      String tableName = (String)map.get("table");
      String schema = (String)map.get("schema");
      boolean b = this.tCoreDigestMainService.checkdigest(dataSystemId, projectId, schema, tableName);
      return b ? RespHelper.errRespStr("校验成功") : RespHelper.errRespStr("校验失败");
   }
}
