package com.huatek.busi.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import com.huatek.busi.common.util.ExcelExport;
import com.huatek.busi.common.valid.ValidUtil;
import com.huatek.busi.service.transformer.TransformerEvaluateDataService;
import com.huatek.busi.vo.TransformerEvaluateDataVo;
import com.huatek.busi.vo.TransformerEvaluateDataVo2;
import com.huatek.torch.frame.tools.ConstantUtil;
import com.huatek.torch.frame.tools.ResultUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
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;

@Api(tags = { "变压器评测数据" })
@Slf4j
@RestController
@RequestMapping("/api/transformerEvaluateData")
public class TransformerEvaluateDataController {

	
	@Reference(check = false)
	private  TransformerEvaluateDataService transformerEvaluateDataService;
	
	/**
	 * @Title: info
	 * @Description: 变压器评测数据详情
	 * @createDate: Aug 27, 2019 6:56:13 PM
	 * @param  id  例行试验ID
	 * @return Map<String,Object>
	 */
	@ApiOperation(value = "变压器评测数据详情")
	@ApiImplicitParam(name = "id", value = "例行试验ID")
	@GetMapping(value = "/info", produces = { "application/json;charset=utf-8" })
	public Map<String, Object> info( @RequestParam ("id")String id) {
		TransformerEvaluateDataVo vo = transformerEvaluateDataService.info(id);
		log.debug("info: {}", vo);
		return ResultUtil.put(ConstantUtil.REQUEST_SUCCESS, "", vo);
	}
	
	
	/**
	 * @Title: add
	 * @Description: 新增变压器评测数据
	 * @createDate: Aug 27, 2019 6:56:13 PM
	 * @param  vo
	 * @return Map<String,Object>
	 */
	@ApiOperation(value = "新增变压器评测数据")
	@PostMapping(value = "/add", produces = { "application/json;charset=utf-8" })
	public Map<String, Object> add(String token, @Valid @RequestBody TransformerEvaluateDataVo vo, BindingResult result) {
	    if(result.hasErrors()) {
	        return ValidUtil.validError(result);
	    }
		boolean flag = transformerEvaluateDataService.save(token, vo);
		log.debug("新增变压器评测数据: {}", flag);
		return ResultUtil.put(ConstantUtil.REQUEST_SUCCESS, flag ? "新增变压器评测数据成功" :"新增变压器评测数据失败" , "");
	}
	
	/**
	 * @Title: update
	 * @Description: 修改变压器例行试验
	 * @createDate: Aug 27, 2019 6:56:13 PM
	 * @param  vo
	 * @return Map<String,Object>
	 */
	@ApiOperation(value = "修改变压器评测数据")
	@PostMapping(value = "/update", produces = { "application/json;charset=utf-8" })
	public Map<String, Object> update(String token, @RequestBody TransformerEvaluateDataVo vo) {
		boolean flag = transformerEvaluateDataService.update(token, vo);
		log.debug("修改变压器例行试验: {}", flag);
		return ResultUtil.put(ConstantUtil.REQUEST_SUCCESS, flag ? "修改评测数据成功" :"修改评测数据失败" , "");
	}
	
    /** 
    * @Title: delete 
    * @Description:删除 变压器例行试验
    * @createDate: Aug 28, 2019 3:29:50 PM
    * @param    ids  主键集合
    * @return   Map<String,Object>    
    */ 
    @ApiOperation(value = "删除变压器评测数据")
    @PostMapping(value = "/delete", produces = {"application/json;charset=utf-8"})
    public Map<String, Object> delete(@RequestHeader("token") String token,
        @RequestBody List<String> ids) {
        int count = transformerEvaluateDataService.delete(token, ids);
        log.debug("删除变压器评测数据: {}", count);
        return ResultUtil.put(ConstantUtil.REQUEST_SUCCESS, count >0  ?"删除评测数据成功" :"删除评测数据失败", "");
    }
	
    /** 
    * @Title: page 
    * @Description: 变压器例行试验列表分页 
    * @createDate: Aug 28, 2019 5:35:41 PM
    * @param    name
    * @param    page
    * @param    limit
    * @return   Map<String,Object>    
    */ 
    @ApiOperation(value = "变压器评测数据列表分页")
    @ApiImplicitParams({
    	@ApiImplicitParam(name = "mainTreeId", value = "变压器站点树ID", required = false),
        @ApiImplicitParam(name = "startTime", value = "开始时间", required = false),
        @ApiImplicitParam(name = "endTime", value = "结束时间", required = false),
        @ApiImplicitParam(name = "page", value = "当前页", required = false),
        @ApiImplicitParam(name = "limit", value = "每页大小", required = false)
    })
    @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());
    }

    /**
   	 * @Title: 变压器评测-数据导出
   	 * @Description: 
   	 * @param response
   	 * @param request
   	 * @param params
   	 * @throws IOException
   	 */
   	@SuppressWarnings("unchecked")
   	@ApiOperation(value = "变压器评测数据导出")
   	@GetMapping("/exportTransformerEvaluateData")
   	public void exportTransformerEvaluateData(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 = transformerEvaluateDataService.exportTransformerEvaluateData(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();
   	}
}
