package com.ozs.rpm.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import com.ozs.rpm.service.ReportAutoViewService;
import com.ozs.rpm.service.ReportService;
import org.apache.poi.util.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.ozs.rpm.dto.ReportDTO;
import com.ozs.rpm.dto.data.ReportDataDTO;
import com.ozs.rpm.dto.view.ReportViewDTO;
import com.ozs.rpm.dto.view.ReportViewDataParam;
import com.ozs.rpm.util.AccountApi;
import com.ozs.rpm.util.R;
import com.ozs.rpm.util.S;
import com.ozs.rpm.util.StringUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Api(tags = { "报表自动化展示" })
@RestController
public class ReportAutoViewController {
	@Autowired
	private ReportAutoViewService reportAutoViewService;
	@Autowired
	private ReportService reportService;
	@Autowired
	private AccountApi accountApi;

	@ApiOperation("报表页面渲染接口")
	@GetMapping("/report/view/{id}")
	public R<ReportViewDTO> reportView(@PathVariable("id") String id,
			@RequestHeader(name = "token", required = false) String token) {
		try {
			String userId = "admin";
			if (StringUtil.isNotEmpty(token) && !token.equals("null")) {
				userId = accountApi.parseTokenId(token);
			}
			return reportAutoViewService.reportView(id, userId);
		} catch (Exception e) {
			e.printStackTrace();
			return new R<>(S.ERROR);
		}
	}
	@ApiOperation("获取报表数据")
	@PostMapping("/report/getReportData")
	public R<ReportDataDTO> getReportData(@RequestBody ReportViewDataParam reportViewDataParam,
			@RequestHeader(name = "token", required = false) String token) {
		try {
			String userId = "admin";
			if (StringUtil.isNotEmpty(token) && !token.equals("null")) {
				userId = accountApi.parseTokenId(token);
			}
			return reportService.getReportData(reportViewDataParam, userId);
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage());
			return new R<>(S.ERROR);
		}
	}

	@ApiOperation("根据分类code获取当前用户已赋权报表列表")
	@ApiImplicitParam(name = "menuCode", value = "菜单编号", required = false, paramType = "query", dataType = "String")
	@GetMapping("/report/listReportByUserAndMenu")
	public R<List<ReportDTO>> listReportByUserAndMenu(
			@RequestParam(value = "menuCode", required = false) String menuCode, @RequestHeader("token") String token) {
		try {
			return reportAutoViewService.listReportByUserAndMenu(menuCode, accountApi.parseTokenId(token));
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage());
			return new R<>(S.ERROR);
		}
	}

	@ApiOperation("报表数据下载-导出excel文件")
	@PostMapping(value = "/report/downloadReportFile", produces = { "application/octet-stream" })
	public void downloadReportFile(@RequestBody ReportViewDataParam reportViewDataParam,
			@RequestHeader("token") String token, HttpServletResponse response) {
		InputStream inputStream = null;
		ServletOutputStream servletOutputStream = null;
		File f = null;
		try {
			String userId = "admin";
			if (StringUtil.isNotEmpty(token) && !token.equals("null")) {
				userId = accountApi.parseTokenId(token);
			}

			// 文件名
			String fileName = "report-data.csv";
			String filePath = reportService.downloadReportFile(reportViewDataParam, userId);
			// response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
			response.setContentType("application/octet-stream");

			response.addHeader("Cache-Control", "no-cache, no-store, must-revalidate");
			response.addHeader("charset", "utf-8");
			response.addHeader("Pragma", "no-cache");
			String encodeName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.toString());
			response.setHeader("Content-Disposition",
					"attachment; filename=\"" + encodeName + "\"; filename*=utf-8''" + encodeName);
			f = new File(filePath);
			inputStream = new FileInputStream(f);
			servletOutputStream = response.getOutputStream();
			IOUtils.copy(inputStream, servletOutputStream);
			response.flushBuffer();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (servletOutputStream != null) {
					servletOutputStream.close();
					servletOutputStream = null;
				}
				if (inputStream != null) {
					inputStream.close();
					f.delete();
					inputStream = null;
				}
				// 召唤jvm的垃圾回收器
				System.gc();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

}
