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.PageInfo;
import com.chenyang.nse.bussiness.dao.table.base.TBaseRoleDao;
import com.chenyang.nse.bussiness.dao.table.core.encryption.DesensitizationStrategyDao;
import com.chenyang.nse.bussiness.dao.table.core.encryption.TCoreDesensitizationStrategyLogDao;
import com.chenyang.nse.bussiness.dao.table.core.encryption.TCoreEncrypLogDao;
import com.chenyang.nse.bussiness.entity.orm.table.base.TBaseRole;
import com.chenyang.nse.bussiness.entity.orm.table.core.encryption.TCoreDesensitizationStrategy;
import com.chenyang.nse.bussiness.entity.orm.table.core.encryption.TCoreDesensitizationStrategyLog;
import com.chenyang.nse.bussiness.entity.vo.strategy.TCoreDesensitizationStrategyVO;
import com.chenyang.nse.bussiness.jar.db.TCoreClientInfo;
import com.chenyang.nse.bussiness.jar.util.JarClientUtil;
import com.chenyang.nse.bussiness.service.core.encryption.DesensitizationStrategyService;
import com.chenyang.nse.bussiness.service.core.encryption.EncryptionProxyService;
import com.chenyang.nse.bussiness.tools.encryption.SM3Utils;
import com.chenyang.nse.bussiness.tools.strategy.StrategyData;
import com.chenyang.nse.bussiness.tools.token.TokenUtil;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import jodd.util.ThreadUtil;
import org.apache.commons.collections.CollectionUtils;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Controller
@RequestMapping({"/core/desensitizationStrategy"})
public class DesensitizationStrategyController {
   @Autowired
   DesensitizationStrategyService desensitizationStrategyService;
   @Autowired
   DesensitizationStrategyDao desensitizationStrategyDao;
   @Autowired
   StrategyData strategyData;
   @Autowired
   private TBaseRoleDao tBaseRoleDao;
   @Autowired
   EncryptionProxyService encryptionProxyService;
   @Autowired
   private TCoreEncrypLogDao tCoreEncrypLogDao;
   @Autowired
   TCoreDesensitizationStrategyLogDao tCoreDesensitizationStrategyLogDao;

   @ResponseBody
   @RequestMapping({"/save"})
   public Response<String> save(@RequestBody Map<String, Object> map, HttpServletRequest request, HttpServletResponse response) {
      String strategyId = (String)map.get("strategyId");
      if (null == strategyId || strategyId.equals("")) {
         UUID strategUuid = UUID.randomUUID();
         strategyId = strategUuid.toString().replace("-", "");
      }

      String strategyName = (String)map.get("strategyName");
      String roleGroup = (String)map.get("roleGroup");
      String remarks = (String)map.get("remarks");
      String state = (String)map.get("state");
      String projectid = (String)map.get("projectId");
      String username = TokenUtil.getUserId(request.getHeader("token"));
      String finalStrategyId = strategyId;
      ((Map)map.get("map")).forEach((k, v) -> {
         String[] split = k.toString().split("\\.");
         String schemaname = split[0];
         String tablename = split[1];
         String fieldname = split[2];
         List<String> desensitizationStrategyList = new ArrayList();
         String dataSystemid = (String)((Map)v).get("dataSystemid");
         desensitizationStrategyList.add(dataSystemid);
         desensitizationStrategyList.add(fieldname);
         desensitizationStrategyList.add(tablename);
         desensitizationStrategyList.add(schemaname);
         String dataareaid = (String)((Map)v).get("dataareaid");
         String dataareaname = (String)((Map)v).get("dataareaname");
         String ruleid = (String)((Map)v).get("ruleid");
         if (ruleid == null || ruleid.equals("")) {
            ruleid = (String)((Map)v).get("ruleId");
         }

         String rulename = (String)((Map)v).get("rulename");
         desensitizationStrategyList.add(state);
         desensitizationStrategyList.add(projectid);
         desensitizationStrategyList.add(username);
         desensitizationStrategyList.add(dataareaid);
         desensitizationStrategyList.add(dataareaname);
         desensitizationStrategyList.add(ruleid);
         desensitizationStrategyList.add(rulename);
         desensitizationStrategyList.add(finalStrategyId);
         desensitizationStrategyList.add(strategyName);
         desensitizationStrategyList.add(roleGroup);
         desensitizationStrategyList.add(remarks);

         try {
            this.desensitizationStrategyService.saveDesensitizationStrategyDel(desensitizationStrategyList);
         } catch (Exception e) {
            e.printStackTrace();
         }

      });
      List<TCoreDesensitizationStrategy> desensitStrategyList = this.desensitizationStrategyDao.queryAll(new Criterion[]{Restrictions.eq("strategyid", strategyId)});
      int y = desensitStrategyList.size();
      Date createtime = new Date();
      if (y > 0) {
         for(int i = 0; i < y; ++i) {
            createtime = ((TCoreDesensitizationStrategy)desensitStrategyList.get(0)).getCreatetime();
         }
      }

      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      String createtimeString = sdf.format(createtime);
      String finalStrategyId1 = strategyId;
      ((Map)map.get("map")).forEach((k, v) -> {
         String[] split = k.toString().split("\\.");
         String schemaname = split[0];
         String tablename = split[1];
         String fieldname = split[2];
         List<String> desensitizationStrategyList = new ArrayList();
         String dataSystemid = (String)((Map)v).get("dataSystemid");
         desensitizationStrategyList.add(dataSystemid);
         desensitizationStrategyList.add(fieldname);
         desensitizationStrategyList.add(tablename);
         desensitizationStrategyList.add(schemaname);
         String dataareaid = (String)((Map)v).get("dataareaid");
         String dataareaname = (String)((Map)v).get("dataareaname");
         String ruleid = (String)((Map)v).get("ruleid");
         if (ruleid == null || ruleid.equals("")) {
            ruleid = (String)((Map)v).get("ruleId");
         }

         String rulename = (String)((Map)v).get("rulename");
         desensitizationStrategyList.add(state);
         desensitizationStrategyList.add(projectid);
         desensitizationStrategyList.add(username);
         desensitizationStrategyList.add(dataareaid);
         desensitizationStrategyList.add(dataareaname);
         desensitizationStrategyList.add(ruleid);
         desensitizationStrategyList.add(rulename);
         desensitizationStrategyList.add(finalStrategyId1);
         desensitizationStrategyList.add(strategyName);
         desensitizationStrategyList.add(roleGroup);
         desensitizationStrategyList.add(remarks);
         desensitizationStrategyList.add(createtimeString);

         try {
            this.desensitizationStrategyService.saveDesensitizationStrategy(desensitizationStrategyList);
         } catch (Exception e) {
            e.printStackTrace();
         }

      });
      this.encryptionProxyService.noticeProxyFetchEngineAndMaskingInfosByProject(projectid);
      ThreadUtil.sleep(2000L);
      return RespHelper.<String>successResp();
   }

   @RequestMapping({"/loadDesensitizationStrategy"})
   @ResponseBody
   public Response loadDesensitizationStrategy(@RequestBody TCoreDesensitizationStrategyVO tCoreDesensitizationStrategyVO) throws Exception {
      String projectId = tCoreDesensitizationStrategyVO.getProjectid();
      String strategyName = tCoreDesensitizationStrategyVO.getStrategyName();
      String remarks = tCoreDesensitizationStrategyVO.getRemarks();
      String roleGroup = tCoreDesensitizationStrategyVO.getRoleGroup();
      String state = tCoreDesensitizationStrategyVO.getState();
      new ArrayList();
      PageInfo pageInfo = new PageInfo();
      List<TCoreDesensitizationStrategy> tcoreJiaMiDulist = new ArrayList();
      if (projectId != null && !projectId.trim().equals("")) {
         Integer page = tCoreDesensitizationStrategyVO.getPageno();
         Integer rows = tCoreDesensitizationStrategyVO.getPagesize();
         pageInfo.setPageno(page);
         pageInfo.setPagesize(rows);
         tcoreJiaMiDulist = this.desensitizationStrategyService.queryDesenStrategylist(projectId, strategyName, remarks, roleGroup, state);
         int tt = tcoreJiaMiDulist.size();
         if (tt > 0) {
            for(int w = 0; w < tt; ++w) {
               if (null != ((TCoreDesensitizationStrategy)tcoreJiaMiDulist.get(w)).getRolegroup()) {
                  String roleGroupList = ((TCoreDesensitizationStrategy)tcoreJiaMiDulist.get(w)).getRolegroup();
                  if (roleGroupList.trim().equals("")) {
                     Criterion croleid = Restrictions.ne("id", "1");
                     List<TBaseRole> tBaseRolelist = this.tBaseRoleDao.queryAll(new Criterion[]{croleid});
                     StringBuffer roleGroupSB = new StringBuffer();
                     int tB = tBaseRolelist.size();
                     if (tB > 0) {
                        for(int t = 0; t < tB; ++t) {
                           String rolename = ((TBaseRole)tBaseRolelist.get(t)).getRolename();
                           if (StringUtils.hasText(rolename)) {
                              roleGroupSB.append(rolename).append(",");
                           }
                        }
                     }

                     String roleGroup1 = roleGroupSB.toString().substring(0, roleGroupSB.lastIndexOf(","));
                     ((TCoreDesensitizationStrategy)tcoreJiaMiDulist.get(w)).setRolegroup("全部");
                  }
               }
            }
         }
      }

      List<TCoreDesensitizationStrategy> tmp = new ArrayList();

      for(int i = 0; i < tcoreJiaMiDulist.size(); ++i) {
         boolean flag = false;

         for(int j = 0; j < tmp.size(); ++j) {
            if (((TCoreDesensitizationStrategy)tmp.get(j)).getStrategyname().equals(((TCoreDesensitizationStrategy)tcoreJiaMiDulist.get(i)).getStrategyname())) {
               flag = true;
               break;
            }
         }

         if (!flag) {
            tmp.add(tcoreJiaMiDulist.get(i));
         }
      }

      List<TCoreDesensitizationStrategy> desensitizationStrategyList = getPageLimit(tmp, tCoreDesensitizationStrategyVO.getPageno(), tCoreDesensitizationStrategyVO.getPagesize());
      pageInfo.setCount((long)tmp.size());
      List<TCoreDesensitizationStrategyVO> desensitizationStrategyListVo = this.stransfer2Vos(desensitizationStrategyList);
      return RespHelper.updateResp(pageInfo, desensitizationStrategyListVo);
   }

   private List<TCoreDesensitizationStrategyVO> stransfer2Vos(List<TCoreDesensitizationStrategy> desensitizationStrategyList) {
      List<TCoreDesensitizationStrategyVO> desensitizationStrategyListVo = new ArrayList();

      for(TCoreDesensitizationStrategy strategy : desensitizationStrategyList) {
         TCoreDesensitizationStrategyVO vo = this.stransfer2Vo(strategy);
         desensitizationStrategyListVo.add(vo);
      }

      return desensitizationStrategyListVo;
   }

   private TCoreDesensitizationStrategyVO stransfer2Vo(TCoreDesensitizationStrategy strategy) {
      TCoreDesensitizationStrategyVO vo = new TCoreDesensitizationStrategyVO();
      BeanUtils.copyProperties(strategy, vo);
      vo.setStrategyName(strategy.getStrategyname());
      vo.setRoleGroup(strategy.getRolegroup());
      vo.setStrategyId(strategy.getStrategyid());
      return vo;
   }

   @RequestMapping({"/desensitizationStrategyDetails"})
   @ResponseBody
   public Response desensitizationStrategyDetails(@RequestBody TCoreDesensitizationStrategyVO tCoreDesensitizationStrategyVO) throws Exception {
      String projectId = tCoreDesensitizationStrategyVO.getProjectid();
      String strategyId = tCoreDesensitizationStrategyVO.getStrategyId();
      List<TCoreDesensitizationStrategy> tcoreJiaMiDulist = new ArrayList();
      if (null != projectId && !projectId.trim().equals("") && null != strategyId && !strategyId.trim().equals("")) {
         tcoreJiaMiDulist = this.desensitizationStrategyService.queryDesenStrategyDetails(projectId, strategyId);
      }

      List<TCoreDesensitizationStrategyVO> desensitizationStrategyListVo = this.stransfer2Vos(tcoreJiaMiDulist);
      return RespHelper.successResp(desensitizationStrategyListVo);
   }

   @RequestMapping({"/updateRoleGroup"})
   @ResponseBody
   public Response updateRoleGroup(@RequestBody TCoreDesensitizationStrategyVO tCoreDesensitizationStrategyVO) throws Exception {
      String projectId = tCoreDesensitizationStrategyVO.getProjectid();
      String strategyId = tCoreDesensitizationStrategyVO.getStrategyId();
      String roleGroup = tCoreDesensitizationStrategyVO.getRoleGroup();
      new ArrayList();
      if (null != projectId && !projectId.trim().equals("") && null != strategyId && !strategyId.trim().equals("")) {
         List<TCoreDesensitizationStrategy> tcoreJiaMiDulist = this.desensitizationStrategyService.queryDesenStrategyDetails(projectId, strategyId);
         if (null != roleGroup) {
            this.desensitizationStrategyService.updateRoleGroup(tcoreJiaMiDulist, roleGroup);
         }
      }

      return RespHelper.successResp();
   }

   @RequestMapping({"/remove"})
   @ResponseBody
   public Response remove(@RequestBody TCoreDesensitizationStrategyVO tCoreDesensitizationStrategyVO) throws Exception {
      String projectId = tCoreDesensitizationStrategyVO.getProjectid();
      String strategyId = tCoreDesensitizationStrategyVO.getStrategyId();
      List<TCoreDesensitizationStrategy> tcoreJiaMiDulist = new ArrayList();
      if (null != projectId && !projectId.trim().equals("") && null != strategyId && !strategyId.trim().equals("")) {
         tcoreJiaMiDulist = this.desensitizationStrategyService.queryDesenStrategyDetails(projectId, strategyId);
         this.desensitizationStrategyService.remove(tcoreJiaMiDulist);
      }

      ServletRequestAttributes attributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
      String username = "";
      if (!ObjectUtils.isEmpty(attributes)) {
         HttpServletRequest request = attributes.getRequest();
         if (!ObjectUtils.isEmpty(request) && !ObjectUtils.isEmpty(request.getHeader("token"))) {
            username = TokenUtil.getUserId(request.getHeader("token"));
         }
      }

      int cpp = tcoreJiaMiDulist.size();
      TCoreDesensitizationStrategy tCoreDesensitizationStrategy = (TCoreDesensitizationStrategy)tcoreJiaMiDulist.get(0);
      if (null != tCoreDesensitizationStrategy) {
         TCoreDesensitizationStrategyLog encryptionLog = new TCoreDesensitizationStrategyLog();
         encryptionLog.setOperModule("脱敏策略管理");
         encryptionLog.setProjectId(projectId);
         encryptionLog.setDataSystemId(tCoreDesensitizationStrategy.getDataareaid());
         encryptionLog.setStrategyName(tCoreDesensitizationStrategy.getStrategyname());
         encryptionLog.setSchemaName(tCoreDesensitizationStrategy.getTschemas());
         encryptionLog.setTableName(tCoreDesensitizationStrategy.getNames());
         encryptionLog.setFieldName(tCoreDesensitizationStrategy.getTable_field_id());
         encryptionLog.setCode("DDM_010010");
         encryptionLog.setOperationMassage("用户[" + username + "]对策略[" + tCoreDesensitizationStrategy.getStrategyname() + "]执行了删除操作;");
         encryptionLog.setId(UUID.randomUUID().toString().replace("-", ""));
         encryptionLog.setCreatetime(new Date());
         encryptionLog.setCreateuser(username);
         String column_enc = "";
         Date date = encryptionLog.getCreatetime();
         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
         String dateString = sdf.format(date);

         try {
            column_enc = SM3Utils.encrypt(encryptionLog.getCreateuser() + dateString + encryptionLog.getOperationMassage());
         } catch (Exception exception) {
            exception.printStackTrace();
         }

         encryptionLog.setColumn_enc(column_enc);
         this.tCoreDesensitizationStrategyLogDao.save(encryptionLog);
      }

      return RespHelper.successResp();
   }

   @RequestMapping({"/disableOrEnable"})
   @ResponseBody
   public Response disableOrEnable(@RequestBody TCoreDesensitizationStrategyVO tCoreDesensitizationStrategyVO) throws Exception {
      String projectId = tCoreDesensitizationStrategyVO.getProjectid();
      String strategyId = tCoreDesensitizationStrategyVO.getStrategyId();
      String state = tCoreDesensitizationStrategyVO.getState();
      new ArrayList();
      if (null != projectId && !projectId.trim().equals("") && null != strategyId && !strategyId.trim().equals("")) {
         List<TCoreDesensitizationStrategy> tcoreJiaMiDulist = this.desensitizationStrategyService.queryDesenStrategyDetails(projectId, strategyId);
         if (null != state) {
            this.desensitizationStrategyService.disableOrEnable(tcoreJiaMiDulist, state);
         }
      }

      this.encryptionProxyService.noticeProxyFetchEngineAndMaskingInfosByProject(projectId);

      for(TCoreClientInfo client : JarClientUtil.clientInfoDao().queryJarClientsByProject(projectId)) {
         client.setLast_opt_time("1970-01-01 00:00:00");
         JarClientUtil.saveClientInfo(client);
      }

      return RespHelper.successResp();
   }

   public static List getPageLimit(List dataList, int pageNum, int pageSize) {
      if (CollectionUtils.isEmpty(dataList)) {
         return dataList;
      } else {
         List resultList = new ArrayList();
         int currIdx = pageNum > 1 ? (pageNum - 1) * pageSize : 0;

         for(int i = 0; i < pageSize && i < dataList.size() - currIdx; ++i) {
            resultList.add(dataList.get(currIdx + i));
         }

         return resultList;
      }
   }

   @RequestMapping({"/checkRepeatName"})
   @ResponseBody
   public Response checkRepeatName(@RequestBody Map<String, String> map, HttpServletRequest request, HttpServletResponse response, Model model) {
      String strategyname = (String)map.get("strategyname");
      String id = map.get("id") != null ? (String)map.get("id") : "";
      String projectid = (String)map.get("projectid");
      int count = this.desensitizationStrategyService.checkRepeatName(strategyname, id, projectid);
      return count == 0 ? RespHelper.successResp(true) : RespHelper.createResp(false, "500", "该脱敏策略名称已存在");
   }
}
