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

import com.alibaba.fastjson.JSONObject;
import com.chenyang.nse.bussiness.commmon.json.RespHelper;
import com.chenyang.nse.bussiness.commmon.json.Response;
import com.chenyang.nse.bussiness.controller.restfulapi.tools.Base64Tool;
import com.chenyang.nse.bussiness.entity.cache.LoginUser;
import com.chenyang.nse.bussiness.entity.orm.table.core.TCoreDatasystem;
import com.chenyang.nse.bussiness.entity.orm.table.core.dataproject.TCoreProjectFile;
import com.chenyang.nse.bussiness.entity.orm.table.core.discovery.TcoreDiscoveryColumn;
import com.chenyang.nse.bussiness.entity.vo.ComboboxVO;
import com.chenyang.nse.bussiness.entity.vo.DBTableVO;
import com.chenyang.nse.bussiness.entity.vo.api.ApiInfoObjectVO;
import com.chenyang.nse.bussiness.service.core.DataSystemService;
import com.chenyang.nse.bussiness.service.core.TdataDiscoveryService;
import com.chenyang.nse.bussiness.tools.token.TokenUtil;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
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.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping({"/api"})
public class APIController {
   @Autowired
   private TdataDiscoveryService tdataDiscoveryService;
   @Autowired
   private DataSystemService dataSystemService;

   @RequestMapping
   public String index(HttpServletRequest request, HttpServletResponse response, Model model) {
      String ip = request.getLocalAddr();
      model.addAttribute("ip", ip);
      return "api/api";
   }

   @RequestMapping({"/viewapi"})
   public String viewapi(HttpServletRequest request, HttpServletResponse response, Model model) {
      String ip = request.getLocalAddr();
      model.addAttribute("ip", ip);
      return "api/viewapi";
   }

   @RequestMapping({"/querytaskById"})
   @ResponseBody
   public List<ComboboxVO> querytaskById(String taskid, HttpServletRequest request, HttpServletResponse response) {
      List<ComboboxVO> rtlist = new ArrayList();
      List<TCoreProjectFile> discoveryfileList = this.tdataDiscoveryService.queryDiscoveryFile(taskid);
      Set<String> schemaSet = new HashSet();
      schemaSet.add(((TCoreProjectFile)discoveryfileList.get(0)).getFilegroup());

      for(String schema : schemaSet) {
         rtlist.add(new ComboboxVO(schema, schema));
      }

      return rtlist;
   }

   @RequestMapping({"/queryfileById"})
   @ResponseBody
   public List<ComboboxVO> queryfileById(String taskid, HttpServletRequest request, HttpServletResponse response) {
      List<ComboboxVO> rtlist = new ArrayList();
      List<TCoreProjectFile> discoveryfileList = this.tdataDiscoveryService.queryDiscoveryFile(taskid);
      Set<String> schemaSet = new HashSet();

      for(int i = 0; i < discoveryfileList.size(); ++i) {
         schemaSet.add(((TCoreProjectFile)discoveryfileList.get(i)).getFilestructure());
      }

      for(String schema : schemaSet) {
         rtlist.add(new ComboboxVO(schema, schema));
      }

      return rtlist;
   }

   @RequestMapping({"/querySchemaById"})
   @ResponseBody
   public Response<List<ComboboxVO>> querySchemaById(@RequestBody Map<String, String> map, HttpServletRequest request, HttpServletResponse response) {
      List<ComboboxVO> rtlist = new ArrayList();
      String taskid = (String)map.get("taskid");
      List<TcoreDiscoveryColumn> discoveryColumnList = this.tdataDiscoveryService.queryDiscoveryColumn(taskid);
      Set<String> schemaSet = new HashSet();

      for(int i = 0; i < discoveryColumnList.size(); ++i) {
         schemaSet.add(((TcoreDiscoveryColumn)discoveryColumnList.get(i)).getTschema());
      }

      for(String schema : schemaSet) {
         rtlist.add(new ComboboxVO(schema, schema));
      }

      return RespHelper.<List<ComboboxVO>>successResp(rtlist);
   }

   @RequestMapping({"/queryTableById"})
   @ResponseBody
   public Response<List<ComboboxVO>> queryTableById(@RequestBody Map<String, String> map, HttpServletRequest request, HttpServletResponse response) {
      List<ComboboxVO> rtlist = new ArrayList();
      String taskid = (String)map.get("taskid");
      String schema = (String)map.get("schema");
      List<TcoreDiscoveryColumn> discoveryColumnList = this.tdataDiscoveryService.queryDiscoveryColumn(taskid);

      for(int i = 0; i < discoveryColumnList.size(); ++i) {
         if (schema != null && schema.equals(((TcoreDiscoveryColumn)discoveryColumnList.get(i)).getTschema())) {
            rtlist.add(new ComboboxVO(((TcoreDiscoveryColumn)discoveryColumnList.get(i)).getTablename(), ((TcoreDiscoveryColumn)discoveryColumnList.get(i)).getTablename()));
         }
      }

      return RespHelper.<List<ComboboxVO>>successResp(rtlist);
   }

   @RequestMapping({"/queryDatabaseByProjectId"})
   @ResponseBody
   public Response<List<ComboboxVO>> queryDatabaseByProjectId(@RequestBody Map<String, String> map, HttpServletRequest request, HttpServletResponse response) {
      List<ComboboxVO> rtlist = new ArrayList();
      String projectId = (String)map.get("projectId");

      for(TCoreDatasystem tCoreDatasystem : this.dataSystemService.querydatasourceds(projectId)) {
         rtlist.add(new ComboboxVO(tCoreDatasystem.getId(), tCoreDatasystem.getSysname()));
      }

      return RespHelper.<List<ComboboxVO>>successResp(rtlist);
   }

   @RequestMapping({"/queryTableBySchema"})
   @ResponseBody
   public Response<List<ComboboxVO>> queryTableBySchema(@RequestBody Map<String, String> map, HttpServletRequest request, HttpServletResponse response) {
      List<ComboboxVO> rtlist = new ArrayList();
      String dataSystemId = (String)map.get("dataSystemId");
      String schema = (String)map.get("schema");

      for(DBTableVO dBTableVO : this.dataSystemService.queryTablename(dataSystemId, schema)) {
         rtlist.add(new ComboboxVO(dBTableVO.getTablename(), dBTableVO.getTablename()));
      }

      return RespHelper.<List<ComboboxVO>>successResp(rtlist);
   }

   @RequestMapping({"/urltest"})
   @ResponseBody
   public Response<String> urltest(@RequestBody Map<String, String> map, HttpServletRequest request, HttpServletResponse response) {
      String reStr = "";
      String testurl = (String)map.get("testurl");
      String requestway = (String)map.get("requestway");
      String token = request.getHeader("token");

      try {
         reStr = load(testurl + "/test", requestway, token, (String)null);
         return RespHelper.<String>successResp(new String(reStr.getBytes()));
      } catch (Exception var12) {
         Exception e = var12;
         var12.printStackTrace();

         try {
            Map<String, Object> result = new HashMap();
            result.put("code", "404");
            result.put("msg", e.toString());
            String message = JSONObject.toJSONString(result);
            return RespHelper.<String>successResp(new String(message.getBytes(), "utf-8"));
         } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
            return null;
         }
      }
   }

   @RequestMapping({"/getAuthorization"})
   @ResponseBody
   public String getAuthorization(HttpServletRequest request, HttpServletResponse response) {
      LoginUser loginUser = (LoginUser)request.getSession().getAttribute("loginUser");
      String authorizationStr = loginUser.getTsysUser().getUsername() + ":" + loginUser.getTsysUser().getPassword();

      try {
         authorizationStr = Base64Tool.encryptBASE64(authorizationStr);
      } catch (Exception e) {
         e.printStackTrace();
      }

      return authorizationStr;
   }

   @RequestMapping({"/getUrlAndToken"})
   @ResponseBody
   public Response<Map<String, String>> getUrlAndToken(HttpServletRequest request, HttpServletResponse response, @RequestBody Map<String, String> params) {
      Map<String, String> map = new HashMap();
      String username = TokenUtil.getUserId(request.getHeader("token"));
      String password = TokenUtil.getPassword(request.getHeader("token"));
      map.put("token", TokenUtil.getNoDateToken(username, password));
      String url = "";
      String taskid = params.get("taskid") == null ? "" : (String)params.get("taskid");
      String projectid = params.get("projectid") == null ? "" : (String)params.get("projectid");
      String type = params.get("type") == null ? "" : (String)params.get("type");
      String editionid = params.get("editionid") == null ? "" : (String)params.get("editionid");
      if (type.equals("2")) {
         url = "/api/tt/pd/" + projectid + "/td/" + taskid;
      } else if (type.equals("3")) {
         if (editionid == "") {
            url = "/api/ft/se/0/pd/" + projectid + "/vn/" + taskid;
         } else {
            url = "/api/ft/se/0/pd/" + projectid + "/vn/" + editionid + "/td/" + taskid;
         }
      } else if (type.equals("4")) {
         if (editionid == "") {
            url = "/api/ft/se/2/pd/" + projectid + "/vn/" + taskid;
         } else {
            url = "/api/ft/se/2/pd/" + projectid + "/vn/" + editionid + "/td/" + taskid;
         }
      } else if (type.equals("5")) {
         if (editionid == "") {
            url = "/api/ft/se/1/pd/" + projectid + "/vn/" + taskid;
         } else {
            url = "/api/ft/se/1/pd/" + projectid + "/vn/" + editionid + "/td/" + taskid;
         }
      } else if (!type.equals("6") && !type.equals("7")) {
         if (type.equals("8")) {
            url = "/api/ay/pd/" + projectid + "/dd/" + editionid + "/td/" + taskid;
         }
      } else {
         url = "/api/ay/dd/" + taskid;
      }

      map.put("url", url);
      return RespHelper.<Map<String, String>>successResp(map);
   }

   public static String load(String url, String requestway, String validationstr, String query) throws Exception {
      url = new String(url.getBytes("UTF-8"), "UTF-8");
      URL restURL = new URL(url);
      HttpURLConnection conn = (HttpURLConnection)restURL.openConnection();
      conn.setRequestMethod(requestway.toUpperCase());
      conn.setRequestProperty("token", validationstr);
      conn.setConnectTimeout(30000);
      conn.setReadTimeout(30000);
      conn.setDoOutput(true);
      conn.setDoInput(true);
      conn.setAllowUserInteraction(true);
      PrintStream ps = new PrintStream(conn.getOutputStream());
      ps.print(query);
      ps.close();
      InputStream inputStream = conn.getInputStream();
      InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
      BufferedReader bReader = new BufferedReader(inputStreamReader);

      String line;
      String resultStr;
      for(resultStr = ""; null != (line = bReader.readLine()); resultStr = resultStr + line) {
      }

      bReader.close();
      conn.disconnect();
      return resultStr;
   }

   @RequestMapping({"/saveApiInfo"})
   @ResponseBody
   public Response<String> saveApiInfo(@RequestBody ApiInfoObjectVO apiInfoObjectVO, HttpServletRequest request, HttpServletResponse response, Model model) {
      String string = this.tdataDiscoveryService.saveApiInfo(apiInfoObjectVO);
      return RespHelper.<String>successResp(string);
   }

   @RequestMapping({"/selectApiInfo"})
   @ResponseBody
   public Response<ApiInfoObjectVO> selectApiInfo(@RequestBody Map<String, String> map, HttpServletRequest request, HttpServletResponse response, Model model) {
      String taskid = (String)map.get("taskid");
      ApiInfoObjectVO selectApiInfo = this.tdataDiscoveryService.selectApiInfo(taskid);
      return RespHelper.<ApiInfoObjectVO>successResp(selectApiInfo);
   }

   @RequestMapping({"/releaseByTreeId"})
   @ResponseBody
   public Response<String> releaseByTreeId(@RequestBody Map<String, String> map, HttpServletRequest request, HttpServletResponse response, Model model) {
      String treeid = (String)map.get("treeid");
      int count = this.tdataDiscoveryService.releaseByTreeId(treeid);
      return count == 0 ? RespHelper.successResp("未保存不能发布") : RespHelper.successResp("发布成功");
   }

   @RequestMapping({"/releaseAll"})
   @ResponseBody
   public Response<String> releaseAll(HttpServletRequest request, HttpServletResponse response, Model model) {
      int count = this.tdataDiscoveryService.releaseAll();
      return RespHelper.<String>successResp("success");
   }
}
