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

import com.alibaba.fastjson.JSONObject;
import com.chenyang.nse.bussiness.annot.PassToken;
import com.chenyang.nse.bussiness.commmon.json.RespHelper;
import com.chenyang.nse.bussiness.commmon.json.Response;
import com.chenyang.nse.bussiness.config.PropertiesLoaderUtils;
import com.chenyang.nse.bussiness.dao.PageInfo;
import com.chenyang.nse.bussiness.dao.table.core.scheduler.TCoreSchedulerKmLogDao;
import com.chenyang.nse.bussiness.dao.table.core.scheduler.TCoreSchedulerKmRulesDao;
import com.chenyang.nse.bussiness.entity.orm.table.core.desensitizationtask.Desensitizationtask;
import com.chenyang.nse.bussiness.entity.orm.table.core.scheduler.TCoreSchedulerKmLog;
import com.chenyang.nse.bussiness.entity.orm.table.core.scheduler.TCoreSchedulerKmRules;
import com.chenyang.nse.bussiness.entity.orm.table.core.scheduler.TCoreSchedulerRules;
import com.chenyang.nse.bussiness.entity.param.scheduler.AddSchedulerParam;
import com.chenyang.nse.bussiness.entity.param.scheduler.SaveTaskParam;
import com.chenyang.nse.bussiness.entity.vo.DataGridVO;
import com.chenyang.nse.bussiness.entity.vo.ResultVO;
import com.chenyang.nse.bussiness.entity.vo.scheduler.RulesVO;
import com.chenyang.nse.bussiness.entity.vo.scheduler.SchedulRuleVO;
import com.chenyang.nse.bussiness.entity.vo.scheduler.SchedulerVO;
import com.chenyang.nse.bussiness.service.core.SchedulerService;
import com.chenyang.nse.bussiness.tools.msg.MesUtil;
import com.chenyang.nse.bussiness.tools.token.TokenUtil;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.FileUtils;
import org.hibernate.criterion.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping({"/core/scheduler"})
public class SchedulerController {
   @Autowired
   private TCoreSchedulerKmRulesDao tCoreSchedulerKmRulesDao;
   @Autowired
   private TCoreSchedulerKmLogDao tCoreSchedulerKmLogDao;
   @Autowired
   private SchedulerService schedulerService;

   @RequestMapping
   public String index(HttpServletRequest request, HttpServletResponse response, Model model) {
      String crud = request.getParameter("crud");
      String id = request.getParameter("id");
      model.addAttribute("id", id);
      model.addAttribute("crud", crud);
      return "core/scheduler/scheduler";
   }

   @RequestMapping({"/add"})
   public String add() {
      return "core/scheduler/add/add";
   }

   @GetMapping({"/get/un/save/task"})
   @ResponseBody
   public Response<Map<String, Object>> getUnSaveTask(String srname, String id, String tid) {
      Map<String, Object> map = new HashMap();
      List<Desensitizationtask> list3 = this.schedulerService.getAddUnSaveTask(tid, srname);
      List<Desensitizationtask> editUnSaveTask = this.schedulerService.getEditUnSaveTask(id, tid, srname);
      List<Desensitizationtask> list2 = editUnSaveTask;
      List<String> list4 = new ArrayList();

      for(int i = 0; i < list2.size(); ++i) {
         String taskid = ((Desensitizationtask)list2.get(i)).getId();
         list4.add(taskid);
      }

      map.put("noin", list4);
      map.put("all", list3);
      return RespHelper.<Map<String, Object>>successResp(map);
   }

   @RequestMapping(
      value = {"/save/scheduler/task"},
      method = {RequestMethod.POST}
   )
   @ResponseBody
   public ResultVO saveSchedulerTask(@RequestBody AddSchedulerParam asp) {
      return this.schedulerService.saveSchedulerTask(asp);
   }

   @RequestMapping({"/save/scheduler/task1"})
   @ResponseBody
   public Response saveSchedulerTask1(@RequestBody SchedulerVO schedulerVO, HttpServletRequest request, HttpServletResponse response) {
      String[] xzlist = schedulerVO.getXzlist();
      String srName = schedulerVO.getSrName();
      String rulesType = schedulerVO.getRulesType();
      String qx = schedulerVO.getQx();
      String xloptions = schedulerVO.getXloptions();
      String howtime = schedulerVO.getHowtime();
      String timebox = schedulerVO.getTimebox();
      String id = schedulerVO.getTid();
      String rulesid = schedulerVO.getRulesid();
      AddSchedulerParam saveData = new AddSchedulerParam();
      List<SaveTaskParam> tasklist = new ArrayList();
      if (rulesType == null || "".equals(rulesType)) {
         rulesType = "0";
      }

      saveData.setRulesType(rulesType);
      saveData.setSrName(srName);
      saveData.setQx(qx);
      saveData.setXloptions(xloptions);
      saveData.setHowtime(howtime);
      saveData.setTimebox(timebox);
      saveData.setId(rulesid);
      String[] arr1 = timebox.split("\\s+");

      for(int i = 0; i < arr1.length; ++i) {
         saveData.setRulesDay(arr1[0]);
      }

      saveData.setRulesDay(timebox);
      saveData.setProjectid(id);
      String[] arr = timebox.split("\\s+|-|:");

      for(int i = 0; i < arr.length; ++i) {
         saveData.setRulesHour(arr[3]);
         saveData.setRulesMinute(arr[4]);
      }

      List<Desensitizationtask> list = this.schedulerService.getAddUnSaveTask(id);
      if ((xzlist == null || xzlist.length == 0) && (qx == "1" || "1".equals(qx))) {
         for(int i = 0; i < list.size(); ++i) {
            SaveTaskParam stp = new SaveTaskParam();
            stp.setId(((Desensitizationtask)list.get(i)).getId());
            stp.setTaskname(((Desensitizationtask)list.get(i)).getTaskname());
            tasklist.add(stp);
         }
      }

      if (xzlist != null) {
         for(int i = 0; i < xzlist.length; ++i) {
            String[] temp = xzlist[i].split("-");
            SaveTaskParam stp = new SaveTaskParam();
            stp.setId(temp[0]);
            stp.setTaskname(temp[1]);
            tasklist.add(stp);
         }
      }

      saveData.setSaveTask(tasklist);
      ResultVO resultVO = this.schedulerService.saveNewSchedulerTask(saveData);
      return RespHelper.createResp(resultVO.getResult(), MesUtil.getMsg("POP_00014", new String[0]), resultVO.getMessage());
   }

   @RequestMapping({"/get/selectscheduler"})
   @ResponseBody
   public Response<TCoreSchedulerRules> selectscheduler(String id, HttpServletRequest request, HttpServletResponse response) {
      TCoreSchedulerRules schedulerRules = this.schedulerService.selectscheduler(id);
      return RespHelper.<TCoreSchedulerRules>successResp(schedulerRules);
   }

   @GetMapping({"/get/scheduler/table"})
   @ResponseBody
   public Response<DataGridVO<RulesVO>> getSchedulerTable(Integer page, Integer rows, String id, HttpServletRequest request, HttpServletResponse response, Model model) {
      PageInfo pageinfo = new PageInfo();
      pageinfo.setPageno(page);
      pageinfo.setPagesize(rows);
      DataGridVO<RulesVO> dgv = new DataGridVO<RulesVO>();
      dgv.setRows(this.schedulerService.getSchedulerTable(pageinfo, id));
      dgv.setTotal(pageinfo.getCount());
      return RespHelper.<DataGridVO<RulesVO>>successResp(dgv);
   }

   @RequestMapping(
      value = {"/remove/scheduler/task"},
      method = {RequestMethod.POST}
   )
   @ResponseBody
   public String removeSchedulerTask(String taskid) {
      this.schedulerService.removeSchedulerTask(taskid);
      return "";
   }

   @RequestMapping(
      value = {"/repeat/task/name"},
      method = {RequestMethod.POST}
   )
   @ResponseBody
   public Response repeatTaskName1(String srName, String projectid) {
      Response res = RespHelper.successResp();
      res.setFlag(false);
      List<TCoreSchedulerRules> list = this.schedulerService.repeatTaskName1(srName, projectid);
      if (list.isEmpty()) {
         res.setFlag(true);
         res.setData("success");
      }

      return res;
   }

   @RequestMapping({"/saveSchedualTask"})
   @ResponseBody
   public Response<String> saveSchedualTask(@RequestBody SchedulRuleVO vo, HttpServletRequest request) throws ParseException {
      String token = request.getHeader("token");
      String username = TokenUtil.getUserId(token);
      TCoreSchedulerKmRules schedulerRule = vo.gettCoreSchedulerKmRules();
      schedulerRule.setCreateuser(username);
      String result = this.schedulerService.saveSchedualTask(schedulerRule);
      return "true".equals(result) ? RespHelper.successResp("操作成功") : RespHelper.createResp(false, "500", result);
   }

   @GetMapping({"/getSchedualTask"})
   @ResponseBody
   public Response<TCoreSchedulerKmRules> getSchedualTask(String id, HttpServletRequest request, HttpServletResponse response) {
      List<TCoreSchedulerKmRules> tCoreSchedulerKmRulesList = this.tCoreSchedulerKmRulesDao.queryAll();
      return null != tCoreSchedulerKmRulesList && tCoreSchedulerKmRulesList.size() > 0 ? RespHelper.successResp(tCoreSchedulerKmRulesList.get(0)) : RespHelper.successResp();
   }

   @GetMapping({"/loadTCoreSchedulerKmLog"})
   @ResponseBody
   public Response loadTCoreSchedulerKmLog(int pageno, int pagesize) throws Exception {
      PageInfo pageInfo = new PageInfo();
      pageInfo.setPageno(pageno);
      pageInfo.setPagesize(pagesize);
      List<TCoreSchedulerKmLog> tCoreSchedulerKmLogList = this.tCoreSchedulerKmLogDao.queryByPageInfo(pageInfo, Order.desc("testTime"));
      return RespHelper.updateResp(pageInfo, tCoreSchedulerKmLogList);
   }

   @PassToken
   @GetMapping({"/downloadLog"})
   @ResponseBody
   public void download(@RequestParam("id") String id, HttpServletRequest request, HttpServletResponse response) throws Exception {
      Properties props = new Properties();

      try {
         props = PropertiesLoaderUtils.loadAllProperties("config.properties");
      } catch (IOException e) {
         e.printStackTrace();
      }

      String filepath = props.getProperty("exceptionKmLogPath");
      String logDetail = props.getProperty("logDetail");
      File fileTarget = new File(filepath);
      if (!fileTarget.exists()) {
         fileTarget.mkdirs();
      }

      TCoreSchedulerKmLog tCoreSchedulerKmLog = (TCoreSchedulerKmLog)this.tCoreSchedulerKmLogDao.get(id);
      String testDetail = "";
      testDetail = tCoreSchedulerKmLog.getTestDetail();
      FileUtils.writeByteArrayToFile(new File(filepath + logDetail), JSONObject.toJSONString(testDetail).getBytes());
      String path = "";

      try {
         response.setCharacterEncoding("utf-8");
         response.setContentType("multipart/form-data");
         response.setHeader("Content-Disposition", "attachment;fileName=logDetail.log");
         InputStream inputStream = new FileInputStream(new File(filepath + logDetail));
         OutputStream os = response.getOutputStream();
         byte[] b = new byte[2048];

         int length;
         while((length = inputStream.read(b)) > 0) {
            os.write(b, 0, length);
         }

         os.close();
         inputStream.close();
      } catch (Exception e) {
         e.printStackTrace();
      }

   }

   @GetMapping({"/getKmLogDetail"})
   @ResponseBody
   public Response<TCoreSchedulerKmLog> getKmLogDetail(String id, HttpServletRequest request, HttpServletResponse response) {
      TCoreSchedulerKmLog tCoreSchedulerKmLog = (TCoreSchedulerKmLog)this.tCoreSchedulerKmLogDao.get(id);
      return RespHelper.<TCoreSchedulerKmLog>successResp(tCoreSchedulerKmLog);
   }

   @RequestMapping(
      value = {"/start/scheduler/task"},
      method = {RequestMethod.POST}
   )
   @ResponseBody
   public Response startTaskName(String taskid) {
      ResultVO resultVO = this.schedulerService.startSchedulerTask(taskid);
      Response response = new Response();
      response.setFlag(resultVO.getResult());
      response.setMsg(resultVO.getMessage());
      response.setData(resultVO.getVersion());
      return response;
   }

   @RequestMapping(
      value = {"/stop/scheduler/task"},
      method = {RequestMethod.POST}
   )
   @ResponseBody
   public ResultVO stopTaskName(String taskid) {
      return this.schedulerService.stopSchedulerTask(taskid);
   }
}
