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.entity.orm.table.core.api.ApiInfoLog;
import com.chenyang.nse.bussiness.entity.orm.table.core.discovery.TcoreDiscoveryResult;
import com.chenyang.nse.bussiness.entity.orm.table.core.discovery.TcoreDiscoveryTask;
import com.chenyang.nse.bussiness.entity.vo.DiscoveryResultVO;
import com.chenyang.nse.bussiness.service.core.TdataDiscoveryResultService;
import com.chenyang.nse.bussiness.service.core.TdataDiscoveryService;
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.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/tt"})
public class TdataDiscoveryAPIController {
   @Autowired
   private TdataDiscoveryService tdataDiscoveryService;
   @Autowired
   private TdataDiscoveryResultService tdataDiscoveryResultService;
   @Autowired
   private ApiInfoLogService apiInfoLogService;
   @Autowired
   private RedisService redisService;

   @ResponseBody
   @RequestMapping(
      value = {"/pd/{projectid}/td/{taskid}/sa/{schema}/te/{tablename}", "/pd/{projectid}/td/{taskid}/sa/{schema}", "/pd/{projectid}/td/{taskid}"},
      method = {RequestMethod.POST},
      produces = {"text/json;charset=UTF-8"}
   )
   public String postDiscoveryResulttablename(@PathVariable("projectid") String projectid, @PathVariable("taskid") String taskid, @PathVariable(value = "schema",required = false) String schema, @PathVariable(value = "tablename",required = false) String tablename, HttpServletRequest request) {
      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();
      boolean flag = TokenUtil.verify(token);
      if (flag) {
         Map<String, String> rvMap = AuthorizationTool.releaseVerification(reqUrl);
         if ("0".equals(rvMap.get("code"))) {
            TcoreDiscoveryTask tcoreDiscoveryTask = this.tdataDiscoveryService.queryTaskByid(taskid);
            if (null == tcoreDiscoveryTask) {
               result.put("code", ResultAPIEnum.RT_ERROR_CODE_403_STR.getCode());
               result.put("msg", ResultAPIEnum.RT_ERROR_CODE_403_STR.getMsg());
            } else {
               String resultTableName = tcoreDiscoveryTask.getResultid();
               DiscoveryResultVO obj = new DiscoveryResultVO();
               obj.setTablename(resultTableName);
               obj.setNschema(schema);
               obj.setNtable(tablename);
               List<TcoreDiscoveryResult> list = this.tdataDiscoveryResultService.selectApiDiscoveryResult(obj);
               if (null != list && list.size() != 0) {
                  List<Map<String, Object>> tdResultMapList = ApiTool.objectsToMaps(list);
                  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());
               }
            }
         } else {
            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("1");
      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 = {"/pd/{projectid}/td/{taskid}/sa/{schema}/te/{tablename}/test", "/pd/{projectid}/td/{taskid}/sa/{schema}/test", "/pd/{projectid}/td/{taskid}/test"},
      method = {RequestMethod.POST},
      produces = {"text/json;charset=UTF-8"}
   )
   public String postDiscoveryResulttablenameTest(@PathVariable("projectid") String projectid, @PathVariable("taskid") String taskid, @PathVariable(value = "schema",required = false) String schema, @PathVariable(value = "tablename",required = false) String tablename, HttpServletRequest request) {
      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");
      if (TokenUtil.verify(token)) {
         TcoreDiscoveryTask tcoreDiscoveryTask = this.tdataDiscoveryService.queryTaskByid(taskid);
         if (null == tcoreDiscoveryTask) {
            result.put("code", ResultAPIEnum.RT_ERROR_CODE_403_STR.getCode());
            result.put("msg", ResultAPIEnum.RT_ERROR_CODE_403_STR.getMsg());
         } else {
            String resultTableName = tcoreDiscoveryTask.getResultid();
            DiscoveryResultVO obj = new DiscoveryResultVO();
            obj.setTablename(resultTableName);
            obj.setNschema(schema);
            obj.setNtable(tablename);
            List<TcoreDiscoveryResult> list = this.tdataDiscoveryResultService.selectApiDiscoveryResult(obj);
            if (null != list && list.size() != 0) {
               List<TcoreDiscoveryResult> list1 = new ArrayList();
               list1.add(list.get(0));
               List<Map<String, Object>> tdResultMapList = ApiTool.objectsToMaps(list1);
               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());
            }
         }
      } 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 = {"/pd/{projectid}/td/{taskid}/sa/{schema}/te/{tablename}", "/pd/{projectid}/td/{taskid}/sa/{schema}", "/pd/{projectid}/td/{taskid}"},
      method = {RequestMethod.GET},
      produces = {"text/json;charset=UTF-8"}
   )
   public String getDiscoveryResulttablename(@PathVariable("projectid") String projectid, @PathVariable("taskid") String taskid, @PathVariable(value = "schema",required = false) String schema, @PathVariable(value = "tablename",required = false) String tablename, HttpServletRequest request, HttpServletResponse response) {
      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)) {
         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, String> rvMap = AuthorizationTool.releaseVerification(reqUrl);
         if ("0".equals(rvMap.get("code"))) {
            TcoreDiscoveryTask tcoreDiscoveryTask = this.tdataDiscoveryService.queryTaskByid(taskid);
            if (null == tcoreDiscoveryTask) {
               result.put("code", ResultAPIEnum.RT_ERROR_CODE_403_STR.getCode());
               result.put("msg", ResultAPIEnum.RT_ERROR_CODE_403_STR.getMsg());
            } else {
               String resultTableName = tcoreDiscoveryTask.getResultid();
               DiscoveryResultVO obj = new DiscoveryResultVO();
               obj.setTablename(resultTableName);
               obj.setNschema(schema);
               obj.setNtable(tablename);
               List<TcoreDiscoveryResult> list = this.tdataDiscoveryResultService.selectApiDiscoveryResult(obj);
               if (null != list && list.size() != 0) {
                  List<Map<String, Object>> tdResultMapList = ApiTool.objectsToMaps(list);
                  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());
               }
            }
         } 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("1");
         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;
      }
   }
}
