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

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.entity.vo.DataGridVO;
import com.chenyang.nse.bussiness.entity.vo.ResultVO;
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.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

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

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

   @ResponseBody
   @RequestMapping({"/getfieldreportform"})
   public Response<DataGridVO<FieldReportFormVO>> fieldreportform(@RequestBody Map<String, Object> map) {
      Map<String, Object> dataall = (Map)map.get("dataall");
      List<String> choseTable = (List)map.get("subject");
      String projectid = map.get("projectid").toString();
      int page = (Integer)map.get("page");
      int rows = (Integer)map.get("rows");
      int offset = (page - 1) * rows;
      List<FieldReportFormVO> list = this.fieldReportFormService.getfieldreportform(dataall, choseTable, projectid);
      new DataGridVO();
      DataGridVO vo;
      if ((list.size() - offset) / rows < 1) {
         vo = new DataGridVO((long)list.size(), list.subList(offset, offset + (list.size() - offset) % rows));
      } else {
         vo = new DataGridVO((long)list.size(), list.subList(offset, offset + rows));
      }

      return RespHelper.<DataGridVO<FieldReportFormVO>>successResp(vo, list.size());
   }

   @ResponseBody
   @RequestMapping({"/exportToExceltoLog"})
   public Response<ResultVO> exportToExceltoLog(@RequestBody Map<String, Object> param) throws Exception {
      Map<String, Object> dataall = (Map)param.get("dataall");
      List<String> choseTable = (List)param.get("subject");
      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 RespHelper.<ResultVO>successResp(vo);
   }

   @RequestMapping({"/downloadfile"})
   public String downloadfile(String path, HttpServletRequest request, HttpServletResponse response, Model model) {
      try {
         String fileName = path.substring(path.length() - 20, path.length());
         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;
   }
}
