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

import com.chenyang.nse.bussiness.config.PropertiesLoaderUtils;
import com.chenyang.nse.bussiness.dao.PageInfo;
import com.chenyang.nse.bussiness.entity.vo.DataGridVO;
import com.chenyang.nse.bussiness.entity.vo.ResultVO;
import com.chenyang.nse.bussiness.entity.vo.datascope.FieldReportFormDetailVO;
import com.chenyang.nse.bussiness.entity.vo.datascope.FieldReportFormTotalVO;
import com.chenyang.nse.bussiness.entity.vo.datascope.FieldReportFormVO;
import com.chenyang.nse.bussiness.service.core.CoreProjectService;
import com.chenyang.nse.bussiness.service.core.FieldReportFormService;
import com.chenyang.nse.bussiness.tools.io.FileTool;
import com.chenyang.nse.bussiness.tools.office.ExcelTool;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping({"/core/fieldreportformtotal"})
public class FieldReportFormTotalController {
   @Autowired
   private FieldReportFormService fieldReportFormService;
   @Autowired
   private CoreProjectService coreProjectService;

   @RequestMapping
   public String index(HttpServletRequest request, HttpServletResponse response, Model model) {
      return "core/datascope/fieldreportformtotal";
   }

   @ResponseBody
   @RequestMapping({"/getfieldreportform"})
   public DataGridVO<FieldReportFormVO> fieldreportform(@RequestParam Map<String, Object> dataall, @RequestParam("subject[]") List<String> choseTable, Integer page, Integer rows, PageInfo pageInfo, HttpServletRequest request, HttpServletResponse response, Model model) {
      pageInfo.setPageno(page);
      pageInfo.setPagesize(rows);
      List<FieldReportFormVO> list = this.fieldReportFormService.getfieldreportform(dataall, choseTable);
      pageInfo.setCount((long)list.size());
      new DataGridVO();
      DataGridVO vo;
      if ((list.size() - pageInfo.getOffset()) / rows < 1) {
         vo = new DataGridVO((long)list.size(), list.subList(pageInfo.getOffset(), pageInfo.getOffset() + (list.size() - pageInfo.getOffset()) % rows));
      } else {
         vo = new DataGridVO((long)list.size(), list.subList(pageInfo.getOffset(), pageInfo.getOffset() + pageInfo.getPagesize()));
      }

      return vo;
   }

   @ResponseBody
   @RequestMapping({"/getfieldreportformTotal"})
   public DataGridVO<FieldReportFormTotalVO> getfieldreportformTotal(@RequestParam Map<String, Object> dataall, @RequestParam("subject[]") List<String> choseTable, Integer page, Integer rows, PageInfo pageInfo, HttpServletRequest request, HttpServletResponse response, Model model) {
      pageInfo.setPageno(page);
      pageInfo.setPagesize(rows);
      List<FieldReportFormTotalVO> list = this.fieldReportFormService.getfieldreportformTotal(dataall, choseTable, pageInfo);
      pageInfo.setCount((long)list.size());
      new DataGridVO();
      DataGridVO<FieldReportFormTotalVO> vo = new DataGridVO((long)list.size(), list);
      return vo;
   }

   @ResponseBody
   @RequestMapping({"/getfieldreportformDetail"})
   public DataGridVO<FieldReportFormDetailVO> getfieldreportformDetail(@RequestParam Map<String, Object> dataall, @RequestParam("subject[]") List<String> choseTable, Integer page, Integer rows, PageInfo pageInfo, HttpServletRequest request, HttpServletResponse response, Model model) {
      pageInfo.setPageno(page);
      pageInfo.setPagesize(rows);
      List<FieldReportFormDetailVO> list = this.fieldReportFormService.getfieldreportformDetail(dataall, choseTable, pageInfo);
      pageInfo.setCount((long)list.size());
      new DataGridVO();
      DataGridVO vo;
      if ((list.size() - pageInfo.getOffset()) / rows < 1) {
         vo = new DataGridVO((long)list.size(), list.subList(pageInfo.getOffset(), pageInfo.getOffset() + (list.size() - pageInfo.getOffset()) % rows));
      } else {
         vo = new DataGridVO((long)list.size(), list.subList(pageInfo.getOffset(), pageInfo.getOffset() + pageInfo.getPagesize()));
      }

      return vo;
   }

   @ResponseBody
   @RequestMapping({"/getfieldreportformDetail/ExceltoLog"})
   public ResultVO getfieldreportformDetailExceltoLog(@RequestParam Map<String, Object> dataall, @RequestParam("subject[]") List<String> choseTable, Integer page, Integer rows, PageInfo pageInfo, HttpServletRequest request, HttpServletResponse response, Model model) throws Exception {
      String userAgent = request.getHeader("User-Agent");
      Properties props = new Properties();

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

      String path = props.getProperty("fieldreportformDir");
      SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHMMSS");
      String fileName = df.format(new Date()) + ".xlsx";
      path = path + fileName;
      XSSFWorkbook wb = new XSSFWorkbook();
      String[] title = new String[]{"", "字段", "表", "分类", "分级", "合规"};
      Map<String, List<FieldReportFormDetailVO>> map = new HashMap();

      for(int i = 1; i < 6; ++i) {
         dataall.put("dataall[detailType]", i + "");
         List<FieldReportFormDetailVO> list = this.fieldReportFormService.getfieldreportformDetail(dataall, choseTable, pageInfo);
         map.put(title[i], list);
      }

      for(Map.Entry<String, List<FieldReportFormDetailVO>> entry : map.entrySet()) {
         LinkedBlockingQueue<HashMap<String, String>> queue = new LinkedBlockingQueue();
         List<FieldReportFormDetailVO> list1 = (List)entry.getValue();
         String sheetname = (String)entry.getKey();
         if ("字段".equals(sheetname)) {
            for(FieldReportFormDetailVO fieldReportFormDetailVO : list1) {
               try {
                  HashMap<String, String> hashmap = new HashMap();
                  hashmap.put("tablename", fieldReportFormDetailVO.getTablecnt().split("#_#")[0]);
                  hashmap.put("columnname", fieldReportFormDetailVO.getFieldcnt().split("#_#")[1]);
                  queue.put(hashmap);
               } catch (InterruptedException e) {
                  e.printStackTrace();
               }
            }

            Map<String, String> titlevalue = new LinkedHashMap();
            titlevalue.put("表名", "tablename");
            titlevalue.put("字段名", "columnname");
            List<Integer> columnWidthList = new ArrayList();
            columnWidthList.add(2200);
            columnWidthList.add(2200);
            ExcelTool.generateSheetExcel(wb, path, queue, titlevalue, columnWidthList, (List)null, sheetname);
         } else if ("表".equals(sheetname)) {
            for(FieldReportFormDetailVO fieldReportFormDetailVO : list1) {
               try {
                  HashMap<String, String> hashmap = new HashMap();
                  hashmap.put("tablename", fieldReportFormDetailVO.getTablecnt());
                  queue.put(hashmap);
               } catch (InterruptedException e) {
                  e.printStackTrace();
               }
            }

            Map<String, String> titlevalue = new LinkedHashMap();
            titlevalue.put("表名", "tablename");
            List<Integer> columnWidthList = new ArrayList();
            columnWidthList.add(2200);
            ExcelTool.generateSheetExcel(wb, path, queue, titlevalue, columnWidthList, (List)null, sheetname);
         } else if ("分类".equals(sheetname)) {
            for(FieldReportFormDetailVO fieldReportFormDetailVO : list1) {
               try {
                  HashMap<String, String> hashmap = new HashMap();
                  hashmap.put("tablename", fieldReportFormDetailVO.getScopecnt());
                  queue.put(hashmap);
               } catch (InterruptedException e) {
                  e.printStackTrace();
               }
            }

            Map<String, String> titlevalue = new LinkedHashMap();
            titlevalue.put("分类名", "tablename");
            List<Integer> columnWidthList = new ArrayList();
            columnWidthList.add(2200);
            ExcelTool.generateSheetExcel(wb, path, queue, titlevalue, columnWidthList, (List)null, sheetname);
         } else if ("分级".equals(sheetname)) {
            for(FieldReportFormDetailVO fieldReportFormDetailVO : list1) {
               try {
                  HashMap<String, String> hashmap = new HashMap();
                  hashmap.put("tablename", fieldReportFormDetailVO.getLevelcnt());
                  queue.put(hashmap);
               } catch (InterruptedException e) {
                  e.printStackTrace();
               }
            }

            Map<String, String> titlevalue = new LinkedHashMap();
            titlevalue.put("分级名", "tablename");
            List<Integer> columnWidthList = new ArrayList();
            columnWidthList.add(2200);
            ExcelTool.generateSheetExcel(wb, path, queue, titlevalue, columnWidthList, (List)null, sheetname);
         } else if ("合规".equals(sheetname)) {
            for(FieldReportFormDetailVO fieldReportFormDetailVO : list1) {
               try {
                  HashMap<String, String> hashmap = new HashMap();
                  hashmap.put("tablename", fieldReportFormDetailVO.getDirectorycnt());
                  queue.put(hashmap);
               } catch (InterruptedException e) {
                  e.printStackTrace();
               }
            }

            Map<String, String> titlevalue = new LinkedHashMap();
            titlevalue.put("合规目录名", "tablename");
            List<Integer> columnWidthList = new ArrayList();
            columnWidthList.add(2200);
            ExcelTool.generateSheetExcel(wb, path, queue, titlevalue, columnWidthList, (List)null, sheetname);
         }
      }

      ResultVO vo = new ResultVO(path, true);
      return vo;
   }

   @ResponseBody
   @RequestMapping({"/exportToExceltoLog"})
   public ResultVO exportToExceltoLog(@RequestParam Map<String, Object> dataall, @RequestParam("subject[]") List<String> choseTable, Integer page, Integer rows, PageInfo pageInfo, HttpServletRequest request, HttpServletResponse response, Model model) throws Exception {
      String userAgent = request.getHeader("User-Agent");
      Properties props = new Properties();

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

      String path = props.getProperty("fieldreportformDir");
      SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHMMSS");
      String fileName = df.format(new Date()) + ".xlsx";
      path = path + fileName;
      XSSFWorkbook wb = new XSSFWorkbook();
      List<FieldReportFormVO> list = this.fieldReportFormService.getfieldreportform(dataall, choseTable);
      Map<String, List<FieldReportFormVO>> map = (Map)list.stream().collect(Collectors.groupingBy(FieldReportFormVO::getId));

      for(Map.Entry<String, List<FieldReportFormVO>> entry : map.entrySet()) {
         LinkedBlockingQueue<HashMap<String, String>> queue = new LinkedBlockingQueue();
         List<FieldReportFormVO> list1 = (List)entry.getValue();
         String sheetname = ((FieldReportFormVO)list1.get(0)).getDatascopename();

         for(FieldReportFormVO fieldReportFormVO : list1) {
            try {
               HashMap<String, String> hashmap = new HashMap();
               hashmap.put("datascopename", fieldReportFormVO.getDatascopename());
               hashmap.put("datasystemname", fieldReportFormVO.getDatasystemname());
               hashmap.put("tschemas", fieldReportFormVO.getTschemas());
               hashmap.put("names", fieldReportFormVO.getNames());
               hashmap.put("fieldname", fieldReportFormVO.getFieldname());
               queue.put(hashmap);
            } catch (InterruptedException e) {
               e.printStackTrace();
            }
         }

         Map<String, String> titlevalue = new LinkedHashMap();
         titlevalue.put("ID", "id");
         titlevalue.put("所属名称", "datascopename");
         titlevalue.put("数据源", "datasystemname");
         titlevalue.put("所有者", "tschemas");
         titlevalue.put("表名", "names");
         titlevalue.put("列名", "fieldname");
         List<Integer> columnWidthList = new ArrayList();
         columnWidthList.add(2200);
         columnWidthList.add(2200);
         columnWidthList.add(2200);
         columnWidthList.add(2200);
         columnWidthList.add(1600);
         columnWidthList.add(1600);
         ExcelTool.generateSheetExcel(wb, path, queue, titlevalue, columnWidthList, (List)null, sheetname);
      }

      ResultVO vo = new ResultVO(path, true);
      return vo;
   }

   @RequestMapping({"/downloadfile"})
   public String downloadfile(String path, HttpServletRequest request, HttpServletResponse response, Model model) {
      try {
         String fileName = path.substring(path.length() - 20, path.length() - 1);
         response.setCharacterEncoding("utf-8");
         response.setContentType("multipart/form-data");
         response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
         InputStream inputStream = new FileInputStream(new File(path));
         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();
         FileTool.removeFile(path);
      } catch (Exception e) {
         e.printStackTrace();
      }

      return null;
   }
}
