package com.huatek.busi.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.JOptionPane;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
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.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.dubbo.config.annotation.Reference;
import com.huatek.busi.common.util.DateUtil;
import com.huatek.busi.common.util.ExcelExport;
import com.huatek.busi.constant.ApiConstant.Tags;
import com.huatek.busi.service.cac.CacEtlFactoryService;
import com.huatek.busi.service.gis.RptGisMonitorSf6Service;
import com.huatek.busi.service.pointtable.PointTableEtlFactoryService;
import com.huatek.busi.service.transformer.TransformerRunStatusService;
import com.huatek.busi.vo.TransformerRunStatusVo;

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

/**
 * 数据输入查询控制器
 * 
 * @author anker_cheng
 * @date 2019/08/21
 */
@Slf4j
@Api(tags = {Tags.HISTORY_DATE})
@RestController
@RequestMapping("/api/DataInputQuery")
public class DataInputQueryController {
    @Reference(check = false)
    private CacEtlFactoryService<?> cacEtlFactoryService;
    @Reference(check = false)
    private TransformerRunStatusService transformerRunStatusService;
    @Reference(check = false)
    private PointTableEtlFactoryService pointTableEtlFactoryService;
    @Reference(check = false)
    private RptGisMonitorSf6Service rptGisMonitorSf6Service;

    /**
     * 分页查询
     * 
     * @param params
     *            参数：</br>
     *            <p>
     *            分页控制：page、limit
     *            </p>
     *            <p>
     *            CAC类型编码：cacMonitorTypeCode
     *            </p>
     *            <p>
     *            监测时间范围：timeStamp~timeStampEnd
     *            </p>
     *            <p>
     *            主设备树ID:mainTreeId
     * @return 分页数据
     * @see com.huatek.busi.common.CacMonitorTypeCode
     */
    @PostMapping(value = "/cacList")
    public Map<String, Object> cacList(@RequestBody Map<String, Object> params) {
        return cacEtlFactoryService.findCACPageData(params);
    }

    /**
     * @Title: 数据输入-CAC数据exportExecl
     * @Description: 数据输入-导出execl
     * @param response
     * @param request
     * @param params
     * 参数：</br>
     *       <p>typeCode:类型编码</p>
     *       <p>mainTreeId：主设备树ID</p>
     *       <p>监测时间范围：timeStamp~timeStampEnd</p>
     * @throws IOException
     */
    @SuppressWarnings("unchecked")
    @ApiOperation(value = "CAC历史数据导出")
    @GetMapping("/exportCacList")
    public void exportCacList(HttpServletResponse response , HttpServletRequest request,@RequestParam Map<String, Object> params) throws IOException {
        request.setCharacterEncoding("UTF-8");
        Map<String,Object> resultMap = cacEtlFactoryService.exportCacMonitorData(params);
        String title = resultMap.get("title").toString(); //excel Header
        String fileName =  resultMap.get("fileName").toString(); //excel Name
        List <Object> list= (List<Object>) resultMap.get("data");
        if (CollectionUtils.isEmpty(list)) {
            log.warn("==> " + title + ":无数据导出.");
        }
        OutputStream out = response.getOutputStream();
        response.reset();
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-Type","application/msexcel");
        fileName = new String(fileName.getBytes("gb2312"), "iso8859-1")+".xls";
        response.setHeader("Content-disposition","attachment; filename="+fileName);
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        ExcelExport<Object> ex = new ExcelExport<>();
        HSSFWorkbook wb = ex.exportExcel(title, list);
        log.info("==> 正在写入文件:" + title + ",请稍后...");
        wb.write(out);
        wb.close();
        log.info("==> " + title + ":数据导出完成.");      
        out.flush();
        out.close();
    }

    /**
     * 变压器运行工况历史数据查询 分页列表
     *
     * @param params
     *            GIS检修记录Dto
     * @return map map
     */
    @ApiOperation(value = "变压器运行工况列表分页查询", response = TransformerRunStatusVo.class)
    @PostMapping(value = "/transformerRunStatusList", produces = {"application/json;charset=utf-8"})
    public Map<String, Object> transformerRunStatusList(@RequestBody Map<String, Object> params) {
        return transformerRunStatusService.findTransformerRunStatusPage(params);
    }

    /**
     * 变压器运行工况历史数据导出
     * @param
     * ：</br>
	 *       <p>typeCode:类型编码</p>
	 *       <p>mainTreeId：主设备树ID</p>
	 *       <p>监测时间范围：timeStamp~timeStampEnd</p>
     * @return map map
     */
    @SuppressWarnings("unchecked")
	@ApiOperation(value = "变压器运行工况历史数据导出")
    @GetMapping(value = "/exportTransformerRunStatusList", produces = {"application/json;charset=utf-8"})
    public void exportTransformerRunStatusList(HttpServletResponse response , HttpServletRequest request,@RequestParam(value="mainTreeId")String mainTreeId,
    		@RequestParam(value="timeStamp")String timeStamp,@RequestParam(value="timeStampEnd")String timeStampEnd) {
		try {
			Map<String,Object> resultMap = transformerRunStatusService.exportPointTableData(mainTreeId,DateUtil.format(timeStamp),DateUtil.format(timeStampEnd));
			String title = resultMap.get("title").toString(); //excel Header
			String fileName =  resultMap.get("fileName").toString(); //excel Name
			List <Object> list= (List<Object>) resultMap.get("data");
			if (CollectionUtils.isEmpty(list)) {
				log.warn("==> " + title + ":无数据导出.");
			}
			OutputStream out = response.getOutputStream();
			response.reset();   
	        response.setHeader("Content-disposition", "attachment; filename="+new String(fileName.getBytes("gb2312"), "iso8859-1")+".xls");
	        response.setContentType("application/msexcel");
	        ExcelExport<Object> ex = new ExcelExport<>();
			HSSFWorkbook wb = ex.exportExcel(title, list);
			log.info("==> 正在写入文件:" + title + ",请稍后...");
			wb.write(out);
			wb.close();
			log.info("==> " + title + ":数据导出完成.");		
			out.flush();
			out.close();
		} catch (IOException e) {
			log.error(e.getMessage());
			Object[] options = { "确定"}; 
			JOptionPane.showOptionDialog(null, "导出失败！", "警告", JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE,null, options, options[0]);
		}
		
    }

    /**
     * 分页查询104图片数据
     * 
     * @param params
     *            参数：</br>
     *            <p>
     *            分页控制：page、limit
     *            </p>
     *            <p>
     *            104类型编码：pointTableMonitorTypeCode
     *            </p>
     *            <p>
     *            监测时间范围：timeStamp~timeStampEnd
     *            </p>
     *            <p>
     *            主设备树ID:mainTreeId
     * @return 分页数据
     * @see com.huatek.busi.common.CacMonitorTypeCode
     */
    @PostMapping(value = "/pointTableList")
    public Map<String, Object> pointTableList(@RequestBody Map<String, Object> params) {
        return pointTableEtlFactoryService.findPointTablePageData(params);
    }

    /**
	 * @Title: 数据输入-图片exportExecl
	 * @Description: 数据输入-导出execl
	 * @param response
	 * @param request
	 * @param params
	 * 参数：</br>
	 *       <p>typeCode:类型编码</p>
	 *       <p>mainTreeId：主设备树ID</p>
	 *       <p>监测时间范围：timeStamp~timeStampEnd</p>
	 * @throws IOException
	 */
	@SuppressWarnings("unchecked")
	@ApiOperation(value = "图片历史数据导出")
	@GetMapping("/exportpointTableListExecl")
	public void exportpointTableListExecl(HttpServletResponse response , HttpServletRequest request,@RequestParam Map<String, Object> params) throws IOException {
		Map<String,Object> resultMap = pointTableEtlFactoryService.exportPointTableData(params);
		String title = resultMap.get("title").toString(); //excel Header
		String fileName =  resultMap.get("fileName").toString(); //excel Name
		List <Object> list= (List<Object>) resultMap.get("data");
		if (CollectionUtils.isEmpty(list)) {
			log.warn("==> " + title + ":无数据导出.");
		}
		OutputStream out = response.getOutputStream();
		response.reset();   
        response.setHeader("Content-disposition", "attachment; filename="+new String(fileName.getBytes("GB2312"),"8859_1")+".xls");
        response.setContentType("application/msexcel");
        ExcelExport<Object> ex = new ExcelExport<>();
		HSSFWorkbook wb = ex.exportExcel(title, list);
		log.info("==> 正在写入文件:" + title + ",请稍后...");
		wb.write(out);
		wb.close();
		log.info("==> " + title + ":数据导出完成.");		
		out.flush();
		out.close();
	}

    /**
     * GIS-断路器监测数据
     *
     * @param Map<String,Object>: mainTreeId
     *                            timeStamp
     *                            timeStampEnd
     *                            
     * @return map map
     */
    @ApiOperation(value = "GIS断路器列表分页查询", response = TransformerRunStatusVo.class)
    @PostMapping(value = "/breakerMonitorList", produces = {"application/json;charset=utf-8"})
    public Map<String, Object> breakerMonitorList(@RequestBody Map<String, Object> params) {
        return rptGisMonitorSf6Service.findGisBreakerPage(params);
    }
    
    /**
     * GIS断路器监测历史数据导出
     * @param
     * </br>
	 *       <p>typeCode:类型编码</p>
	 *       <p>mainTreeId：主设备树ID</p>
	 *       <p>监测时间范围：timeStamp~timeStampEnd</p>
     * @return map map
     */
    @SuppressWarnings("unchecked")
	@ApiOperation(value = "GIS断路器监测历史数据导出")
    @GetMapping(value = "/exportBreakerMonitorList", produces = {"application/json;charset=utf-8"})
    public void exportBreakerMonitorList(HttpServletResponse response , HttpServletRequest request,@RequestParam(value="mainTreeId")String mainTreeId,
    		@RequestParam(value="timeStamp")String timeStamp,@RequestParam(value="timeStampEnd")String timeStampEnd) {
		try {
			Map<String,Object> resultMap = rptGisMonitorSf6Service.exportBreakerMonitorList(mainTreeId,timeStamp,timeStampEnd);
			String title = resultMap.get("title").toString(); //excel Header
			String fileName =  resultMap.get("fileName").toString(); //excel Name
			List <Object> list= (List<Object>) resultMap.get("data");
			if (CollectionUtils.isEmpty(list)) {
				log.warn("==> " + title + ":无数据导出.");
			}
			OutputStream out = response.getOutputStream();
			response.reset();   
	        response.setHeader("Content-disposition", "attachment; filename="+new String(fileName.getBytes("gb2312"), "iso8859-1")+".xls");
	        response.setContentType("application/msexcel");
	        ExcelExport<Object> ex = new ExcelExport<>();
			HSSFWorkbook wb = ex.exportExcel(title, list);
			log.info("==> 正在写入文件:" + title + ",请稍后...");
			wb.write(out);
			wb.close();
			log.info("==> " + title + ":数据导出完成.");		
			out.flush();
			out.close();
		} catch (IOException e) {
			log.error(e.getMessage());
			Object[] options = { "确定"}; 
			JOptionPane.showOptionDialog(null, "导出失败！", "警告", JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE,null, options, options[0]);
		}
		
    }
}