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.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
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.common.util.Tools;
import com.huatek.busi.constant.ApiConstant.Tags;
import com.huatek.busi.dto.BusiEvaMonitorConfigDto;
import com.huatek.busi.service.BusiEvaMonitorConfigService;
import com.huatek.busi.vo.BusiEvaMonitorConfigVo;
import com.huatek.busi.vo.BusiEvaMonitorEquipmentVo;
import com.huatek.busi.vo.BusiEvaMonitorUnitIndicatorsVo;
import com.huatek.busi.vo.BusiEvaMonitorUnitVo;
import com.huatek.busi.vo.BusiSensorVo;
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;

/**
 * 考评指标配置 控制层
 *
 * @author anker_cheng
 * @date Jul 23, 2019 9:50:14 AM
 */
@Api(tags = {Tags.BUSI_EVA_MONITOR})
@Slf4j
@RestController
@RequestMapping("/api/BusiEvaMonitorConfig")
public class BusiEvaMonitorConfigController {

    @Reference(check = false)
    private BusiEvaMonitorConfigService busiEvaMonitorConfigService;

    // ************************************************************************\\
    /**
     * 获取监测设备(类型)名称列表
     * 
     * @return
     */
    @ApiOperation(value = "获取监测设备(类型)名称列表", response = BusiEvaMonitorEquipmentVo.class)
    @GetMapping(value = "/monitorEquipTypeList", produces = {"application/json;charset=utf-8"})
    public Map<String, Object> monitorEquipTypeList() {
        List<BusiEvaMonitorEquipmentVo> busiEvaEquipList =
            busiEvaMonitorConfigService.findBusiEvaMonitorEquipmentList();
        return ResultUtil.put(ConstantUtil.REQUEST_SUCCESS, "", busiEvaEquipList);
    }

    /**
     * 获取监测单元列表
     * 
     * @param equipTypeId
     *            监测设备（类型）ID
     * @return
     */
    @ApiOperation(value = "获取监测单元列表", response = BusiEvaMonitorUnitVo.class)
    @ApiImplicitParam(name = "equipTypeId", value = "监测设备（类型）ID")
    @GetMapping(value = "/monitorUnitList", produces = {"application/json;charset=utf-8"})
    public Map<String, Object> monitorUnitList(@RequestParam("equipTypeId") final String equipTypeId) {
        List<BusiEvaMonitorUnitVo> busiMonitorUnitList =
            busiEvaMonitorConfigService.findBusiEvaMonitorUnitList(equipTypeId);
        return ResultUtil.put(ConstantUtil.REQUEST_SUCCESS, "", busiMonitorUnitList);
    }

    /**
     * 获取单元考核指标列表
     * 
     * @param unitId
     *            监测单元
     * @return
     */
    @ApiOperation(value = "获取单元考核指标列表", response = BusiEvaMonitorUnitIndicatorsVo.class)
    @ApiImplicitParam(name = "unitId", value = "监测单元ID")
    @GetMapping(value = "/monitorIndicators", produces = {"application/json;charset=utf-8"})
    public Map<String, Object> monitorIndicators(@RequestParam("unitId") final String unitId) {
        List<BusiEvaMonitorUnitIndicatorsVo> busiEvaMonitorUnitIndicators =
            busiEvaMonitorConfigService.findBusiEvaMonitorUnitIndicators(unitId);
        return ResultUtil.put(ConstantUtil.REQUEST_SUCCESS, "", busiEvaMonitorUnitIndicators);
    }

    @ApiOperation(value = "获取传感器列表", response = BusiSensorVo.class)
    @ApiImplicitParams({
        @ApiImplicitParam(name = "evaEpTypeId", value = "获取监测设备(类型)名称ID"),
        @ApiImplicitParam(name = "unitId", value = "监测单元ID")
    })
    @GetMapping(value = "/sensorList", produces = {"application/json;charset=utf-8"})
    public Map<String, Object> sensorList(@RequestParam("evaEpTypeId") final String evaMonitorEquipmentTypeId,
        @RequestParam("unitId") final String evaMonitorUnitId) {
        List<BusiSensorVo> sensorList =
            busiEvaMonitorConfigService.findSensorList(evaMonitorEquipmentTypeId, evaMonitorUnitId);
        return ResultUtil.put(ConstantUtil.REQUEST_SUCCESS, "", sensorList);
    }

    // ************************************************************************\\
    /**
     * 考评指标配置 分页列表
     *
     * @param busiEvaMonitorConfigDto
     *            考评指标配置Dto
     * @return map map
     */
    @ApiOperation(value = "分页查询", response = BusiEvaMonitorConfigVo.class)
    @PostMapping(value = "/queryList", produces = {"application/json;charset=utf-8"})
    public Map<String, Object> queryList(@RequestBody BusiEvaMonitorConfigDto busiEvaMonitorConfigDto) {
        PageInfo<BusiEvaMonitorConfigVo> pageInfo =
            busiEvaMonitorConfigService.findBusiEvaMonitorConfigPage(busiEvaMonitorConfigDto);
        return ResultUtil.put(ConstantUtil.REQUEST_SUCCESS, pageInfo.getTotal(), "", pageInfo.getList());
    }

    /**
     * 添加 考评指标配置
     *
     * @param token
     *            the token
     * @param busiEvaMonitorConfigDto
     *            考评指标配置Dto
     * @return map map
     */
    @ApiOperation(value = "添加考评指标配置")
    @PostMapping(value = "/addBusiEvaMonitorConfig", produces = {"application/json;charset=utf-8"})
    public Map<String, Object> addBusiEvaMonitorConfig(@RequestHeader("token")String token,
        @RequestBody BusiEvaMonitorConfigDto busiEvaMonitorConfigDto) {
        int count = busiEvaMonitorConfigService.saveOrUpdate(token, busiEvaMonitorConfigDto);
        log.debug("addBusiEvaMonitorConfig: {}", count);
        return ResultUtil.put(ConstantUtil.REQUEST_SUCCESS, "", "");
    }

    /**
     * 通过id查找 考评指标配置
     *
     * @param id
     *            id
     * @return map map
     */
    @ApiOperation(value = "通过id查找 考评指标配置")
    @GetMapping(value = "/findBusiEvaMonitorConfig/{id}", produces = {"application/json;charset=utf-8"})
    public Map<String, Object> findBusiEvaMonitorConfig(@PathVariable(value = "id") String id) {
        BusiEvaMonitorConfigVo vo = busiEvaMonitorConfigService.findBusiEvaMonitorConfigVo(id);
        return ResultUtil.put(ConstantUtil.REQUEST_SUCCESS, "", vo);
    }

    /**
     * 修改 考评指标配置
     *
     * @param token
     *            the token
     * @param busiEvaMonitorConfigDto
     *            考评指标配置Dto
     * @return the map
     */
    @ApiOperation(value = "修改 考评指标配置")
    @PostMapping(value = "/updateBusiEvaMonitorConfig", produces = {"application/json;charset=utf-8"})
    public Map<String, Object> updateBusiEvaMonitorConfig(@RequestHeader("token")String token,
        @RequestBody BusiEvaMonitorConfigDto busiEvaMonitorConfigDto) {
        int count = busiEvaMonitorConfigService.saveOrUpdate(token, busiEvaMonitorConfigDto);
        log.debug("updateBusiEvaMonitorConfig: {}", count);
        return ResultUtil.put(ConstantUtil.REQUEST_SUCCESS, "", "");
    }

    /**
     * 删除 考评指标配置
     *
     * @param token
     *            the token
     * @param busiEvaMonitorConfigDto
     *            考评指标配置Dto
     * @return map map
     */
    @ApiOperation("删除考评指标配置")
    @ApiImplicitParam(name = "id", value = "数据ID", allowMultiple = true)
    @PostMapping(value = "/deleteBusiEvaMonitorConfig", produces = {"application/json;charset=utf-8"})
    public Map<String, Object> deleteBusiEvaMonitorConfig(@RequestHeader("token")String token, @RequestParam("id") String[] ids) {
        int count = busiEvaMonitorConfigService.deleteBusiEvaMonitorConfig(token, ids);
        log.debug("deleteBusiEvaMonitorConfig: {}", count);
        return ResultUtil.put(ConstantUtil.REQUEST_SUCCESS, "", "");
    }
    
	/**
	 * @Title: 导出考评指标
	 * @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("/exportBusiEvaMonitorConfig")
	public void exportCacList(HttpServletResponse response , HttpServletRequest request,@RequestParam Map<String, Object> params) throws IOException {
		request.setCharacterEncoding("UTF-8");
		BusiEvaMonitorConfigDto aBusiEvaMonitorConfigDto = Tools.mapToBean(params, BusiEvaMonitorConfigDto.class);
		Map<String,Object> resultMap = busiEvaMonitorConfigService.exportBusiEvaMonitorConfig(aBusiEvaMonitorConfigDto);
		String title = resultMap.get("title").toString();
		String fileName =  resultMap.get("fileName").toString();
		List <Object> list= (List<Object>) resultMap.get("data");
		if (CollectionUtils.isEmpty(list)) {
			log.warn("==> " + title + ":无数据导出.");
			Object[] options = { "确定"}; 
			JOptionPane.showOptionDialog(null, "导出考评指标数据为空", "提示", JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE,null, options, options[0]);
			return;
		}
		OutputStream out = response.getOutputStream();
		response.reset();
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Content-Type","application/msexcel");
		fileName = new String(fileName.getBytes("gb2312"), "iso8859-1");
		response.setHeader("Content-disposition","attachment; filename="+fileName+".xls");
		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 sensorId  传感器编号
     * @return
     */
    @ApiOperation(value = "获取单元考核指标列表", response = BusiEvaMonitorUnitIndicatorsVo.class)
    @ApiImplicitParam(name = "unitId", value = "监测单元ID")
    @GetMapping(value = "/monitorIndicators/{sensorId}", produces = {"application/json;charset=utf-8"})
    public Map<String, Object> sensorMonitorIndicatorsList(@PathVariable("sensorId") final String sensorId) {
        List<BusiEvaMonitorUnitIndicatorsVo> busiEvaMonitorUnitIndicators =
            busiEvaMonitorConfigService.findBusiEvaMonitorUnitIndicatorsList(sensorId);
        return ResultUtil.put(ConstantUtil.REQUEST_SUCCESS, "", busiEvaMonitorUnitIndicators);
    }
}
