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.entity.vo.desensitization.DesensitizationStrategyLogVO;
import com.chenyang.nse.bussiness.service.console.DesensitizationStrategyLogService;
import java.io.BufferedOutputStream;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
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.CrossOrigin;
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/DesensitizationStrategyLog"})
public class DesensitizationStrategyLogController {
   @Autowired
   DesensitizationStrategyLogService desensitizationStrategyLogService;

   @ResponseBody
   @PostMapping({"/queryDesensitizationStrategyLog"})
   @CrossOrigin
   public Response<DesensitizationStrategyLogVO> desensitizationStrategyLog(@RequestBody Map<String, Object> vo) {
      PageInfo pageInfo = new PageInfo();
      pageInfo.setPageno((Integer)vo.get("page"));
      pageInfo.setPagesize((Integer)vo.get("rows"));
      String module = vo.get("module").toString();
      String range = vo.get("range").toString();
      String user = vo.get("user").toString();
      String projectId = "";
      if (null != vo.get("projectId")) {
         projectId = vo.get("projectId").toString();
      }

      List<DesensitizationStrategyLogVO> data = this.desensitizationStrategyLogService.queryRow(pageInfo, module, range, user, projectId);
      return RespHelper.updateResp(pageInfo, data);
   }

   @ResponseBody
   @PostMapping({"/checkEnc"})
   @CrossOrigin
   public Response checkEnc(@RequestBody Map<String, Object> vo) {
      String module = vo.get("module").toString();
      String range = vo.get("range").toString();
      String user = vo.get("user").toString();
      String projectId = "";
      if (null != vo.get("projectId")) {
         projectId = vo.get("projectId").toString();
      }

      boolean check = this.desensitizationStrategyLogService.checkEnc(module, range, user, projectId);
      return check ? RespHelper.successResp() : RespHelper.errRespStr("校验失败");
   }

   @ResponseBody
   @PostMapping({"/getdesensitizationStrategyLog"})
   @CrossOrigin
   public Response getdesensitizationStrategyLog(@RequestBody Map<String, Object> vo, HttpServletRequest request, HttpServletResponse response) {
      String module = vo.get("module").toString();
      String range = vo.get("range").toString();
      String user = vo.get("user").toString();
      String projectId = "";
      if (null != vo.get("projectId")) {
         projectId = vo.get("projectId").toString();
      }

      List<Map<String, Object>> dataList = this.desensitizationStrategyLogService.queryList(module, range, user, projectId);
      String[] headers = new String[]{"用户", "时间", "操作代码", "操作信息"};
      if (dataList.size() < 65536) {
         this.xls("脱敏日志", dataList, headers, request, response);
         return null;
      } else {
         return RespHelper.successResp("数据量太大暂不支持");
      }
   }

   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);
         HSSFCellStyle style = this.getStyle(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);
                  cell.setCellStyle(style);
               }
            }
         }

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

   }

   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;
   }

   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 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();
         }

      }

   }
}
