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.EncryptionLogVo;
import com.chenyang.nse.bussiness.service.console.EncrypLogService;
import com.chenyang.nse.bussiness.service.core.encryption.EncryptionConfigService;
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 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.util.ObjectUtils;
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/encryptlog"})
public class EncryptLogController {
   @Autowired
   EncrypLogService encrypLogService;
   @Autowired
   private TBaseUserDao tBaseUserDao;
   @Autowired
   EncryptionConfigService encryptionConfigService;

   @RequestMapping({"/queryUserlist"})
   @ResponseBody
   public Response queryUserList() {
      List<TBaseUser> userlist = this.tBaseUserDao.queryAll();
      Map map = new HashMap();
      map.put("userlist", userlist);
      return RespHelper.successResp(map);
   }

   @RequestMapping({"/queryEncryptionType"})
   @ResponseBody
   public Response queryEncryptionType() {
      String encryptionType = "";
      List<TreeVO> data = this.encryptionConfigService.getEncryptionTypeList();
      Map map = new HashMap();
      map.put("EncryptionType", data);
      return RespHelper.successResp(map);
   }

   @ResponseBody
   @PostMapping({"/query"})
   @CrossOrigin
   public Response<EncryptionLogVo> getEncryptionLog(@RequestBody Map<String, Object> vo) {
      PageInfo pageInfo = new PageInfo();
      pageInfo.setPageno((Integer)vo.get("page"));
      pageInfo.setPagesize((Integer)vo.get("rows"));
      String projectId = "";
      if (!ObjectUtils.isEmpty(vo.get("projectId"))) {
         projectId = vo.get("projectId").toString();
      }

      String module = vo.get("module") == null ? "" : vo.get("module").toString();
      String range = vo.get("range") == null ? "" : vo.get("range").toString();
      String user = "";
      if (null != vo.get("user")) {
         user = vo.get("user").toString();
      }

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

   @ResponseBody
   @PostMapping({"/getEncryptionLogExcel"})
   public Response getEncryptionLogExcel(@RequestBody Map<String, Object> vo, HttpServletRequest request, HttpServletResponse response) {
      String projectId = "";
      if (!ObjectUtils.isEmpty(vo.get("projectId"))) {
         projectId = vo.get("projectId").toString();
      }

   String module = vo.get("module") == null ? "" : vo.get("module").toString();
   String range = vo.get("range") == null ? "" : vo.get("range").toString();
      String user = "";
      if (null != vo.get("user")) {
         user = vo.get("user").toString();
      }

      List<Map<String, Object>> dataList = this.encrypLogService.queryList(projectId, module, range, user);
      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 Map<String, Object> vo, HttpServletRequest request, HttpServletResponse response) {
      String projectId = "";
      if (!ObjectUtils.isEmpty(vo.get("projectId"))) {
         projectId = vo.get("projectId").toString();
      }

      String module = vo.get("module").toString();
      String range = vo.get("range").toString();
      String user = "";
      if (null != vo.get("user")) {
         user = vo.get("user").toString();
      }

      boolean check = this.encrypLogService.checkEnc(projectId, module, range, user);
      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);
         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();
         }

      }

   }
}
