package com.yeejoin.amos.boot.module.jxiop.biz.controller;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.biz.common.controller.BaseController;
import com.yeejoin.amos.boot.biz.common.utils.DateUtils;
import com.yeejoin.amos.boot.module.jxiop.biz.Enum.HealthLevelSortEnum;
import com.yeejoin.amos.boot.module.jxiop.biz.Enum.WarningPeriodEnum;
import com.yeejoin.amos.boot.module.jxiop.biz.dto.IdxBizPvHealthIndexDto;
import com.yeejoin.amos.boot.module.jxiop.biz.entity.IdxBizFanPointProcessVariableClassification;
import com.yeejoin.amos.boot.module.jxiop.biz.entity.IdxBizPvPointProcessVariableClassification;
import com.yeejoin.amos.boot.module.jxiop.biz.entity.IdxBizPvWarningRecord;
import com.yeejoin.amos.boot.module.jxiop.biz.mapper2.IdxBizFanPointProcessVariableClassificationMapper;
import com.yeejoin.amos.boot.module.jxiop.biz.mapper2.IdxBizPvPointProcessVariableClassificationMapper;
import com.yeejoin.amos.boot.module.jxiop.biz.service.IPermissionService;
import com.yeejoin.amos.boot.module.jxiop.biz.service.impl.IdxBizPvHealthIndexServiceImpl;
import com.yeejoin.amos.boot.module.jxiop.biz.tdMapper2.*;
import com.yeejoin.amos.boot.module.jxiop.biz.tdengine.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.restful.doc.TycloudOperation;
import org.typroject.tyboot.core.restful.utils.ResponseHelper;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

import javax.servlet.http.HttpServletRequest;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 *
 *
 * @author system_generator
 * @date 2023-08-15
 */
@RestController
@Api(tags = "Api")
@RequestMapping(value = "/idx-biz-pv-health-index")
public class IdxBizPvHealthIndexController extends BaseController {

    @Autowired
    IdxBizPvHealthIndexServiceImpl idxBizPvHealthIndexServiceImpl;
    @Autowired
	PvHealthIndexDayMapper pvHealthIndexDayMapper;
	@Autowired
	PvHealthIndexHourMapper pvHealthIndexHourMapper;
	@Autowired
	PvHealthIndexMomentMapper pvHealthIndexMomentMapper;
	@Autowired
	PvWaringRecordMapper pvWaringRecordMapper;
	@Autowired
	IPermissionService permissionService;


	@Autowired
	IdxBizPvPointProcessVariableClassificationMapper idxBizPvPointProcessVariableClassificationMapper;

	public final DecimalFormat df = new DecimalFormat("0.0");

	public final DecimalFormat dfSS = new DecimalFormat("0.00");
    /**
     * 新增
     *
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
	@PostMapping(value = "/save")
	@ApiOperation(httpMethod = "POST", value = "新增", notes = "新增")
	public ResponseModel<IdxBizPvHealthIndexDto> save(@RequestBody IdxBizPvHealthIndexDto model) {
	    model = idxBizPvHealthIndexServiceImpl.createWithModel(model);
	    return ResponseHelper.buildResponse(model);
	}

	/**
     * 根据sequenceNbr更新
     *
     * @param sequenceNbr 主键
     * @return
     */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@PutMapping(value = "/{sequenceNbr}")
	@ApiOperation(httpMethod = "PUT", value = "根据sequenceNbr更新", notes = "根据sequenceNbr更新")
	public ResponseModel<IdxBizPvHealthIndexDto> updateBySequenceNbrIdxBizPvHealthIndex(@RequestBody IdxBizPvHealthIndexDto model,@PathVariable(value = "sequenceNbr") String sequenceNbr) {
	    model.setSequenceNbr(sequenceNbr);
	    return ResponseHelper.buildResponse(idxBizPvHealthIndexServiceImpl.updateWithModel(model));
	}

	/**
     * 根据sequenceNbr删除
     *
     * @param sequenceNbr 主键
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @DeleteMapping(value = "/{sequenceNbr}")
    @ApiOperation(httpMethod = "DELETE", value = "根据sequenceNbr删除", notes = "根据sequenceNbr删除")
    public ResponseModel<Boolean> deleteBySequenceNbr(HttpServletRequest request, @PathVariable(value = "sequenceNbr") Long sequenceNbr){
        return ResponseHelper.buildResponse(idxBizPvHealthIndexServiceImpl.removeById(sequenceNbr));
    }

    /**
     * 根据sequenceNbr查询
     *
	 * @param sequenceNbr  主键
     * @return
     */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/{sequenceNbr}")
	@ApiOperation(httpMethod = "GET",value = "根据sequenceNbr查询单个",  notes = "根据sequenceNbr查询单个")
	public ResponseModel<IdxBizPvHealthIndexDto> selectOne(@PathVariable Long sequenceNbr) {
	    return ResponseHelper.buildResponse(idxBizPvHealthIndexServiceImpl.queryBySeq(sequenceNbr));
	}

	/**
     * 列表分页查询
     *
     * @param current 当前页
     * @param current 每页大小
     * @return
     */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/page")
	@ApiOperation(httpMethod = "GET",value = "分页查询",  notes = "分页查询")
	public ResponseModel<Page<IdxBizPvHealthIndexDto>> queryForPage(@RequestParam(value = "current") int current,@RequestParam
                    (value = "size") int size) {
	    Page<IdxBizPvHealthIndexDto> page = new Page<IdxBizPvHealthIndexDto>();
	    page.setCurrent(current);
	    page.setSize(size);
	    return ResponseHelper.buildResponse(idxBizPvHealthIndexServiceImpl.queryForIdxBizPvHealthIndexPage(page));
	}

	/**
	 * 列表全部数据查询
     *
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(httpMethod = "GET",value = "列表全部数据查询",   notes = "列表全部数据查询")
	@GetMapping(value = "/list")
	public ResponseModel<List<IdxBizPvHealthIndexDto>> selectForList() {
	    return ResponseHelper.buildResponse(idxBizPvHealthIndexServiceImpl.queryForIdxBizPvHealthIndexList());
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY,needAuth = false)
	@ApiOperation(httpMethod = "GET",value = "预警监测设备级左侧列表",   notes = "预警监测设备级左侧列表")
	@GetMapping(value = "/queryForLeftTableListByEquip")
	public ResponseModel<Page<Map<String,Object>>> queryForLeftTableListByEquip(@RequestParam(required = false) String STATION, @RequestParam(required = false) String SUBARRAY, @RequestParam(required = false) String HEALTHLEVEL, @RequestParam(required = false) String EQUIPMENTNAME, @RequestParam(required = false) Integer current, @RequestParam(required = false) Integer size ) {
		Page<Map<String,Object>> page = new Page<Map<String,Object>>();
		page.setCurrent(current);
		page.setSize(size);
		int total = idxBizPvHealthIndexServiceImpl.queryForLeftTableListByEquipCount(STATION, SUBARRAY, HEALTHLEVEL,EQUIPMENTNAME);
		Long num = Long.valueOf(total);
		page.setTotal(num);
		page.setRecords(idxBizPvHealthIndexServiceImpl.queryForLeftTableListByEquip(STATION,SUBARRAY,HEALTHLEVEL,EQUIPMENTNAME,(current-1)*size,size));
		return ResponseHelper.buildResponse(page);
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY,needAuth = false)
	@ApiOperation(httpMethod = "GET",value = "预警监测测点级左侧列表",   notes = "预警监测设备级左侧列表")
	@GetMapping(value = "/queryForLeftTableListByPoint")
	public ResponseModel<Page<Map<String,Object>>> queryForLeftTableListByPoint(@RequestParam(required = false) String STATION,@RequestParam(required = false) String SUBARRAY,@RequestParam(required = false) String HEALTHLEVEL,@RequestParam(required = false) String EQUIPMENTNAME,@RequestParam(required = false) String POINTNAME,@RequestParam(required = false) Integer current,@RequestParam(required = false) Integer size) {
		Page<Map<String,Object>> page = new Page<Map<String,Object>>();
		page.setCurrent(current);
		page.setSize(size);
		int total = idxBizPvHealthIndexServiceImpl.queryForLeftTableListByPointCount(STATION, SUBARRAY, HEALTHLEVEL, EQUIPMENTNAME, POINTNAME);
		Long num = Long.valueOf(total);
		page.setTotal(num);
		page.setRecords(idxBizPvHealthIndexServiceImpl.queryForLeftTableListByPoint(STATION,SUBARRAY,HEALTHLEVEL,EQUIPMENTNAME,POINTNAME,(current-1)*size,size));
		return ResponseHelper.buildResponse(page);
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY,needAuth = false)
	@ApiOperation(httpMethod = "GET",value = "预警监测设备级仪表盘",   notes = "预警监测设备级仪表盘")
	@GetMapping(value = "/queryForLeftTableListByEquipNum")
	public ResponseModel<Map<String,Object>> queryForLeftTableListByEquipNum(@RequestParam(required = false) String STATION, @RequestParam(required = false) String SUBARRAY, @RequestParam(required = false) String HEALTHLEVEL, @RequestParam(required = false) String EQUIPMENTNAME) {

	;
			return ResponseHelper.buildResponse(idxBizPvHealthIndexServiceImpl.queryForLeftTableListByEquipNum(STATION, SUBARRAY, HEALTHLEVEL,EQUIPMENTNAME));
	}


	@TycloudOperation(ApiLevel = UserType.AGENCY,needAuth = false)
	@ApiOperation(httpMethod = "GET",value = "预警监测测点级仪表盘",   notes = "预警监测设备级仪表盘")
	@GetMapping(value = "/queryForLeftTableListByPointNum")
	public ResponseModel<Map<String,Object>> queryForLeftTableListByPointNum(@RequestParam(required = false) String STATION,@RequestParam(required = false) String SUBARRAY,@RequestParam(required = false) String HEALTHLEVEL,@RequestParam(required = false) String EQUIPMENTNAME,@RequestParam(required = false) String POINTNAME) {

		return ResponseHelper.buildResponse(idxBizPvHealthIndexServiceImpl.queryForLeftTableListByPointNum(STATION, SUBARRAY, HEALTHLEVEL, EQUIPMENTNAME, POINTNAME));
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY,needAuth = false)
	@ApiOperation(httpMethod = "GET",value = "预警监测设备级统计",   notes = "预警监测设备级统计")
	@GetMapping(value = "/queryForPointNum")
	public ResponseModel<List<Map<String,Object>>> queryForLeftTableListByPointNum(@RequestParam(required = false) String STATION,@RequestParam(required = false) String SUBARRAY,@RequestParam(required = false) String  EQUIPMENTNAME) {
		List<IdxBizPvWarningRecord> idxBizPvWarningRecordList = idxBizPvHealthIndexServiceImpl.warningData(STATION, SUBARRAY, EQUIPMENTNAME);
		int total = idxBizPvHealthIndexServiceImpl.pointNum(STATION, SUBARRAY, EQUIPMENTNAME);

		Map<String,Object> map =new HashMap<>();
		Map<String,Object> map1 =new HashMap<>();
		Map<String,Object> warningNum =new HashMap<>();
		Map<String,Object> pointNum =new  HashMap<>();

		map1.put("name","危险");
		map1.put("value",idxBizPvWarningRecordList.stream().filter(e->e.getWarningName().equals("危险")).count());
		map.put("name","警告");
		map.put("value",idxBizPvWarningRecordList.stream().filter(e->e.getWarningName().equals("警告")).count());
		warningNum.put("name","注意");
		warningNum.put("value",idxBizPvWarningRecordList.stream().filter(e->e.getWarningName().equals("注意")).count());
		pointNum.put("name","安全");
		pointNum.put("value", Math.max((total - idxBizPvWarningRecordList.size()), 0));

		List<Map<String,Object>> list = new ArrayList<>();
		list.add(pointNum);
		list.add(warningNum);
		list.add(map);
		list.add(map1);

		return ResponseHelper.buildResponse(list);
	}
	@TycloudOperation(ApiLevel = UserType.AGENCY,needAuth = false)
	@ApiOperation(httpMethod = "GET",value = "预警监测设备级统计",   notes = "预警监测设备级统计")
	@GetMapping(value = "/selectPointByANALYSISTYPE")
	public ResponseModel<Map<String,Object>> selectPointByANALYSISTYPE(@RequestParam(required = false) String STATION, @RequestParam(required = false)String HEALTHLEVEL,@RequestParam(required = false) String EQUIPMENTNAME,@RequestParam(required = false)String POINTNAME,@RequestParam(required = false)String SUBARRAY,@RequestParam(required = false)String startTime,@RequestParam(required = false) String endTime) {

		List<Map<String, Object>> maps = idxBizPvHealthIndexServiceImpl.selectPointByANALYSISTYPE(STATION, HEALTHLEVEL, EQUIPMENTNAME, POINTNAME,SUBARRAY,startTime,endTime);
		Map<String,Object> result = new HashMap<>();
		List<Object> seriesData = new ArrayList<>();
		List<Object> axisData = new ArrayList<>();
		Collections.reverse(seriesData);
		Collections.reverse(axisData);

		for (Map<String, Object> map : maps) {
			seriesData.add(map.get("value"));
			axisData.add(map.get("REC_DATE"));
		}

		result.put("seriesData",seriesData);
		result.put("axisData",axisData);
		return ResponseHelper.buildResponse(result);}


	@TycloudOperation(ApiLevel = UserType.AGENCY,needAuth = false)
	@ApiOperation(httpMethod = "GET",value = "TD 光伏场站/设备列表通用接口",   notes = "TD 光伏场站/设备列表通用接口")
	@GetMapping(value = "/pointHealthIndexTable")
	public ResponseModel<Page> pointHealthIndexTable(@RequestParam(value = "area",required = false) String area,
													   @RequestParam(value = "station",required = false) String station,
													   @RequestParam(value = "analysisObjType",required = false) String analysisObjType,
													   @RequestParam(value = "analysisType",required = false) String analysisType,
													   @RequestParam(value = "endTimeTop",required = false) String endTimeTop,
													   @RequestParam(value = "startTimeTop",required = false) String startTimeTop,
													   @RequestParam(value = "indexAddress",required = false) String indexAddress,
													   @RequestParam(value = "pointName",required = false) String pointName,
													   @RequestParam(value = "equipmentName",required = false) String equipmentName,
													   @RequestParam(value = "healthLevel",required = false) String healthLevel,
													   @RequestParam(value = "type",required = false) String type,
													   @RequestParam(value = "requiredType",required = false) String requiredType,
													   @RequestParam(value = "current",required = false) Integer current,
													   @RequestParam(value = "size",required = false) Integer size,
													   @RequestParam(value = "subarray",required = false) String subarray){


		List<String> gatewayIds = permissionService.getCurrentUserAmosOrgCodes();
		String orgCode = "NULL";
		if(gatewayIds.size()>0){
			orgCode =gatewayIds.get(0)+"%";
		}
		if (requiredType.equals(WarningPeriodEnum.DAY.getName())){
			Date startDayTime = DateUtils.getCurrentDayStartTime(new Date());
			Date date = DateUtils.dateAddHours(startDayTime, -9);
			startTimeTop = DateUtil.format(date,DatePattern.NORM_DATETIME_PATTERN);
			List<PvHealthIndexDay> fanHealthIndexDays = pvHealthIndexDayMapper.selectData(station, analysisType, indexAddress, healthLevel, area, analysisObjType, subarray, pointName, startTimeTop, endTimeTop, equipmentName,(current-1)*size,size, orgCode);

			fanHealthIndexDays.forEach(item -> {
				item.setHealthIndex(Double.parseDouble(df.format(item.getHealthIndex())));
			});

			int total = pvHealthIndexDayMapper.selectDataTotal(station, analysisType, indexAddress, healthLevel, area, analysisObjType, subarray, pointName, startTimeTop, endTimeTop, equipmentName, orgCode);
			Page page = new Page<>();
			page.setCurrent(current);
			page.setSize(size);
			page.setRecords(fanHealthIndexDays);
			page.setTotal(total);
			return 	ResponseHelper.buildResponse(page);
		}else if (requiredType.equals(WarningPeriodEnum.HOUR.getName())){
			Date date = new Date();
			date = DateUtil.offsetHour(date,-8);
			date = DateUtil.offsetMinute(date,-59);
			startTimeTop = DateUtil.format(date,DatePattern.NORM_DATETIME_PATTERN);
			List<PvHealthIndexHour> fanHealthIndexHours = pvHealthIndexHourMapper.selectData(healthLevel, area, equipmentName, subarray, analysisType, analysisObjType, station, pointName, indexAddress, startTimeTop, endTimeTop,(current-1)*size,size, orgCode);
			fanHealthIndexHours.forEach(item -> {
				item.setHealthIndex(Double.parseDouble(df.format(item.getHealthIndex())));
			});
			int total = pvHealthIndexHourMapper.selectDataTotal(healthLevel, area, equipmentName, subarray, analysisType, analysisObjType, station, pointName, indexAddress, startTimeTop, endTimeTop, orgCode);

			Page page = new Page<>();
			page.setCurrent(current);
			page.setSize(size);
			page.setRecords(fanHealthIndexHours);
			page.setTotal(total);
			return 	ResponseHelper.buildResponse(page);
		}else {
			Date date = DateUtils.dateAddMinutes(null,-9);
			date = DateUtils.dateAddHours(date, -8);
			SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			startTimeTop = formatter.format(date);
			List<PvHealthIndexMoment> fanHealthIndexMoments = pvHealthIndexMomentMapper.selectData(healthLevel, area, equipmentName, subarray, analysisType, analysisObjType, station, pointName, indexAddress, startTimeTop, endTimeTop,(current-1)*size,size, gatewayIds);
			fanHealthIndexMoments.forEach(item -> {
				item.setHealthIndex(Double.parseDouble(df.format(item.getHealthIndex())));
			});
			Page page = new Page<>();
			page.setCurrent(current);
			page.setSize(size);
			page.setRecords(fanHealthIndexMoments);
			int total = pvHealthIndexMomentMapper.selectDataTotal(healthLevel, area, equipmentName, subarray, analysisType, analysisObjType, station, pointName, indexAddress, startTimeTop, endTimeTop, gatewayIds);
			page.setTotal(total);
			return 	ResponseHelper.buildResponse(page);
		}
	}


	@TycloudOperation(ApiLevel = UserType.AGENCY,needAuth = false)
	@ApiOperation(httpMethod = "GET",value = "仪表盘",   notes = "仪表盘")
	@GetMapping(value = "/pointHealthIndexTableByPanel")
	public ResponseModel<Map<String, Object>> pointHealthIndexTableByPanel(@RequestParam(value = "area",required = false) String area,
													 		@RequestParam(value = "station",required = false) String station,
													 		@RequestParam(value = "analysisObjType",required = false) String analysisObjType,
													 		@RequestParam(value = "analysisType",required = false) String analysisType,
													 		@RequestParam(value = "endTimeTop",required = false) String endTimeTop,
													 		@RequestParam(value = "startTimeTop",required = false) String startTimeTop,
													 		@RequestParam(value = "indexAddress",required = false) String indexAddress,
													 		@RequestParam(value = "pointName",required = false) String pointName,
													 		@RequestParam(value = "equipmentName",required = false) String equipmentName,
													 		@RequestParam(value = "healthLevel",required = false) String healthLevel,
													 		@RequestParam(value = "type",required = false) String type,
													 		@RequestParam(value = "requiredType",required = false) String requiredType,
													 		@RequestParam(value = "current",required = false) Integer current,
													 		@RequestParam(value = "size",required = false) Integer size,
													 		@RequestParam(value = "subarray",required = false) String subarray){


		List<String> gatewayIds = permissionService.getCurrentUserAmosOrgCodes();
		String orgCode = "NULL";
		if(gatewayIds.size()>0){
			orgCode =gatewayIds.get(0)+"%";
		}
		if (requiredType.equals(WarningPeriodEnum.DAY.getName())){
			Date startDayTime = DateUtils.getCurrentDayStartTime(new Date());
			Date date = DateUtils.dateAddHours(startDayTime, -9);
			SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			startTimeTop = formatter.format(date);

			List<PvHealthIndexDay> fanHealthIndexDays = pvHealthIndexDayMapper.selectData(station, requiredType, indexAddress, healthLevel, area, analysisObjType, subarray, pointName, startTimeTop, endTimeTop, equipmentName,(current-1)*size,size, orgCode);

			Map<String,Object> map = new HashMap<>();

			map.put("value", Double.parseDouble(df.format(fanHealthIndexDays.get(0).getHealthIndex())));

			return 	ResponseHelper.buildResponse(map);




		}else if (requiredType.equals(WarningPeriodEnum.HOUR.getName())){

			Date date = new Date();
			date = DateUtil.offsetHour(date,-8);
			date = DateUtil.offsetMinute(date,-59);
			startTimeTop = DateUtil.format(date,DatePattern.NORM_DATETIME_PATTERN);
			List<PvHealthIndexHour> fanHealthIndexHours = pvHealthIndexHourMapper.selectData(station, analysisType, indexAddress, healthLevel, area, analysisObjType, subarray, pointName, startTimeTop, endTimeTop, equipmentName,(current-1)*size,size, orgCode);
			Map<String,Object> map = new HashMap<>();


			map.put("value", Double.parseDouble(df.format(fanHealthIndexHours.get(0).getHealthIndex())));

			return 	ResponseHelper.buildResponse(map);
		}else {
			Date date = DateUtils.dateAddMinutes(null,-9);
			date = DateUtils.dateAddHours(date, -8);
			SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			startTimeTop = formatter.format(date);
			List<PvHealthIndexMoment> fanHealthIndexMoments = pvHealthIndexMomentMapper.selectData(station, analysisType, indexAddress, healthLevel, area, analysisObjType, subarray, pointName, startTimeTop, endTimeTop, equipmentName,(current-1)*size,size, gatewayIds);
			Map<String,Object> map = new HashMap<>();

			map.put("value", Double.parseDouble(df.format(fanHealthIndexMoments.get(0).getHealthIndex())));

			return 	ResponseHelper.buildResponse(map);
		}
	}


	@TycloudOperation(ApiLevel = UserType.AGENCY,needAuth = false)
	@ApiOperation(httpMethod = "GET",value = "TD 光伏折线图",   notes = "TD光伏折线图")
	@GetMapping(value = "/pointHealthIndexTrend")
	public ResponseModel<Object> pointHealthIndexTrend(@RequestParam(value = "area",required = false) String area,
													   @RequestParam(value = "station",required = false) String station,
													   @RequestParam(value = "analysisObjType",required = false) String analysisObjType,
													   @RequestParam(value = "analysisType",required = false) String analysisType,
													   @RequestParam(value = "endTimeTop",required = false) String endTimeTop,
													   @RequestParam(value = "startTimeTop",required = false) String startTimeTop,
													   @RequestParam(value = "indexAddress",required = false) String indexAddress,
													   @RequestParam(value = "pointName",required = false) String pointName,
													   @RequestParam(value = "equipmentName",required = false) String equipmentName,
													   @RequestParam(value = "healthLevel",required = false) String healthLevel,
													   @RequestParam(value = "type",required = false) String type,
													   @RequestParam(value = "requiredType",required = false) String requiredType,
													   @RequestParam(value = "current",required = false) Integer current,
													   @RequestParam(value = "size",required = false) Integer size,
													   @RequestParam(value = "subarray",required = false) String subarray) {

		Map<String,Object> result = new HashMap<>();
		List<Object> seriesData = new ArrayList<>();
		List<Object> axisData = new ArrayList<>();
		List<String> gatewayIds = permissionService.getCurrentUserAmosOrgCodes();
		String orgCode = "NULL";
		if(gatewayIds.size()>0){
			orgCode =gatewayIds.get(0)+"%";
		}
		if (WarningPeriodEnum.DAY.getName().equals(requiredType)){
			SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			if ( null != endTimeTop){
				Date endDate = DateUtils.dateAddHours(DateUtils.longStr2Date(endTimeTop), -8);
				endTimeTop = formatter.format(endDate);
			}

			Date startDate = DateUtils.dateAddHours(DateUtils.longStr2Date(startTimeTop), -8);
			startTimeTop = formatter.format(startDate);

			List<PvHealthIndexDay> fanHealthIndexDays = pvHealthIndexDayMapper.selectData(station, analysisType, indexAddress, healthLevel, area, analysisObjType, subarray, pointName, startTimeTop, endTimeTop, equipmentName, (current - 1) * size, size, orgCode);
			fanHealthIndexDays=	fanHealthIndexDays.stream().sorted(Comparator.comparing(PvHealthIndexDay::getAnalysisTime)).collect(Collectors.toList());

			for (PvHealthIndexDay obj : fanHealthIndexDays) {
				if (type.equals("0")){
					seriesData.add(Double.parseDouble(df.format(obj.getHealthIndex())));
				}else {
					seriesData.add(obj.getAnomaly() > 7.5?7.5:dfSS.format(obj.getAnomaly()));
				}
				axisData.add(obj.getRecDate());
			}
			result.put("seriesData",seriesData);
			result.put("axisData",axisData);
			return 	ResponseHelper.buildResponse(result);
		}else if (WarningPeriodEnum.HOUR.getName().equals(requiredType)){
			SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			if ( null != endTimeTop){
				Date endDate = DateUtils.dateAddHours(DateUtils.longStr2Date(endTimeTop), -8);
				endTimeTop = formatter.format(endDate);
			}
			Date startDate = DateUtils.dateAddHours(DateUtils.longStr2Date(startTimeTop), -8);
			startTimeTop = formatter.format(startDate);
			List<PvHealthIndexHour> fanHealthIndexHours = pvHealthIndexHourMapper.selectData(healthLevel, area, equipmentName, subarray, analysisType, analysisObjType, station, pointName, indexAddress, startTimeTop, endTimeTop,null,null, orgCode);
			fanHealthIndexHours=	fanHealthIndexHours.stream().sorted(Comparator.comparing(PvHealthIndexHour::getAnalysisTime)).collect(Collectors.toList());
			for (PvHealthIndexHour obj : fanHealthIndexHours) {
				if (type.equals("0")){
					seriesData.add(Double.parseDouble(df.format(obj.getHealthIndex())));
				}else {
					seriesData.add(obj.getAnomaly() > 7.5?7.5:dfSS.format(obj.getAnomaly()));
				}
//				Date dateTime = DateUtil.parseDateTime(obj.getAnalysisTime());
//				String format = DateUtil.format(dateTime, "yyyy-MM-dd HH:00");
				axisData.add(obj.getRecDate());
			}
			result.put("seriesData",seriesData);
			result.put("axisData",axisData);
			return 	ResponseHelper.buildResponse(result);
		}else {
			SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

			SimpleDateFormat formatterNYRSF = new SimpleDateFormat("yyyy-MM-dd HH:mm");

			if ( null != endTimeTop){
				Date endDate = DateUtils.dateAddHours(DateUtils.longStr2Date(endTimeTop), -8);
				endTimeTop = formatter.format(endDate);
			}
			Date startDate = DateUtils.dateAddHours(DateUtils.longStr2Date(startTimeTop), -8);
			startTimeTop = formatter.format(startDate);

			List<PvHealthIndexMoment> fanHealthIndexMoments = pvHealthIndexMomentMapper.selectData(healthLevel, area, equipmentName, subarray, analysisType, analysisObjType, station, pointName, indexAddress, startTimeTop, endTimeTop,null,null, gatewayIds);
			fanHealthIndexMoments=	fanHealthIndexMoments.stream().sorted(Comparator.comparing(PvHealthIndexMoment::getAnalysisTime)).collect(Collectors.toList());
			for (PvHealthIndexMoment obj : fanHealthIndexMoments) {
				if (type.equals("0")){
					seriesData.add(Double.parseDouble(df.format(obj.getHealthIndex())));
				}else {
					seriesData.add(obj.getAnomaly() > 7.5?7.5:dfSS.format(obj.getAnomaly()));
				}
//				Date dateTime = DateUtil.parseDateTime(obj.getAnalysisTime());
//				String format = DateUtil.format(dateTime, DatePattern.NORM_DATETIME_MINUTE_PATTERN);
				axisData.add(obj.getRecDate());
			}
			result.put("seriesData",seriesData);
			result.put("axisData",axisData);
			return 	ResponseHelper.buildResponse(result);
		}
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY,needAuth = false)
	@ApiOperation(httpMethod = "GET",value = "预警监测设备级统计 TD",   notes = "预警监测设备级统计 TD")
	@GetMapping(value = "/selectPointNum")
	public ResponseModel<List<Map<String,Object>>> selectPointNum(@RequestParam(required = false) String STATION,@RequestParam(required = false) String SUBARRAY,@RequestParam(required = false) String  EQUIPMENTNAME) {
		List<String> gatewayIds = this.getGatewayIds();
		List<Map<String, Object>> maps = pvHealthIndexDayMapper.selectEquipStatusByEquipment( "测点", STATION,EQUIPMENTNAME, SUBARRAY, gatewayIds);
		if (maps.size() == 4){
			for (Map<String, Object> map : maps) {
				map.put("name",map.get("healthlevel"));
			}
		} else {
			List<String> levels = new ArrayList<>();
			levels.add("安全");
			levels.add("注意");
			levels.add("警告");
			levels.add("危险");

			for (Map<String, Object> map : maps) {
				map.put("name",map.get("healthlevel"));
				String healthlevel = map.get("healthlevel").toString();
				levels.remove(healthlevel);
			}

			if (levels.size()>0){
				for (String s : levels) {
					Map<String, Object> map = new HashMap<>();
					map.put("name",s);
					map.put("value",0);
					map.put("sort",HealthLevelSortEnum.getCode(s));
					maps.add(map);
				}
				maps = maps.stream().sorted(Comparator.comparingLong(e ->  Long.valueOf(e.get("sort").toString()))).collect(Collectors.toList());
			}
		}
		return ResponseHelper.buildResponse(maps);
	}


	@TycloudOperation(ApiLevel = UserType.AGENCY,needAuth = false)
	@GetMapping(value = "/selectWarningPoint")
	@ApiOperation(httpMethod = "GET", value = "预警监测设备右侧预警重复列表", notes = "预警监测设备右侧预警重复列表")
	public ResponseModel<Page<PvWarningRecord>> selectFanWarningNum(@RequestParam String STATION,@RequestParam String EQUIPMENTNAME,@RequestParam(required = false) String SUBARRAY,Integer current,Integer size) {
		Page<PvWarningRecord> page = new Page<>();
		page.setCurrent(current);
		page.setSize(size);
		List<String> gatewayIds = this.getGatewayIds();
		List<PvWarningRecord> maps = pvWaringRecordMapper.selectWarningPoint(STATION,EQUIPMENTNAME,SUBARRAY,(current-1)*size,size, gatewayIds);
		page.setRecords(maps);
		int total = pvWaringRecordMapper.selectWarningPointTotal(STATION, EQUIPMENTNAME,SUBARRAY, gatewayIds);
		page.setTotal(total);
		return ResponseHelper.buildResponse(page);
	}


	@TycloudOperation(ApiLevel = UserType.AGENCY,needAuth = false)
	@GetMapping(value = "/selectEquipWarningTotal")
	@ApiOperation(httpMethod = "GET", value = "预警信息统计富文本", notes = "预警信息统计富文本")
	public ResponseModel<Map<String,Object>> selectEquipWarningTotal(@RequestParam String STATION,@RequestParam String EQUIPMENTNAME,@RequestParam(required = false) String SUBARRAY) {
		List<String> gatewayIds = this.getGatewayIds();
		Map<String, Object> map = pvWaringRecordMapper.selectEquipWarningTotal(STATION,EQUIPMENTNAME,SUBARRAY, gatewayIds);
		return ResponseHelper.buildResponse(map);
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY,needAuth = false)
	@ApiOperation(httpMethod = "GET",value = "查询场站下设备状态统计",   notes = "查询场站下设备状态统计")
	@GetMapping (value = "/selectEquipStatusByStationPv")
	public ResponseModel<List<Map<String,Object>>> selectEquipStatusByStationPv(@RequestParam(value = "area",required = false) String area,
																			  	@RequestParam(value = "station",required = false) String station,
																			  	@RequestParam(value = "analysisObjType",required = false) String analysisObjType
	) {
		List<String> gatewayIds = this.getGatewayIds();
		List<Map<String, Object>> maps = pvHealthIndexDayMapper.selectEquipStatusByStationPv(area, analysisObjType, station, gatewayIds);
		if (maps.size() == 4){
			for (Map<String, Object> map : maps) {
				map.put("name",map.get("healthlevel"));
			}
		} else {

			List<String> levels = new ArrayList<>();
			levels.add("安全");
			levels.add("注意");
			levels.add("警告");
			levels.add("危险");

			for (Map<String, Object> map : maps) {
				map.put("name",map.get("healthlevel"));
				String healthlevel = map.get("healthlevel").toString();
				levels.remove(healthlevel);
			}

			if (levels.size()>0){
				for (String s : levels) {
					Map<String, Object> map = new HashMap<>();
					map.put("name",s);
					map.put("value",0);
					map.put("sort", HealthLevelSortEnum.getCode(s));
					maps.add(map);
				}
				maps = maps.stream().sorted(Comparator.comparingLong(e ->  Long.valueOf(e.get("sort").toString()))).collect(Collectors.toList());
			}
		}
		return ResponseHelper.buildResponse(maps);
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY,needAuth = false)
	@GetMapping(value = "/selectFanWarningNum")
	@ApiOperation(httpMethod = "GET", value = "查询各风机预警状况", notes = "查询各风机预警状况")
	public ResponseModel<Map<String,Object>> selectFanWarningNum(@RequestParam String station) {


		LambdaQueryWrapper<IdxBizPvPointProcessVariableClassification> wrapper = new LambdaQueryWrapper<>();
		wrapper.select(IdxBizPvPointProcessVariableClassification::getSubarray);
		wrapper.eq(IdxBizPvPointProcessVariableClassification::getStation, station);
		wrapper.groupBy(IdxBizPvPointProcessVariableClassification::getSubarray);
		wrapper.last(" ORDER BY SUBARRAY desc");
		List<IdxBizPvPointProcessVariableClassification> variableClassificationList = idxBizPvPointProcessVariableClassificationMapper.selectList(wrapper);
		Map<String, Object> resultMap = new HashMap<>();
		List<String> gatewayIds = this.getGatewayIds();
		List<Map<String, Object>> maps = pvWaringRecordMapper.selectFanWarningNum(station, gatewayIds);
		Map<String, Map<String, Object>> equipmentNameInfoMap = maps.stream().collect(Collectors.toMap(t -> t.get("subarray").toString(), t -> t));

		List<Integer> wxList = new ArrayList<>();
		List<Integer> zyList = new ArrayList<>();
		List<Integer> jgList = new ArrayList<>();
		List<String> list =new ArrayList<>();
		for (Map<String, Object> map : maps) {
			wxList.add(Integer.valueOf(map.get("危险").toString()));
			zyList.add(Integer.valueOf(map.get("注意").toString()));
			jgList.add(Integer.valueOf(map.get("警告").toString()));
			list.add(map.get("subarray").toString());

		}
		variableClassificationList.forEach(item -> {
			if (!equipmentNameInfoMap.containsKey(item.getSubarray())) {
				wxList.add(0);
				zyList.add(0);
				jgList.add(0);
				list.add(item.getSubarray());
			}
		});

		HashMap<String, Object> wxMapResult = new HashMap<>();
		wxMapResult.put("data", wxList);
		wxMapResult.put("name", "危险");
		HashMap<String, Object> zyMapResult = new HashMap<>();
		zyMapResult.put("data", zyList);
		zyMapResult.put("name", "注意");
		HashMap<String, Object> jgMapResult = new HashMap<>();
		jgMapResult.put("data", jgList);
		jgMapResult.put("name", "警告");

		List<Map<String, Object>> hashMaps = Arrays.asList(wxMapResult, zyMapResult, jgMapResult);
		resultMap.put("axisData", list);
		resultMap.put("seriesData", hashMaps);
		return ResponseHelper.buildResponse(resultMap);

	}

	/**
	 * 获取用户权限(此处使用gatewayId)
	 *
	 * @return gatewayIds
	 */
	private List<String> getGatewayIds() {
		List<String> permissions = permissionService.getCurrentUserPermissions();
		if (Objects.isNull(permissions)) {
			permissions = Collections.emptyList();
		}
		return permissions;
	}
}
