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

import com.alibaba.fastjson.JSONObject;
import com.chenyang.nse.bussiness.controller.restfulapi.entity.ResultAPIEnum;
import com.chenyang.nse.bussiness.controller.restfulapi.tools.ApiTool;
import com.chenyang.nse.bussiness.controller.restfulapi.tools.AuthorizationTool;
import com.chenyang.nse.bussiness.engine.ghca.webservice.DesensitizationEngineInterfaceImpl;
import com.chenyang.nse.bussiness.engine.ghca.webservice.DesensitizationEngineInterfaceImplService;
import com.chenyang.nse.bussiness.entity.orm.table.core.api.ApiInfoLog;
import com.chenyang.nse.bussiness.service.core.api.ApiInfoLogService;
import com.chenyang.nse.bussiness.service.redis.RedisService;
import com.chenyang.nse.bussiness.tools.token.TokenUtil;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping({"/api/dg"})
public class DataMaskingAPIController {
   @Autowired
   private ApiInfoLogService apiInfoLogService;
   @Autowired
   private RedisService redisService;

   @ResponseBody
   @RequestMapping(
      value = {"/re/{rulename}/dr/{dataVar}"},
      method = {RequestMethod.POST},
      produces = {"text/json;charset=UTF-8"}
   )
   public String postDataMasking(@PathVariable("rulename") String rulename, @PathVariable("dataVar") Object dataVar, HttpServletRequest request) {
      label58: {
         Map<String, Object> result = new HashMap();
         result.put("code", ResultAPIEnum.RT_SUC_CODE_200_STR.getCode());
         result.put("msg", ResultAPIEnum.RT_SUC_CODE_200_STR.getMsg());
         String token = request.getHeader("token");
         String cilentip = request.getRemoteAddr();
         String reqUrl = "http://" + request.getServerName() + ":" + request.getServerPort() + request.getRequestURI();
         if (!TokenUtil.verify(token)) {
            String reqUrlsubStr = reqUrl.substring(0, reqUrl.lastIndexOf("/dr"));
            Map<String, String> rvMap = AuthorizationTool.releaseVerification(reqUrlsubStr, "3");
            if ("0".equals(rvMap.get("code"))) {
               try {
                  DesensitizationEngineInterfaceImplService engineInterfaceImplService = new DesensitizationEngineInterfaceImplService();
                  DesensitizationEngineInterfaceImpl engineInterfaceImpl = (DesensitizationEngineInterfaceImpl)engineInterfaceImplService.getPort(DesensitizationEngineInterfaceImpl.class);
                  List<Object> dataList = new ArrayList();
                  dataList.add(dataVar);
                  List<Object> reList = engineInterfaceImpl.dataMaskingListByRuleName(rulename, dataList);
                  if (null != reList && reList.size() != 0) {
                     List<Map<String, Object>> tdResultMapList = ApiTool.realObjectsToMaps(reList);
                     result.put("data", tdResultMapList);
                  }

                  result.put("code", ResultAPIEnum.RT_ERROR_CODE_403_STR.getCode());
                  result.put("msg", ResultAPIEnum.RT_ERROR_CODE_403_STR.getMsg());
               } catch (Exception e) {
                  System.out.println(">>>>>>>>调用脱敏引擎dataMaskingListByRuleName方法出错..");
                  result.put("code", ResultAPIEnum.RT_ERROR_CODE_432_STR.getCode());
                  result.put("msg", ResultAPIEnum.RT_ERROR_CODE_432_STR.getMsg());
                  e.printStackTrace();
               } finally {
                  String message = JSONObject.toJSONString(result);
                  ApiInfoLog info = new ApiInfoLog();
                  info.setApitype("3");
                  info.setAuthorization(token);
                  info.setUsername(TokenUtil.getUserId(token));
                  info.setCalldatetime(new Date());
                  info.setCreatetime(new Date());
                  info.setRestatus(String.valueOf(result.get("code")));
                  info.setRemsg(String.valueOf(result.get("msg")));
                  info.setUrl(reqUrl);
                  info.setCilentip(cilentip);
                  this.apiInfoLogService.save(info);
                  System.out.println(message);
                  return message;
               }
            }

            result.put("code", ResultAPIEnum.RT_ERROR_CODE_431_STR.getCode());
            result.put("msg", rvMap.get("msg"));
         } else {
            result.put("code", ResultAPIEnum.RT_ERROR_CODE_400_STR.getCode());
            result.put("msg", "Invalid Request");
         }

         String message = JSONObject.toJSONString(result);
         ApiInfoLog info = new ApiInfoLog();
         info.setApitype("3");
         info.setAuthorization(token);
         info.setUsername(TokenUtil.getUserId(token));
         info.setCalldatetime(new Date());
         info.setCreatetime(new Date());
         info.setRestatus(String.valueOf(result.get("code")));
         info.setRemsg(String.valueOf(result.get("msg")));
         info.setUrl(reqUrl);
         info.setCilentip(cilentip);
         this.apiInfoLogService.save(info);
         System.out.println(message);
         return message;
      }
   }

   @ResponseBody
   @RequestMapping(
      value = {"/re/{rulename}/dr/{dataVar}/test"},
      method = {RequestMethod.POST},
      produces = {"text/json;charset=UTF-8"}
   )
   public String postDataMaskingTest(@PathVariable("rulename") String rulename, @PathVariable("dataVar") Object dataVar, HttpServletRequest request) {
      Map<String, Object> result = new HashMap();

      try {
         dataVar = new String(dataVar.toString().getBytes("UTF-8"), "UTF-8");
      } catch (UnsupportedEncodingException e1) {
         e1.printStackTrace();
      }

      result.put("code", ResultAPIEnum.RT_SUC_CODE_200_STR.getCode());
      result.put("msg", ResultAPIEnum.RT_SUC_CODE_200_STR.getMsg());
      String token = request.getHeader("token");
      if (TokenUtil.verify(token)) {
         try {
            DesensitizationEngineInterfaceImplService engineInterfaceImplService = new DesensitizationEngineInterfaceImplService();
            DesensitizationEngineInterfaceImpl engineInterfaceImpl = (DesensitizationEngineInterfaceImpl)engineInterfaceImplService.getPort(DesensitizationEngineInterfaceImpl.class);
            List<Object> dataList = new ArrayList();
            dataList.add(dataVar);
            List<Object> reList = engineInterfaceImpl.dataMaskingListByRuleName(rulename, dataList);
            if (null != reList && reList.size() != 0) {
               List<Map<String, Object>> tdResultMapList = ApiTool.realObjectsToMaps(reList);
               result.put("data", tdResultMapList);
            } else {
               result.put("code", ResultAPIEnum.RT_ERROR_CODE_403_STR.getCode());
               result.put("msg", ResultAPIEnum.RT_ERROR_CODE_403_STR.getMsg());
            }
         } catch (Exception e) {
            System.out.println(">>>>>>>>调用脱敏引擎dataMaskingListByRuleName方法出错..");
            result.put("code", ResultAPIEnum.RT_ERROR_CODE_432_STR.getCode());
            result.put("msg", ResultAPIEnum.RT_ERROR_CODE_432_STR.getMsg());
            e.printStackTrace();
         }
      } else {
         result.put("code", ResultAPIEnum.RT_ERROR_CODE_400_STR.getCode());
         result.put("msg", "Invalid Request");
      }

      String message = JSONObject.toJSONString(result);
      System.out.println(message);
      return message;
   }

   @ResponseBody
   @RequestMapping(
      value = {"/re/{rulename}/dr/{dataVar}"},
      method = {RequestMethod.GET},
      produces = {"text/json;charset=UTF-8"}
   )
   public String getDataMasking(@PathVariable("rulename") String rulename, @PathVariable("dataVar") Object dataVar, HttpServletRequest request, HttpServletResponse response) {
      String token = request.getHeader("token");
      String cilentip = request.getRemoteAddr();
      String reqUrl = "http://" + request.getServerName() + ":" + request.getServerPort() + request.getRequestURI();
      if (!TokenUtil.verify(token)) {
         response.setStatus(401);
         response.setHeader("WWW-Authenticate", "Basic realm=\"My Application\"");
         response.setContentType("text/html; charset=UTF-8");

         try {
            response.getWriter().print("HTTP STATUS -- 401!");
            return null;
         } catch (IOException e) {
            e.printStackTrace();
            return null;
         } finally {
            ;
         }
      } else {
         Map<String, Object> result = new HashMap();
         result.put("code", ResultAPIEnum.RT_SUC_CODE_200_STR.getCode());
         result.put("msg", ResultAPIEnum.RT_SUC_CODE_200_STR.getMsg());
         String reqUrlsubStr = reqUrl.substring(0, reqUrl.lastIndexOf("/dr"));
         Map<String, String> rvMap = AuthorizationTool.releaseVerification(reqUrlsubStr, "3");
         if ("0".equals(rvMap.get("code"))) {
            try {
               DesensitizationEngineInterfaceImplService engineInterfaceImplService = new DesensitizationEngineInterfaceImplService();
               DesensitizationEngineInterfaceImpl engineInterfaceImpl = (DesensitizationEngineInterfaceImpl)engineInterfaceImplService.getPort(DesensitizationEngineInterfaceImpl.class);
               List<Object> dataList = new ArrayList();
               dataList.add(dataVar);
               List<Object> reList = engineInterfaceImpl.dataMaskingListByRuleName(rulename, dataList);
               if (null != reList && reList.size() != 0) {
                  List<Map<String, Object>> tdResultMapList = ApiTool.realObjectsToMaps(reList);
                  result.put("data", tdResultMapList);
               } else {
                  result.put("code", ResultAPIEnum.RT_ERROR_CODE_403_STR.getCode());
                  result.put("msg", ResultAPIEnum.RT_ERROR_CODE_403_STR.getMsg());
               }
            } catch (Exception e) {
               System.out.println(">>>>>>>>调用脱敏引擎dataMaskingListByRuleName方法出错..");
               result.put("code", ResultAPIEnum.RT_ERROR_CODE_432_STR.getCode());
               result.put("msg", ResultAPIEnum.RT_ERROR_CODE_432_STR.getMsg());
               e.printStackTrace();
            } finally {
               String message = JSONObject.toJSONString(result);
               ApiInfoLog info = new ApiInfoLog();
               info.setApitype("3");
               info.setAuthorization(token);
               info.setUsername(TokenUtil.getUserId(token));
               info.setCalldatetime(new Date());
               info.setCreatetime(new Date());
               info.setRestatus(String.valueOf(result.get("code")));
               info.setRemsg(String.valueOf(result.get("msg")));
               info.setUrl(reqUrl);
               info.setCilentip(cilentip);
               this.apiInfoLogService.save(info);
               System.out.println(message);
               return message;
            }
         } else {
            result.put("code", ResultAPIEnum.RT_ERROR_CODE_431_STR.getCode());
            result.put("msg", rvMap.get("msg"));
            String message = JSONObject.toJSONString(result);
            ApiInfoLog info = new ApiInfoLog();
            info.setApitype("3");
            info.setAuthorization(token);
            info.setUsername(TokenUtil.getUserId(token));
            info.setCalldatetime(new Date());
            info.setCreatetime(new Date());
            info.setRestatus(String.valueOf(result.get("code")));
            info.setRemsg(String.valueOf(result.get("msg")));
            info.setUrl(reqUrl);
            info.setCilentip(cilentip);
            this.apiInfoLogService.save(info);
            System.out.println(message);
            return message;
         }
      }
   }
}
