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

import com.chenyang.nse.bussiness.commmon.json.RespHelper;
import com.chenyang.nse.bussiness.commmon.json.Response;
import com.chenyang.nse.bussiness.dao.PageInfo;
import com.chenyang.nse.bussiness.dao.table.base.TBaseUserDao;
import com.chenyang.nse.bussiness.entity.orm.table.base.TBaseUser;
import com.chenyang.nse.bussiness.entity.vo.TreeVO;
import com.chenyang.nse.bussiness.entity.vo.encyption.TConsoleLogVo;
import com.chenyang.nse.bussiness.service.console.MenuService;
import com.chenyang.nse.bussiness.service.console.OperLogService;
import java.io.BufferedOutputStream;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping({"/aop"})
public class OperLogController {
   @Autowired
   private OperLogService operLogService;
   @Autowired
   private MenuService menuService;
   @Autowired
   private TBaseUserDao tBaseUserDao;

   @PostMapping({"/queryMenuTreeAndUserlist"})
   @ResponseBody
   public Response queryMenuTree(@RequestBody String type) {
      String menutype = "";
      if (type.equals("global")) {
         menutype = "";
      }

      if (type.equals("item")) {
         menutype = "2";
      }

      List<TreeVO> menulist = this.menuService.getMenuTreeList(menutype);
      menulist = (List)menulist.stream().filter((m) -> !m.getText().equals("管理首页") && !m.getText().equals("行为审计") && !m.getText().equals("首页") && !m.getText().equals("License管理")).collect(Collectors.toList());
      List<TBaseUser> userlist = this.tBaseUserDao.queryAll();
      Map map = new HashMap();
      map.put("menulist", menulist);
      map.put("userlist", userlist);
      return RespHelper.successResp(map);
   }

   @ResponseBody
   @PostMapping({"/query"})
   public Response<TConsoleLogVo> getOperLog(@RequestBody TConsoleLogVo vo) {
      PageInfo pageInfo = new PageInfo();
      pageInfo.setPageno(vo.getPage());
      pageInfo.setPagesize(vo.getRows());
      String range = vo.getRange();
      String user = vo.getUser();
      String module = vo.getModule();
      List<TConsoleLogVo> data = this.operLogService.queryRow(pageInfo, user, range, module);
      return RespHelper.updateResp(pageInfo, data);
   }

   @ResponseBody
   @PostMapping({"/getOpeExcel"})
   public Response getOpeExcel(@RequestBody TConsoleLogVo vo, HttpServletRequest request, HttpServletResponse response) {
      String range = vo.getRange();
      String user = vo.getUser();
      String module = vo.getModule();
      List<Map<String, Object>> dataList = this.operLogService.queryList(user, range, module);
      String[] headers = new String[]{"用户", "时间", "操作代码", "操作模块", "操作信息"};
      if (dataList.size() < 65536) {
         this.xls("操作日志", dataList, headers, request, response);
         return null;
      } else {
         return RespHelper.successResp("数据量太大暂不支持");
      }
   }

   @ResponseBody
   @PostMapping({"/checkEnc"})
   public Response checkEnc(@RequestBody TConsoleLogVo vo, HttpServletRequest request, HttpServletResponse response) {
      String range = vo.getRange();
      String user = vo.getUser();
      String module = vo.getModule();
      boolean check = this.operLogService.checkEnc(user, range, module);
      return check ? RespHelper.successResp() : RespHelper.errRespStr("校验失败");
   }

   private void xls(String name, List<Map<String, Object>> dataList, String[] headers, HttpServletRequest request, HttpServletResponse response) {
      Date date = new Date();
      String sdate = (new SimpleDateFormat("yyyyMMdd")).format(date);
      String fileName = name + "_" + sdate + ".xls";
      HSSFWorkbook workbook = new HSSFWorkbook();
      HSSFSheet sheet = null;

      try {
         sheet = workbook.createSheet("操作日志");
         HSSFCellStyle columnTopStyle = this.getColumnTopStyle(workbook);
         int columnNum = headers.length;
         HSSFRow headLine = sheet.createRow(0);
         sheet.setDefaultColumnWidth(15);

         for(int n = 0; n < columnNum; ++n) {
            HSSFCell cellRowName = headLine.createCell(n);
            cellRowName.setCellType(1);
            HSSFRichTextString text = new HSSFRichTextString(headers[n]);
            cellRowName.setCellValue(text);
            cellRowName.setCellStyle(columnTopStyle);
         }

         if (dataList.size() != 0) {
            HSSFCellStyle lockstyle = this.getStyle(workbook);
            lockstyle.setAlignment((short)2);
            lockstyle.setVerticalAlignment((short)1);
            HSSFRow dataRow = null;
            int index = 0;

            for(Map<String, Object> mapx : dataList) {
               ++index;
               dataRow = sheet.createRow(index);

               for(int i = 0; i < headers.length; ++i) {
                  HSSFCell cell = dataRow.createCell(i);
                  String value;
                  if ("时间".equals(headers[i])) {
                     value = mapx.get(headers[i]) == null ? null : (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(mapx.get(headers[i]));
                  } else {
                     value = (String)mapx.get(headers[i]);
                  }

                  cell.setCellValue(value);
               }
            }
         }

         try {
            this.getExportedField(workbook, fileName, response);
         } catch (Exception e) {
            e.printStackTrace();
         }
      } catch (Exception e) {
         e.printStackTrace();
      }

   }

   public void getExportedField(Workbook workbook, String name, HttpServletResponse response) throws Exception {
      BufferedOutputStream fos = null;

      try {
         response.setContentType("application/x-download");
         response.setHeader("Content-Disposition", "attachment;filename=" + new String(name.getBytes(StandardCharsets.UTF_8), "ISO8859-1"));
         fos = new BufferedOutputStream(response.getOutputStream());
         workbook.write(fos);
      } catch (Exception e) {
         e.printStackTrace();
      } finally {
         if (fos != null) {
            fos.close();
         }

      }

   }

   public HSSFCellStyle getColumnTopStyle(HSSFWorkbook workbook) {
      HSSFFont font = workbook.createFont();
      font.setFontHeightInPoints((short)11);
      font.setBoldweight((short)700);
      font.setFontName("微软雅黑");
      HSSFCellStyle style = workbook.createCellStyle();
      style.setBorderBottom((short)1);
      style.setBottomBorderColor((short)8);
      style.setBorderRight((short)1);
      style.setTopBorderColor((short)8);
      style.setTopBorderColor((short)8);
      style.setFont(font);
      style.setWrapText(false);
      style.setAlignment((short)2);
      style.setVerticalAlignment((short)1);
      return style;
   }

   public HSSFCellStyle getStyle(HSSFWorkbook workbook) {
      HSSFFont font = workbook.createFont();
      font.setFontHeightInPoints((short)10);
      font.setBoldweight((short)400);
      font.setFontName("微软雅黑");
      HSSFCellStyle style = workbook.createCellStyle();
      style.setBorderBottom((short)1);
      style.setBottomBorderColor((short)8);
      style.setBorderLeft((short)1);
      style.setLeftBorderColor((short)8);
      style.setBorderRight((short)1);
      style.setRightBorderColor((short)8);
      style.setBorderTop((short)1);
      style.setTopBorderColor((short)8);
      style.setFont(font);
      style.setWrapText(false);
      style.setAlignment((short)2);
      style.setVerticalAlignment((short)1);
      return style;
   }
}
