package com.unis.detectionnum.server.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.unis.common.utils.ResponseWrapper;
import com.unis.detectionnum.common.vo.CableVO;
import com.unis.detectionnum.common.vo.DetectionWaterHistoryVO;
import com.unis.detectionnum.common.vo.DetectionWaterReportVO;
import com.unis.detectionnum.server.service.DetectionWaterService;

import com.unis.detectionnum.server.utils.ExcelUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import org.apache.poi.hpsf.ClassID;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.*;

/**
 * @Description 水分数据检测控制类
 * @Package: com.unis.detectionnum.server.controller
 * @Author: LiuFeng
 * @Description:
 * @Date: Created in 2019/8/14
 */

@Controller
@Api("水分检测管理")
public class DetectionWaterController {

    private static final Logger log = LoggerFactory.getLogger(DetectionWaterController.class);

    @Autowired
    private DetectionWaterService waterSevice;

    @ApiOperation(value = "读取水分数据接口")
    @RequestMapping(value = "/detection/water/readData", method = RequestMethod.GET)
    @ResponseBody
    public ResponseWrapper readWaterData(HttpServletRequest request) {

        try {
        	if(waterSevice.readWaterData() > 0) {
        		return ResponseWrapper.success(HttpStatus.OK.value(), "新增成功", null);
        	}
        	return ResponseWrapper.error(HttpStatus.INTERNAL_SERVER_ERROR.value(),"读取失败",null);
        } catch (Exception e) {
            log.error("DetectionWaterController.readWaterData", e);
			return ResponseWrapper.error(HttpStatus.INTERNAL_SERVER_ERROR.value(),"读取失败",null);
        }

    }
    
    @ApiOperation(value = "读取水分数据详细信息接口")
    @RequestMapping(value = "/detection/water/info/{cfbh}", method = RequestMethod.GET)
    @ResponseBody
    public ResponseWrapper getDetectionDataInfo(@PathVariable("cfbh") String cfbh) {

        try {
        	//waterSevice.getDetectionDataInfo(cfbh);
        	return ResponseWrapper.success(HttpStatus.OK.value(), "查询成功", waterSevice.readWaterData());
        	
        } catch (Exception e) {
            log.error("DetectionWaterController.readWaterData", e);
			return ResponseWrapper.error(HttpStatus.INTERNAL_SERVER_ERROR.value(),"案件处理信息参数为空",null);
        }

    }
    
    @ApiOperation(value = "根据仓房编号获取水分检测报告")
    @RequestMapping(value = "/detection/water/report/{cfbh}/{historyId}", method = RequestMethod.GET)
    @ResponseBody
    public ResponseWrapper getDetectionWaterReport(@PathVariable("cfbh") String cfbh,@PathVariable("historyId") Integer historyId) {

        try {
        	
        	return ResponseWrapper.success(HttpStatus.OK.value(), "查询成功", waterSevice.getDetectionWaterReport(cfbh,historyId));
        	
        } catch (Exception e) {
            log.error("DetectionWaterController.readWaterData", e);
			return ResponseWrapper.error(HttpStatus.INTERNAL_SERVER_ERROR.value(),"案件处理信息参数为空",null);
        }

    }
    
	@ApiOperation(value = "根据仓房编号获取水分检测报告")
	@RequestMapping(value = "/detection/water/report/{cfbh}.html", method = RequestMethod.GET)
	public String WaterReportView(Model model, @PathVariable("cfbh") String cfbh,@RequestParam(value = "historyId",required = false) Integer historyId) {

		DetectionWaterReportVO reportVO = waterSevice.getDetectionWaterReport(cfbh,historyId);
		if (reportVO != null) {
			model.addAttribute("report", reportVO);
			String reportDatas  = null;
	        //禁用引用对象
			reportDatas = JSON.toJSONString(reportVO.getCableDatas(),
	                                        SerializerFeature.PrettyFormat,
	                                        SerializerFeature.DisableCircularReferenceDetect);
	        log.info(reportDatas);

			model.addAttribute("reportDatas",JSON.parseArray(reportDatas));
		} else {
			model.addAttribute("report", new DetectionWaterReportVO());
		}

		return "humitureDetection";
	}
	
	@ApiOperation(value = "根据仓房编号获取水分检测历史记录数据")
	@RequestMapping(value = "/detection/water/history/{cfbh}.html", method = RequestMethod.GET)
	public String waterHistoryView(Model model, @PathVariable("cfbh") String cfbh,
                                   @RequestParam(value = "pageNum",defaultValue = "1") Integer  pageNum,
                                   @RequestParam(value = "time" ,required = false) String time) {

		@SuppressWarnings("unused")
		PageInfo<DetectionWaterHistoryVO> voPageInfos = new PageInfo<>();
		PageHelper.startPage(pageNum,10);
		List<DetectionWaterHistoryVO> historyVOs = waterSevice.getWaterHistory(cfbh, time);



		PageInfo<DetectionWaterHistoryVO> pageInfos = new PageInfo<DetectionWaterHistoryVO>(historyVOs);
		model.addAttribute("historyVOs", pageInfos);

		return "historyDetection";
	}
	
	@ApiOperation(value = "根据仓房编号获取水分检测报告")
	@RequestMapping(value = "/detection/water/login.html", method = RequestMethod.GET)
	public String login(Model model) {

		return "login";
	}


	@ApiOperation(value = "根据仓房编号获取水分/温度数据")
	@RequestMapping(value = "/detection/water/reports/{cfbh}.html", method = RequestMethod.GET)
	public String getWaterTempView(Model model, @PathVariable("cfbh") String cfbh) {
		Map<String, Object> resultMap = waterSevice.getWaterTempView(cfbh);
		model.addAttribute("resultMap",resultMap);
		return "temperatureOrWater";
	}

    @ApiOperation(value = "导出")
    @RequestMapping(value = "/detection/water/impots/{cfbh}/{historyId}", method = RequestMethod.GET)
    public String export(@PathVariable("cfbh") String cfbh, @PathVariable("historyId") String historyId, HttpServletResponse response) throws Exception {
        Integer historyid = Integer.valueOf(historyId);
        String export="";
        export ="测温测水信息表.xls";
        List<CableVO> talentStoreVOList = waterSevice.selectDatasByCfbh(cfbh,historyid);
      /*  List<CableVO> oblist=talentStoreVOList.get();*/
        HSSFWorkbook wb = ExcelUtils.custodyNewBook(export,talentStoreVOList);
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + new String((export).getBytes(), "ISO8859-1"));//设定输出文件头
        OutputStream ouputStream = response.getOutputStream();
        wb.write(ouputStream);
        
        ouputStream.flush();
        ouputStream.close();

        return null;

    }
    
    
}
