package com.huatek.busi.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;

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

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;
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.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import com.huatek.busi.common.util.ExcelExport;
import com.huatek.busi.constant.ApiConstant.Tags;
import com.huatek.busi.dto.BusiOutlineGisExperimentDataDto;
import com.huatek.busi.entity.BusiOutlineGisExperimentData;
import com.huatek.busi.service.BusiOutlineGisExperimentDataService;
import com.huatek.busi.vo.BusiOutlineGisExperimentDataVo;
import com.huatek.busi.vo.TransformerEvaluateDataVo2;
import com.huatek.torch.frame.log.KerLog;
import com.huatek.torch.frame.tools.ConstantUtil;
import com.huatek.torch.frame.tools.ResultUtil;

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

/**
 * 离线数据--GIS开关试验数据 控制层
 *
 * @author anker_cheng
 * @date Jul 4, 2019 2:15:27 PM
 */
@Api(tags = { Tags.BUSI_OUTLINE_GIS })
@Slf4j
@RestController
@RequestMapping("/api/BusiOutlineGisExperimentData")
public class BusiOutlineGisExperimentDataController {

	protected final Logger logger = LoggerFactory.getLogger(BusiOutlineGisExperimentDataController.class);

	@Reference(check = false)
	private BusiOutlineGisExperimentDataService busiOutlineGisExperimentDataService;

	/**
	 * 离线数据--GIS开关试验数据 分页列表
	 *
	 * @param busiOutlineGisExperimentDataDto
	 *            离线数据--GIS开关试验数据Dto
	 * @return map map
	 */
	@ApiOperation(value = "GIS开关试验数据查询")
	@KerLog(projectName = "PROJECTNAME", modelName = "BUSIOUTLINEGISEXPERIMENTDATA.MODELNAME", methodName = "BUSIOUTLINEGISEXPERIMENTDATA.METHODNAME.QUERYLIST")
	@GetMapping(value = "/queryList", produces = { "application/json;charset=utf-8" })
    public Map<String, Object> queryList(@RequestParam(value = "mainTreeId", required = true) String mainTreeId, @RequestParam(value = "startTime", required = false) String startTime, @RequestParam(value = "endTime", required = false) String endTime,
	        @RequestParam(value = "page", required = false) Integer page,
	        @RequestParam(value = "limit", required = false) Integer limit) {
		
		 DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    	 LocalDateTime start = null ;
    	 LocalDateTime end = null ;
    	 /*LocalDateTime.parse(start+
         		" 00:00:00",df), LocalDateTime.parse(end+" 23:59:59",df))*/

		if(StringUtils.isNotBlank(startTime)){
			start = LocalDateTime.parse(startTime+" 00:00:00",df);
		}
		
		if(StringUtils.isNotBlank(endTime)){
			end =	LocalDateTime.parse(endTime+" 23:59:59",df);
		}

		
        PageInfo<BusiOutlineGisExperimentDataVo> pageInfo =
            busiOutlineGisExperimentDataService.findBusiOutlineGisExperimentDataPage(mainTreeId,start,  end, page,  limit);
        return ResultUtil.put(ConstantUtil.REQUEST_SUCCESS, pageInfo.getTotal(), "", pageInfo.getList());
    }
	
	
	
//	 @GetMapping(value = "/page")
//	    public Map<String, Object> page(@RequestParam(value = "mainTreeId", required = true) String mainTreeId, @RequestParam(value = "startTime", required = false) String startTime, @RequestParam(value = "endTime", required = false) String endTime,
//	        @RequestParam(value = "page", required = false) Integer page,
//	        @RequestParam(value = "limit", required = false) Integer limit) {
//	    	
//	    	 DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//	    	 LocalDateTime start = null ;
//	    	 LocalDateTime end = null ;
//	    	 /*LocalDateTime.parse(start+
//	         		" 00:00:00",df), LocalDateTime.parse(end+" 23:59:59",df))*/
//
//			if(StringUtils.isNotBlank(startTime)){
//				start = LocalDateTime.parse(startTime+" 00:00:00",df);
//			}
//			
//			if(StringUtils.isNotBlank(endTime)){
//				end =	LocalDateTime.parse(endTime+" 23:59:59",df);
//			}
//
//
//	        PageInfo<TransformerEvaluateDataVo2> pageInfo = transformerEvaluateDataService.page(mainTreeId,start,  end, page,  limit);
//	        return ResultUtil.put(ConstantUtil.REQUEST_SUCCESS, pageInfo.getTotal(), "", pageInfo.getList());
//	    }
	 

	/**
	 * 添加 离线数据--GIS开关试验数据
	 *
	 * @param token
	 *            the token
	 * @param busiOutlineGisExperimentDataDto
	 *            离线数据--GIS开关试验数据Dto
	 * @return map map
	 */
	@ApiOperation(value = "GIS开关试验数据添加")
	@KerLog(projectName = "PROJECTNAME", modelName = "BUSIOUTLINEGISEXPERIMENTDATA.MODELNAME", methodName = "BUSIOUTLINEGISEXPERIMENTDATA.METHODNAME.ADDBUSIOUTLINEGISEXPERIMENTDATA")
	@PostMapping(value = "/addBusiOutlineGisExperimentData", produces = { "application/json;charset=utf-8" })
//	@KerValid
//	@KerPermission("")
	public Map<String, Object> addBusiOutlineGisExperimentData(String token,
			@RequestBody BusiOutlineGisExperimentDataDto busiOutlineGisExperimentDataDto) {
		int count = busiOutlineGisExperimentDataService.addBusiOutlineGisExperimentData(token,
				busiOutlineGisExperimentDataDto);
		logger.debug("addBusiOutlineGisExperimentData: {}", count);
		Map<String, Object> map = ResultUtil.put(ConstantUtil.REQUEST_SUCCESS, "", "");
		return map;
	}

	/**
	 * 通过id查找 离线数据--GIS开关试验数据
	 *
	 * @param id
	 *            id
	 * @return map map
	 */
	@ApiOperation(value = "通过id查找GIS开关试验数据")
	@KerLog(projectName = "PROJECTNAME", modelName = "BUSIOUTLINEGISEXPERIMENTDATA.MODELNAME", methodName = "BUSIOUTLINEGISEXPERIMENTDATA.METHODNAME.FINDBUSIOUTLINEGISEXPERIMENTDATA")
	@GetMapping(value = "/findBusiOutlineGisExperimentData/{id}", produces = { "application/json;charset=utf-8" })
//	@KerPermission("")
	public Map<String, Object> findBusiOutlineGisExperimentData(@PathVariable(value = "id") String id) {
		BusiOutlineGisExperimentData busiOutlineGisExperimentData = busiOutlineGisExperimentDataService
				.findBusiOutlineGisExperimentData(id);
		return ResultUtil.put(ConstantUtil.REQUEST_SUCCESS, "", busiOutlineGisExperimentData);
	}

	/**
	 * 修改 离线数据--GIS开关试验数据
	 *
	 * @param token
	 *            the token
	 * @param busiOutlineGisExperimentDataDto
	 *            离线数据--GIS开关试验数据Dto
	 * @return the map
	 */
	@ApiOperation(value = "GIS开关试验修改")
	@KerLog(projectName = "PROJECTNAME", modelName = "BUSIOUTLINEGISEXPERIMENTDATA.MODELNAME", methodName = "BUSIOUTLINEGISEXPERIMENTDATA.METHODNAME.UPDATEBUSIOUTLINEGISEXPERIMENTDATA")
	@PostMapping(value = "/updateBusiOutlineGisExperimentData", produces = { "application/json;charset=utf-8" })
//	@KerPermission("")
	public Map<String, Object> updateBusiOutlineGisExperimentData(String token,
			@RequestBody BusiOutlineGisExperimentDataDto busiOutlineGisExperimentDataDto) {
		int count = busiOutlineGisExperimentDataService.updateBusiOutlineGisExperimentData(token,
				busiOutlineGisExperimentDataDto);
		logger.debug("updateBusiOutlineGisExperimentData: {}", count);
		Map<String, Object> map = ResultUtil.put(ConstantUtil.REQUEST_SUCCESS, "", "");
		return map;
	}

	/**
	 * 删除 离线数据--GIS开关试验数据
	 *
	 * @param token
	 *            the token
	 * @param busiOutlineGisExperimentDataDto
	 *            离线数据--GIS开关试验数据Dto
	 * @return map map
	 */
	@ApiOperation(value = "GIS开关试验删除")
	@KerLog(projectName = "PROJECTNAME", modelName = "BUSIOUTLINEGISEXPERIMENTDATA.MODELNAME", methodName = "BUSIOUTLINEGISEXPERIMENTDATA.METHODNAME.DELETEBUSIOUTLINEGISEXPERIMENTDATA")
	@PostMapping(value = "/deleteBusiOutlineGisExperimentData", produces = { "application/json;charset=utf-8" })
//	@KerPermission("")
	public Map<String, Object> deleteBusiOutlineGisExperimentData(String token, @RequestBody String[] ids) {
		busiOutlineGisExperimentDataService.deleteBusiOutlineGisExperimentData(ids);
		Map<String, Object> map = ResultUtil.put(ConstantUtil.REQUEST_SUCCESS, "", "");
		return map;
	}

	/**
	 * 查看例行实验
	 * @param equipmentId
	 * @param siteId
	 * @return
	 */
	@ApiOperation(value = "查看例行实验")
	@KerLog(projectName = "PROJECTNAME", modelName = "BUSIOUTLINETRANSFORMEREXPERIMENTDATA.MODELNAME", methodName = "BUSIOUTLINETRANSFORMEREXPERIMENTDATA.METHODNAME.FINDBUSIOUTLINEDATABYEQUIP")
	@GetMapping(value = "/findBusiOutlineTransformerExperimentData", produces = {
			"application/json;charset=utf-8" })
//	@KerPermission("")
	public Map<String, Object> findBusiOutlineDataByEquip(@PathVariable(value = "equipmentId") String equipmentId, @PathVariable(value = "siteId") String siteId) {
		BusiOutlineGisExperimentData busiOutlineGisExperimentData = busiOutlineGisExperimentDataService.findBusiOutlineDataByEquip(equipmentId, siteId);
		return ResultUtil.put(ConstantUtil.REQUEST_SUCCESS, "", busiOutlineGisExperimentData);
	}
	
	/**
   	 * @Title: GIS评测-数据导出
   	 * @Description: 
   	 * @param response
   	 * @param request
   	 * @param params
   	 * @throws IOException
   	 */
   	@SuppressWarnings("unchecked")
   	@ApiOperation(value = "GIS评测数据导出")
   	@GetMapping("/exportGisExperimentData")
   	public void exportGisExperimentData(HttpServletResponse response , HttpServletRequest request,@RequestParam(value = "mainTreeId", required = true) String mainTreeId, @RequestParam(value = "startTime", required = false) String startTime, @RequestParam(value = "endTime", required = false) String endTime) throws IOException {
   		DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
	   	LocalDateTime start = null ;
	   	LocalDateTime end = null ;
		if (StringUtils.isNotBlank(startTime)) {
			start = LocalDateTime.parse(startTime+" 00:00:00",df);
		}		
		if (StringUtils.isNotBlank(endTime)) {
			end = LocalDateTime.parse(endTime+" 23:59:59",df);
		}
   		Map<String,Object> resultMap = busiOutlineGisExperimentDataService.exportGisExperimentData(mainTreeId,start,end);
   		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();
   	}
}