package com.chenyang.nse.bussiness.aop;

import com.chenyang.nse.bussiness.dao.table.core.dataproject.TCoreDataProjectDao;
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.entity.orm.table.core.dataproject.TCoreDataProject;
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.tools.encryption.SM3Utils;
import com.chenyang.nse.bussiness.tools.msg.MesUtil;
import com.chenyang.nse.bussiness.tools.token.TokenUtil;
import com.jcabi.aspects.Async;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.thymeleaf.util.StringUtils;

@Aspect
@Component
public class DesensitizationStrategyAspect {
   @Autowired
   TCoreDesensitizationStrategyLogDao tCoreDesensitizationStrategyLogDao;
   @Autowired
   DesensitizationStrategyDao desensitizationStrategyDao;
   @Autowired
   TCoreDataProjectDao tCoreDataProjectDao;

   @Pointcut("execution(public * com.chenyang.nse.bussiness.controller.core.DesensitizationStrategyController.save(..))")
   public void saveDesensitizationStrategyPointCut() {
   }

   private Method getMethod(JoinPoint joinPoint) {
      Signature signature = joinPoint.getSignature();
      MethodSignature methodSignature = (MethodSignature)signature;
      Method method = methodSignature.getMethod();
      return method != null ? method : null;
   }

   @Before("saveDesensitizationStrategyPointCut()")
   public void beforeDo(JoinPoint joinPoint) throws Exception {
      this.saveDesensitizationStrategyLog(joinPoint);
   }

   @Async
   private void saveDesensitizationStrategyLog(final JoinPoint joinPoint) throws Exception {
      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"));
         } else {
             username = null;
         }
      } else {
          username = null;
      }

       Object[] args = joinPoint.getArgs();
      if (null != args && args.length != 0 && !ObjectUtils.isEmpty(args[0])) {
         String finalDecoValue = "项目管理-脱敏策略";
         Map<String, Object> map = (Map)args[0];
         String projectid = (String)map.get("projectId");
         String strategyName = (String)map.get("strategyName");
         if (StringUtils.isEmpty((String)map.get("roleGroup"))) {
            String var10000 = "全部";
         } else {
            String var17 = (String)map.get("roleGroup");
         }

         String state = (String)map.get("state");
         String strategyId = (String)map.get("strategyId");
         TCoreDesensitizationStrategyLog tCoreDesensitizationStrategyLog = new TCoreDesensitizationStrategyLog();
         tCoreDesensitizationStrategyLog.setOperModule(finalDecoValue);
         tCoreDesensitizationStrategyLog.setProjectId(projectid);
         tCoreDesensitizationStrategyLog.setCreatetime(new Date());
         if (null != strategyId && !"".equals(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];
               String dataSystemid = (String)((Map)v).get("dataSystemid");
               String dataareaid = (String)((Map)v).get("dataareaid");
               String ruleid = (String)((Map)v).get("ruleid");
               tCoreDesensitizationStrategyLog.setSchemaName(schemaname);
               tCoreDesensitizationStrategyLog.setTableName(tablename);
               tCoreDesensitizationStrategyLog.setFieldName(fieldname);
               tCoreDesensitizationStrategyLog.setStrategyName(strategyName);
               tCoreDesensitizationStrategyLog.setDataSystemId(dataSystemid);
               tCoreDesensitizationStrategyLog.setDataareaid(dataareaid);
               tCoreDesensitizationStrategyLog.setRuleid(ruleid);
               tCoreDesensitizationStrategyLog.setCreateuser(username);
               tCoreDesensitizationStrategyLog.setState(state);
               String code = "DDM_02402";
               tCoreDesensitizationStrategyLog.setCode(code);
               tCoreDesensitizationStrategyLog.setOperationMassage(MesUtil.getMsg(code, new String[]{username, strategyName}));
               String column_enc = "";
               Date date = tCoreDesensitizationStrategyLog.getCreatetime();
               SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
               String dateString = sdf.format(date);

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

               tCoreDesensitizationStrategyLog.setColumn_enc(column_enc);
               this.tCoreDesensitizationStrategyLogDao.save(tCoreDesensitizationStrategyLog);
            });
         } else {
            UUID strategUuid = UUID.randomUUID();
            strategyId = strategUuid.toString().replace("-", "");
            ((Map)map.get("map")).forEach((k, v) -> {
               String[] split = k.toString().split("\\.");
               String schemaname = split[0];
               String tablename = split[1];
               String fieldname = split[2];
               String dataSystemid = (String)((Map)v).get("dataSystemid");
               String dataareaid = (String)((Map)v).get("dataareaid");
               String ruleid = (String)((Map)v).get("ruleid");
               tCoreDesensitizationStrategyLog.setSchemaName(schemaname);
               tCoreDesensitizationStrategyLog.setTableName(tablename);
               tCoreDesensitizationStrategyLog.setFieldName(fieldname);
               tCoreDesensitizationStrategyLog.setStrategyName(strategyName);
               tCoreDesensitizationStrategyLog.setDataSystemId(dataSystemid);
               tCoreDesensitizationStrategyLog.setDataareaid(dataareaid);
               tCoreDesensitizationStrategyLog.setRuleid(ruleid);
               tCoreDesensitizationStrategyLog.setCreateuser(username);
               tCoreDesensitizationStrategyLog.setState(state);
               String code = "DDM_02401";
               tCoreDesensitizationStrategyLog.setCode(code);
               tCoreDesensitizationStrategyLog.setOperationMassage(MesUtil.getMsg(code, new String[]{username, strategyName}));
               String column_enc = "";
               Date date = tCoreDesensitizationStrategyLog.getCreatetime();
               SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
               String dateString = sdf.format(date);

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

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

   }

   @Pointcut("execution(public * com.chenyang.nse.bussiness.controller.core.DesensitizationStrategyController.updateRoleGroup(..))")
   private void updateRoleGroupPointCut() {
   }

   @Pointcut("execution(public * com.chenyang.nse.bussiness.controller.core.DesensitizationStrategyController.disableOrEnable(..))")
   public void disableOrEnablePointcut() {
   }

   @Before("disableOrEnablePointcut()")
   private void beforeDisableOrEnable(JoinPoint joinPoint) throws Exception {
      this.disableOrEnableLog(joinPoint);
   }

   @Async
   private void disableOrEnableLog(final JoinPoint joinPoint) throws Exception {
      ServletRequestAttributes attributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
      String username = null;
      if (!ObjectUtils.isEmpty(attributes)) {
         HttpServletRequest request = attributes.getRequest();
         if (!ObjectUtils.isEmpty(request) && !ObjectUtils.isEmpty(request.getHeader("token"))) {
            username = TokenUtil.getUserId(request.getHeader("token"));
         }
      }

      Object[] args = joinPoint.getArgs();
      if (null != args && args.length != 0 && !ObjectUtils.isEmpty(args[0])) {
         String finalDecoValue = "项目管理-脱敏策略";
         TCoreDesensitizationStrategyVO tCoreDesensitizationStrategyVO = (TCoreDesensitizationStrategyVO)args[0];
         String projectId = tCoreDesensitizationStrategyVO.getProjectid();
         String strategyId = tCoreDesensitizationStrategyVO.getStrategyId();
         String state = tCoreDesensitizationStrategyVO.getState();
         List<TCoreDesensitizationStrategy> tCoreDesensitizationStrategies = this.desensitizationStrategyDao.queryDesenStrategyDetails(projectId, strategyId);
         TCoreDesensitizationStrategy tCoreDesensitizationStrategy = (TCoreDesensitizationStrategy)tCoreDesensitizationStrategies.get(0);
         TCoreDesensitizationStrategyLog tCoreDesensitizationStrategyLog = new TCoreDesensitizationStrategyLog();
         String strategyName = tCoreDesensitizationStrategy.getStrategyname();
         tCoreDesensitizationStrategyLog.setOperModule(finalDecoValue);
         tCoreDesensitizationStrategyLog.setSchemaName(tCoreDesensitizationStrategy.getTschemas());
         tCoreDesensitizationStrategyLog.setDataareaid(tCoreDesensitizationStrategy.getDataareaid());
         tCoreDesensitizationStrategyLog.setTableName(tCoreDesensitizationStrategy.getTable_field_id());
         tCoreDesensitizationStrategyLog.setProjectId(projectId);
         tCoreDesensitizationStrategyLog.setStrategyName(strategyName);
         tCoreDesensitizationStrategyLog.setState(state);
         tCoreDesensitizationStrategyLog.setCreatetime(new Date());
         tCoreDesensitizationStrategyLog.setCreateuser(username);
         tCoreDesensitizationStrategyLog.setRuleid(tCoreDesensitizationStrategy.getRuleid());
         tCoreDesensitizationStrategyLog.setDataSystemId(tCoreDesensitizationStrategy.getDatasystem_id());
         String column_enc = "";
         Date date = tCoreDesensitizationStrategyLog.getCreatetime();
         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
         String dateString = sdf.format(date);
         if ("0".equals(state)) {
            String code = "DDM_02404";
            tCoreDesensitizationStrategyLog.setCode(code);
            tCoreDesensitizationStrategyLog.setOperationMassage(MesUtil.getMsg(code, new String[]{username, strategyName}));

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

            tCoreDesensitizationStrategyLog.setColumn_enc(column_enc);
            this.tCoreDesensitizationStrategyLogDao.save(tCoreDesensitizationStrategyLog);
         } else if ("1".equals(state)) {
            String code = "DDM_02405";
            tCoreDesensitizationStrategyLog.setCode(code);
            tCoreDesensitizationStrategyLog.setOperationMassage(MesUtil.getMsg(code, new String[]{username, strategyName}));

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

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

   }

   @Pointcut("execution(public * com.chenyang.nse.bussiness.controller.core.EncryptionConfigController.download(..))")
   public void downloadPointcut() {
   }

   @AfterReturning("downloadPointcut()")
   private void afterDownload(JoinPoint joinPoint) throws Exception {
      this.downloadLog(joinPoint);
   }

   @Async
   private void downloadLog(final JoinPoint joinPoint) throws Exception {
      ServletRequestAttributes attributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
      String username = null;
      if (!ObjectUtils.isEmpty(attributes)) {
         HttpServletRequest request = attributes.getRequest();
         if (!ObjectUtils.isEmpty(request) && !ObjectUtils.isEmpty(request.getHeader("token"))) {
            username = TokenUtil.getUserId(request.getHeader("token"));
         }
      }

      Object[] args = joinPoint.getArgs();
      if (null != args && args.length != 0 && !ObjectUtils.isEmpty(args[0]) && !ObjectUtils.isEmpty(args[1])) {
         String finalDecoValue = "项目管理-脱敏策略";
         String projectId = (String)args[0];
         String project = ((TCoreDataProject)this.tCoreDataProjectDao.get(projectId)).getProject();
         String finalUsername = (String)args[1];
         TCoreDesensitizationStrategyLog tCoreDesensitizationStrategyLog = new TCoreDesensitizationStrategyLog();
         String code = "DDM_02406";
         tCoreDesensitizationStrategyLog.setCode(code);
         tCoreDesensitizationStrategyLog.setOperationMassage(MesUtil.getMsg(code, new String[]{finalUsername, project}));
         tCoreDesensitizationStrategyLog.setOperModule(finalDecoValue);
         tCoreDesensitizationStrategyLog.setProjectId(projectId);
         tCoreDesensitizationStrategyLog.setCreatetime(new Date());
         tCoreDesensitizationStrategyLog.setCreateuser(username);
         String column_enc = "";
         Date date = tCoreDesensitizationStrategyLog.getCreatetime();
         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
         String dateString = sdf.format(date);

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

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

   }
}
