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.vo.datascope.FieldReportFormVO;
import com.chenyang.nse.bussiness.service.core.FieldReportFormService;
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.apache.commons.lang.StringUtils;
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/ft"})
public class FieldReportAPIController {
   @Autowired
   private FieldReportFormService fieldReportFormService;
   @Autowired
   private ApiInfoLogService apiInfoLogService;
   @Autowired
   private RedisService redisService;

   @ResponseBody
   @RequestMapping(
      value = {"/se/{setuptype}/pd/{projectid}/vn/{version}/td/{treetid}/dd/{datasystemid}/sa/{schema}/te/{tablename}", "/se/{setuptype}/pd/{projectid}/vn/{version}/td/{treetid}/dd/{datasystemid}/sa/{schema}", "/se/{setuptype}/pd/{projectid}/vn/{version}/td/{treetid}/dd/{datasystemid}", "/se/{setuptype}/pd/{projectid}/vn/{version}/td/{treetid}", "/se/{setuptype}/pd/{projectid}/vn/{version}"},
      method = {RequestMethod.POST},
      produces = {"text/json;charset=UTF-8"}
   )
   public String postDataScope(@PathVariable("setuptype") String setuptype, @PathVariable("projectid") String projectid, @PathVariable("version") String version, @PathVariable(value = "treetid",required = false) String treetid, @PathVariable(value = "datasystemid",required = false) String datasystemid, @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"))) {
            Map<String, Object> datalist = new HashMap();
            datalist.put("dataall[setuptype]", setuptype);
            datalist.put("dataall[editionid]", version);
            datalist.put("dataall[treetid]", treetid);
            datalist.put("dataall[datasystemname]", datasystemid);
            datalist.put("dataall[tschemas]", schema);
            List<String> choseTableList = new ArrayList();
            if (StringUtils.isNotBlank(tablename)) {
               String[] tableArr = tablename.split(",");

               for(int i = 0; i < tableArr.length; ++i) {
                  choseTableList.add(tableArr[i]);
               }
            }

            List<FieldReportFormVO> list = this.fieldReportFormService.getfieldreportform(datalist, choseTableList);
            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("2");
      info.setAuthorization(token);
      info.setUsername(TokenUtil.getUserId(request.getHeader("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 = {"/se/{setuptype}/pd/{projectid}/vn/{version}/td/{treetid}/dd/{datasystemid}/sa/{schema}/te/{tablename}/test", "/se/{setuptype}/pd/{projectid}/vn/{version}/td/{treetid}/dd/{datasystemid}/sa/{schema}/test", "/se/{setuptype}/pd/{projectid}/vn/{version}/td/{treetid}/dd/{datasystemid}/test", "/se/{setuptype}/pd/{projectid}/vn/{version}/td/{treetid}/test", "/se/{setuptype}/pd/{projectid}/vn/{version}/test"},
      method = {RequestMethod.POST},
      produces = {"text/json;charset=UTF-8"}
   )
   public String postDataScopeTest(@PathVariable("setuptype") String setuptype, @PathVariable("projectid") String projectid, @PathVariable("version") String version, @PathVariable(value = "treetid",required = false) String treetid, @PathVariable(value = "datasystemid",required = false) String datasystemid, @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");
      boolean flag = TokenUtil.verify(token);
      if (flag) {
         Map<String, Object> datalist = new HashMap();
         datalist.put("dataall[setuptype]", setuptype);
         datalist.put("dataall[editionid]", version);
         datalist.put("dataall[treetid]", treetid);
         datalist.put("dataall[datasystemname]", datasystemid);
         datalist.put("dataall[tschemas]", schema);
         List<String> choseTableList = new ArrayList();
         if (StringUtils.isNotBlank(tablename)) {
            String[] tableArr = tablename.split(",");

            for(int i = 0; i < tableArr.length; ++i) {
               choseTableList.add(tableArr[i]);
            }
         }

         List<FieldReportFormVO> list = this.fieldReportFormService.getfieldreportform(datalist, choseTableList);
         if (null != list && list.size() != 0) {
            List<FieldReportFormVO> 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 = {"/se/{setuptype}/pd/{projectid}/vn/{version}/td/{treetid}/dd/{datasystemid}/sa/{schema}/te/{tablename}", "/se/{setuptype}/pd/{projectid}/vn/{version}/td/{treetid}/dd/{datasystemid}/sa/{schema}", "/se/{setuptype}/pd/{projectid}/vn/{version}/td/{treetid}/dd/{datasystemid}", "/se/{setuptype}/pd/{projectid}/vn/{version}/td/{treetid}", "/se/{setuptype}/pd/{projectid}/vn/{version}"},
      method = {RequestMethod.GET},
      produces = {"text/json;charset=UTF-8"}
   )
   public String getDataScope(@PathVariable("setuptype") String setuptype, @PathVariable("projectid") String projectid, @PathVariable("version") String version, @PathVariable(value = "treetid",required = false) String treetid, @PathVariable(value = "datasystemid",required = false) String datasystemid, @PathVariable(value = "schema",required = false) String schema, @PathVariable(value = "tablename",required = false) String tablename, HttpServletRequest request, HttpServletResponse response) {
      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) {
         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());
         Map<String, String> rvMap = AuthorizationTool.releaseVerification(reqUrl);
         if ("0".equals(rvMap.get("code"))) {
            Map<String, Object> datamap = new HashMap();
            datamap.put("dataall[setuptype]", setuptype);
            datamap.put("dataall[editionid]", version);
            datamap.put("dataall[treetid]", treetid);
            datamap.put("dataall[datasystemname]", datasystemid);
            datamap.put("dataall[tschemas]", schema);
            List<String> choseTableList = new ArrayList();
            if (StringUtils.isNotBlank(tablename)) {
               String[] tableArr = tablename.split(",");

               for(int i = 0; i < tableArr.length; ++i) {
                  choseTableList.add(tableArr[i]);
               }
            }

            List<FieldReportFormVO> list = this.fieldReportFormService.getfieldreportform(datamap, choseTableList);
            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("2");
         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;
      }
   }
}
