package com.yeejoin.amos.maintenance.business.controller;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.restful.doc.TycloudOperation;

import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.maintenance.business.param.TaskStatisticsParam;
import com.yeejoin.amos.maintenance.business.service.impl.TaskReportService;
import com.yeejoin.amos.maintenance.business.util.CommonResponse;
import com.yeejoin.amos.maintenance.business.util.CommonResponseUtil;
import com.yeejoin.amos.maintenance.business.util.Toke;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@RestController
@RequestMapping(value = "/api/excel")
@Api(tags="巡检完成情况月报表")
public class ExcelExportController extends AbstractBaseController{
	private final Logger log = LoggerFactory.getLogger(ExcelExportController.class);


	@Autowired
	private TaskReportService taskReportService;

	/**
	 * 巡检完成情况月报表导出excel
	 *
	 * @param statistical  统计类型
	 * @param startDate		统计开始时间
	 * @param endDate     统计结束时间
	 * @param planId		计划ID
	 * @param routeId		路线ID
	 *
	 * @return
	 *
	 * 导出格式为：vnd.ms-excel
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "巡检完成情况月报表导出excel", notes = " 巡检完成情况月报表导出excel")
	@RequestMapping(value = "/task/{statistical}", produces = "application/vnd.ms-excel;charset=UTF-8", method = RequestMethod.GET)
	public CommonResponse taskReport(
					@ApiParam(value = "统计口径", required = true) @PathVariable String statistical,
					@ApiParam(value = "开始日期", required = true) @RequestParam String startDate,
					@ApiParam(value = "结束日期", required = true) @RequestParam String endDate,
					@ApiParam(value = "所属计划") @RequestParam(required = false) Integer planId,
					@ApiParam(value = "所属路线") @RequestParam(required = false) Integer routeId,
					HttpServletResponse response) throws Exception
	{
		startDate 	+= " 00:00:00";
		endDate 	+= " 23:59:59";
		ReginParams reginParams = getSelectedOrgInfo();
		String orgCode = getLoginOrgCode(reginParams);
		Map<String,Object> map 	=  taskReportService.queryForTaskReport(getToken(),getProduct(),getAppKey(),statistical,startDate,endDate,planId,routeId,orgCode);


		Map summation = (Map)map.get("summation");

		for(Object key : summation.keySet())
			map.put("summation"+key,summation.get(key));

		String template 		= "temp/reportExportTemplate.xls";
		this.writToResponse(map,response,template,"report.xls");

		return CommonResponseUtil.success();
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "  人员综合统计分析Excel导出", notes = " 人员综合统计分析Excel导出")
	@RequestMapping(value = "/comprehensive/user", produces = "application/vnd.ms-excel;charset=UTF-8", method = RequestMethod.POST)
	public CommonResponse comprehensiveStatisticalForUser(
			@RequestBody(required=true) TaskStatisticsParam param,
			HttpServletResponse response) throws Exception

	{
		Toke toke = new Toke();
		toke.setToke(getToken());
		toke.setProduct(getProduct());
		toke.setAppKey(getAppKey());
		Map<String,Object> map 	= taskReportService.comprehensiveStatisticalForUser(toke,getProduct(),getAppKey(),param.getStartTime(),param.getEndTime());

		Map summation = (Map)map.get("summation");

		for(Object key : summation.keySet())
			map.put("summation"+key,summation.get(key));

		String template 		= "temp/comprehensiveStatistical.xls";
		this.writToResponse(map,response,template,"comprehensiveStatistical.xls");
		return CommonResponseUtil.success();
	}





	private void writToResponse(Map data,HttpServletResponse response,String templateFileName ,String outFileName) throws Exception
	{
		ClassPathResource classPathResource = new ClassPathResource(templateFileName);
		InputStream inputStream = classPathResource.getInputStream();
		File file = File.createTempFile("test", ".xls");
		FileUtils.copyInputStreamToFile(inputStream, file);
		TemplateExportParams params = new TemplateExportParams(file.getAbsolutePath(), true);
		ByteArrayOutputStream bout  = new ByteArrayOutputStream();

		Workbook book = ExcelExportUtil.exportExcel(params, data);
		book.write(bout);

		response.setHeader("Content-Disposition", "attachment; filename="+outFileName);
		response.setHeader("content-length", bout.size() + "");
		response.getOutputStream().write(bout.toByteArray());
		response.getOutputStream().flush();
		response.getOutputStream().close();
	}
}
