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.dao.table.core.TCoreDatasystemDao;
import com.chenyang.nse.bussiness.entity.orm.table.core.TCoreDatasystem;
import com.chenyang.nse.bussiness.entity.orm.table.core.api.ApiInfoLog;
import com.chenyang.nse.bussiness.entity.orm.table.core.duty.DutyTableInfo;
import com.chenyang.nse.bussiness.entity.vo.api.AccountabilityVO;
import com.chenyang.nse.bussiness.service.core.api.AccountabilityAPIService;
import com.chenyang.nse.bussiness.service.core.api.ApiInfoLogService;
import com.chenyang.nse.bussiness.tools.token.TokenUtil;
import java.io.IOException;
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.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
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/ay"})
public class AccountabilityAPIController {
   @Autowired
   private AccountabilityAPIService accountabilityAPIService;
   @Autowired
   private TCoreDatasystemDao tCoreDatasystemDao;
   @Autowired
   private ApiInfoLogService apiInfoLogService;

   @ResponseBody
   @RequestMapping(
      value = {"/dd/{datasystemid}", "/pd/{projectid}/dd/{datasystemid}/td/{taskid}"},
      method = {RequestMethod.POST},
      produces = {"text/json;charset=UTF-8"}
   )
   public String postAccountability(@PathVariable(value = "projectid",required = false) String projectid, @PathVariable("datasystemid") String datasystemid, @PathVariable(value = "taskid",required = false) String taskid, 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"))) {
            TCoreDatasystem datasystem = (TCoreDatasystem)this.tCoreDatasystemDao.queryUnique(new Criterion[]{Restrictions.eq("id", datasystemid)});
            if (null == datasystem) {
               result.put("code", ResultAPIEnum.RT_ERROR_CODE_403_STR.getCode());
               result.put("msg", ResultAPIEnum.RT_ERROR_CODE_403_STR.getMsg());
            } else {
               DutyTableInfo obj = new DutyTableInfo();
               obj.setId(taskid);
               obj.setProjectid(projectid);
               obj.setDatasystemid(datasystemid);
               List<AccountabilityVO> list = this.accountabilityAPIService.selectAccountabilityInfo(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("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 = {"/dd/{datasystemid}/test", "/pd/{projectid}/dd/{datasystemid}/td/{taskid}/test"},
      method = {RequestMethod.POST},
      produces = {"text/json;charset=UTF-8"}
   )
   public String postAccountabilityTest(@PathVariable(value = "projectid",required = false) String projectid, @PathVariable("datasystemid") String datasystemid, @PathVariable(value = "taskid",required = false) String taskid, 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();
      (new StringBuilder()).append("http://").append(request.getServerName()).append(":").append(request.getServerPort()).append(request.getRequestURI()).toString();
      boolean flag = TokenUtil.verify(token);
      if (flag) {
         TCoreDatasystem datasystem = (TCoreDatasystem)this.tCoreDatasystemDao.queryUnique(new Criterion[]{Restrictions.eq("id", datasystemid)});
         if (null == datasystem) {
            result.put("code", ResultAPIEnum.RT_ERROR_CODE_403_STR.getCode());
            result.put("msg", ResultAPIEnum.RT_ERROR_CODE_403_STR.getMsg());
         } else {
            DutyTableInfo obj = new DutyTableInfo();
            obj.setId(taskid);
            obj.setProjectid(projectid);
            obj.setDatasystemid(datasystemid);
            List<AccountabilityVO> list = this.accountabilityAPIService.selectAccountabilityInfo(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_400_STR.getCode());
         result.put("msg", "Invalid Request");
      }

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

   @ResponseBody
   @RequestMapping(
      value = {"/dd/{datasystemid}", "/pd/{projectid}/dd/{datasystemid}/td/{taskid}"},
      method = {RequestMethod.GET},
      produces = {"text/json;charset=UTF-8"}
   )
   public String getAccountability(@PathVariable(value = "projectid",required = false) String projectid, @PathVariable("datasystemid") String datasystemid, @PathVariable(value = "taskid",required = false) String taskid, 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"))) {
            TCoreDatasystem datasystem = (TCoreDatasystem)this.tCoreDatasystemDao.queryUnique(new Criterion[]{Restrictions.eq("id", datasystemid)});
            if (null == datasystem) {
               result.put("code", ResultAPIEnum.RT_ERROR_CODE_403_STR.getCode());
               result.put("msg", ResultAPIEnum.RT_ERROR_CODE_403_STR.getMsg());
            } else {
               DutyTableInfo obj = new DutyTableInfo();
               obj.setId(taskid);
               obj.setProjectid(projectid);
               obj.setDatasystemid(datasystemid);
               List<AccountabilityVO> list = this.accountabilityAPIService.selectAccountabilityInfo(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("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;
      }
   }
}
