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.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
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.common.biz.utils.CommonResponseUtil;
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.IdxBizFanHealthIndexDto;
import com.yeejoin.amos.boot.module.jxiop.biz.entity.IdxBizFanPointTag;
import com.yeejoin.amos.boot.module.jxiop.biz.entity.IdxBizFanWarningRecord;
import com.yeejoin.amos.boot.module.jxiop.biz.entity.IdxBizPvPointTag;
import com.yeejoin.amos.boot.module.jxiop.biz.entity.IdxBizPvWarningRecord;
import com.yeejoin.amos.boot.module.jxiop.biz.mapper2.IdxBizFanPointTagMapper;
import com.yeejoin.amos.boot.module.jxiop.biz.mapper2.IdxBizPvPointTagMapper;
import com.yeejoin.amos.boot.module.jxiop.biz.service.IPermissionService;
import com.yeejoin.amos.boot.module.jxiop.biz.service.impl.IdxBizFanHealthIndexServiceImpl;
import com.yeejoin.amos.boot.module.jxiop.biz.tdMapper2.FanHealthIndexDayMapper;
import com.yeejoin.amos.boot.module.jxiop.biz.tdMapper2.FanHealthIndexHourMapper;
import com.yeejoin.amos.boot.module.jxiop.biz.tdMapper2.FanHealthIndexMomentMapper;
import com.yeejoin.amos.boot.module.jxiop.biz.tdMapper2.FanWaringRecordMapper;
import com.yeejoin.amos.boot.module.jxiop.biz.tdengine.FanHealthIndexDay;
import com.yeejoin.amos.boot.module.jxiop.biz.tdengine.FanHealthIndexHour;
import com.yeejoin.amos.boot.module.jxiop.biz.tdengine.FanHealthIndexMoment;
import com.yeejoin.amos.boot.module.jxiop.biz.tdengine.FanWarningRecord;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.formula.functions.T;
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 javax.ws.rs.POST;
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-fan-health-index")
public class IdxBizFanHealthIndexController extends BaseController {

    @Autowired
    IdxBizFanHealthIndexServiceImpl idxBizFanHealthIndexServiceImpl;

    @Autowired
    IdxBizFanPointTagMapper idxBizFanPointTagMapper;
    @Autowired
    IdxBizPvPointTagMapper idxBizPvPointTagMapper;
    @Autowired
	FanHealthIndexDayMapper fanHealthIndexDayMapper;
    @Autowired
	FanHealthIndexHourMapper fanHealthIndexHourMapper;
    @Autowired
	FanHealthIndexMomentMapper fanHealthIndexMomentMapper;
    @Autowired
	FanWaringRecordMapper fanWarningRecord;
	@Autowired
	IPermissionService permissionService;
    public final DecimalFormat df = new DecimalFormat("#.0");

	public final DecimalFormat dfSS = new DecimalFormat("#.00");
    /**
     * 新增
     *
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
	@PostMapping(value = "/save")
	@ApiOperation(httpMethod = "POST", value = "新增", notes = "新增")
	public ResponseModel<IdxBizFanHealthIndexDto> save(@RequestBody IdxBizFanHealthIndexDto model) {
	    model = idxBizFanHealthIndexServiceImpl.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<IdxBizFanHealthIndexDto> updateBySequenceNbrIdxBizFanHealthIndex(@RequestBody IdxBizFanHealthIndexDto model,@PathVariable(value = "sequenceNbr") String sequenceNbr) {
	    model.setSequenceNbr(sequenceNbr);
	    return ResponseHelper.buildResponse(idxBizFanHealthIndexServiceImpl.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(idxBizFanHealthIndexServiceImpl.removeById(sequenceNbr));
    }

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

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

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

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

	@TycloudOperation(ApiLevel = UserType.AGENCY,needAuth = false)
	@ApiOperation(httpMethod = "GET",value = "预警监测风机层仪表盘",   notes = "预警监测风机层仪表盘")
	@GetMapping(value = "/queryForLeftTableListNum")
	public ResponseModel<Map<String,Object>> queryForLeftTableListNum(@RequestParam(required = false)String STATION, @RequestParam(required = false)String HEALTHLEVEL,@RequestParam(required = false)String EQUIPMENTNAME) {
		return ResponseHelper.buildResponse(	idxBizFanHealthIndexServiceImpl.queryForLeftTableListNum(STATION, HEALTHLEVEL, EQUIPMENTNAME));
	}

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

	@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 HEALTHLEVEL,@RequestParam(required = false)String EQUIPMENTNAME,@RequestParam(required = false)String POINTNAME) {
		return ResponseHelper.buildResponse(	idxBizFanHealthIndexServiceImpl.queryForLeftTableListByPointNum(STATION, 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<IdxBizFanWarningRecord> idxBizPvWarningRecordList = idxBizFanHealthIndexServiceImpl.warningData(STATION, SUBARRAY, EQUIPMENTNAME);
		int total = idxBizFanHealthIndexServiceImpl.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",total  - idxBizPvWarningRecordList.size());

		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 = "/getqyt")
    public ResponseModel<Object> getqyt(
            String type,
            String address,
            String statioName,
            String equipmentName,
            String  arae,
            @RequestParam(value = "startTime", required = false) String startTime,
            @RequestParam(value = "endTime", required = false) String endTime
    ) {
       if(StringUtils.isEmpty(address) || StringUtils.isEmpty(statioName) || StringUtils.isEmpty(equipmentName) || StringUtils.isEmpty(arae)){
           throw new RuntimeException("片区，场站，设备名称，子系统，分析变量不能为空");
       }
		List<String> gatewayIds = this.getGatewayIds();
		return ResponseHelper.buildResponse(idxBizFanHealthIndexServiceImpl.getqyt( type,address,statioName,equipmentName,arae,startTime,endTime,gatewayIds));
    }


    @TycloudOperation(ApiLevel = UserType.AGENCY,needAuth = false)
    @ApiOperation(httpMethod = "GET",value = "工况字典详情",   notes = "工况字典详情")
    @GetMapping(value = "/getZDXQ")
    public ResponseModel<Object> getZDXQ(
            String type,
            String  id
    ) {
        Object object=null;
	    if(type.equals("1")){
            object= idxBizPvPointTagMapper.selectById(id);
        }else{
            object= idxBizFanPointTagMapper.selectById(id);
        }
        return ResponseHelper.buildResponse(object);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY,needAuth = false)
    @ApiOperation(httpMethod = "GET",value = "工况字典修改",   notes = "工况字典修改")
    @PostMapping (value = "/updateZDXQ")
    public ResponseModel<Object> updateZDXQ(
            String type,
            String  id,
            String pointDirection,
            String  tagCode
    ) {
        idxBizFanHealthIndexServiceImpl.updatezd( type,id, pointDirection,tagCode);
        return ResponseHelper.buildResponse(null);
    }

	@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 startTime,@RequestParam(required = false) String endTime) {

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


		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 = "查询场站下设备状态统计",   notes = "查询场站下设备状态统计")
	@GetMapping (value = "/getFanEquipStatusByStation")
	public ResponseModel<List<Map<String,Object>>> getFanEquipStatusByStation(String STATION) {
		Map<String, Object> map = idxBizFanHealthIndexServiceImpl.getFanEquipStatusByStation(STATION);
		List<Map<String,Object>>  maps = new ArrayList<>();


		Map<String,Object> anquan = new HashMap<>();
		anquan.put("name","安全");
		anquan.put("value",map.get("安全"));
		maps.add(anquan);
		Map<String,Object> zhuyi = new HashMap<>();
		zhuyi.put("name","注意");
		zhuyi.put("value",map.get("注意"));
		maps.add(zhuyi);
		Map<String,Object> jinggao = new HashMap<>();
		jinggao.put("name","警告");
		jinggao.put("value",map.get("警告"));
		maps.add(jinggao);
		Map<String,Object> weixian = new HashMap<>();
		weixian.put("name","危险");
		weixian.put("value",map.get("危险"));
		maps.add(weixian);


		return ResponseHelper.buildResponse(maps);
	}


	@TycloudOperation(ApiLevel = UserType.AGENCY,needAuth = false)
	@ApiOperation(httpMethod = "GET",value = "查询光伏场站所有设备状态统计",   notes = "查询光伏场站所有设备状态统计")
	@GetMapping (value = "/getPvEquipStatusByStation")
	public ResponseModel<List<Map<String,Object>>> getPvEquipStatusByStation(String STATION) {
		Map<String, Object> map = idxBizFanHealthIndexServiceImpl.getPvEquipStatusByStation(STATION);
		List<Map<String,Object>>  maps = new ArrayList<>();

		Map<String,Object> anquan = new HashMap<>();
		anquan.put("name","安全");
		anquan.put("value",map.get("安全"));
		maps.add(anquan);
		Map<String,Object> zhuyi = new HashMap<>();
		zhuyi.put("name","注意");
		zhuyi.put("value",map.get("注意"));
		maps.add(zhuyi);
		Map<String,Object> jinggao = new HashMap<>();
		jinggao.put("name","警告");
		jinggao.put("value",map.get("警告"));
		maps.add(jinggao);
		Map<String,Object> weixian = new HashMap<>();
		weixian.put("name","危险");
		weixian.put("value",map.get("危险"));
		maps.add(weixian);
		return ResponseHelper.buildResponse(maps);
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY,needAuth = false)
	@ApiOperation(httpMethod = "GET",value = "TD 风电场站/设备左侧列表通用接口",   notes = "TD 风电场站/设备列表通用接口")
	@GetMapping(value = "/stationHealthIndexTable")
	public ResponseModel<Page<FanHealthIndexDay>> stationHealthIndexTable(@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 = "subSystem",required = false) String subSystem,
																		   @RequestParam(value = "current",required = false)Integer current,
																		   @RequestParam(value = "size",required = false)Integer size){


		Page<FanHealthIndexDay> page = new Page<FanHealthIndexDay>();
		page.setCurrent(current);
		page.setSize(size);
		if (type.equals("0")){
			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);
		}else{
			Date endDate = DateUtils.dateAddHours(DateUtils.longStr2Date(endTimeTop), -7);
			SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			endTimeTop = formatter.format(endDate);
			Date startDate = DateUtils.dateAddHours(DateUtils.longStr2Date(startTimeTop), -9);
			startTimeTop = formatter.format(startDate);
		}
		List<String> gatewayIds = permissionService.getCurrentUserAmosOrgCodes();
		String orgCode = "NULL";
		if(gatewayIds.size()>0){
			orgCode =gatewayIds.get(0)+"%";
		}
		List<FanHealthIndexDay> fanHealthIndexDays = fanHealthIndexDayMapper.selectData(healthLevel, area, equipmentName, subSystem, analysisType, analysisObjType, station, pointName, indexAddress, startTimeTop, endTimeTop,(current-1)*size,size, orgCode);

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

		int total = fanHealthIndexDayMapper.selectDataTotal(healthLevel, area, equipmentName, subSystem, analysisType, analysisObjType, station, pointName, indexAddress, startTimeTop, endTimeTop);
		page.setRecords(fanHealthIndexDays);
		page.setTotal(total);
//		page.setTotal(Long.valueOf(fanHealthIndexDays.size()));
		return ResponseHelper.buildResponse(page);
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY,needAuth = false)
	@ApiOperation(httpMethod = "GET",value = "TD 风电场站/设备仪表盘",   notes = "TD 风电场站/设备仪表盘")
	@GetMapping(value = "/HealthIndexValue")
	public ResponseModel<Map<String,Object>> HealthIndexValue(@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 = "subSystem",required = false) String subSystem,
																		  @RequestParam(value = "current",required = false)Integer current,
																		  @RequestParam(value = "size",required = false)Integer size){



		if (type.equals("0")){
			Date startDayTime = DateUtils.getCurrentDayStartTime(new Date());
			Date date = DateUtils.dateAddHours(startDayTime, -8);
			SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			startTimeTop = formatter.format(date);
		}else{
			Date endDate = DateUtils.dateAddHours(DateUtils.longStr2Date(endTimeTop), -8);
			SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			endTimeTop = formatter.format(endDate);
			Date startDate = DateUtils.dateAddHours(DateUtils.longStr2Date(startTimeTop), -8);
			startTimeTop = formatter.format(startDate);
		}
		List<String> gatewayIds = permissionService.getCurrentUserAmosOrgCodes();
		String orgCode = "NULL";
		if(gatewayIds.size()>0){
			orgCode =gatewayIds.get(0)+"%";
		}
		List<FanHealthIndexDay> fanHealthIndexDays = fanHealthIndexDayMapper.selectData(healthLevel, area, equipmentName, subSystem, analysisType, analysisObjType, station, pointName, indexAddress, startTimeTop, endTimeTop,null,null, orgCode);

		Map<String,Object> map = new HashMap<>();
		map.put("value",Double.parseDouble(df.format(Double.parseDouble(fanHealthIndexDays.get(0).getValue()))));
		return ResponseHelper.buildResponse(map);
	}


	@TycloudOperation(ApiLevel = UserType.AGENCY,needAuth = false)
	@ApiOperation(httpMethod = "GET",value = "查询场站下设备状态统计",   notes = "查询场站下设备状态统计")
	@GetMapping (value = "/selectEquipStatusByStation")
	public ResponseModel<List<Map<String,Object>>> getFanEquipStatusByStation(@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 = fanHealthIndexDayMapper.selectEquipStatusByStation(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)
	@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 SUBSYSTEM,@RequestParam(required = false) String  EQUIPMENTNAME) {
	//	List<FanWarningRecord> idxBizPvWarningRecordList = fanWarningRecord.warningData(STATION,EQUIPMENTNAME ,SUBSYSTEM );
		List<Map<String, Object>> maps = fanHealthIndexDayMapper.selectEquipStatusByEquipment( "测点", STATION,EQUIPMENTNAME);
		int total = idxBizFanHealthIndexServiceImpl.pointNum(STATION, SUBSYSTEM, 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",total  - idxBizPvWarningRecordList.size());
//
//		List<Map<String,Object>> list = new ArrayList<>();
//		list.add(pointNum);
//		list.add(warningNum);
//		list.add(map);
//		list.add(map1);
//
//		return ResponseHelper.buildResponse(list);
		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)
	@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 = "subSystem",required = false) String subSystem,
														@RequestParam(value = "current",required = false) Integer current,
														@RequestParam(value = "size",required = false) Integer size){
		List<String> gatewayIds = permissionService.getCurrentUserAmosOrgCodes();
		String orgCode = "NULL";
		if(gatewayIds.size()>0){
			orgCode =gatewayIds.get(0)+"%";
		}
		if (requiredType.equals(WarningPeriodEnum.DAY.getName())){
//			if (null != type && type.equals("0")){
				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);
//			}else{
//				Date endDate = DateUtils.dateAddHours(DateUtils.longStr2Date(endTimeTop), -8);
//				SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//				endTimeTop = formatter.format(endDate);
//				Date startDate = DateUtils.dateAddHours(DateUtils.longStr2Date(startTimeTop), -8);
//				startTimeTop = formatter.format(startDate);
//			}
			List<FanHealthIndexDay> fanHealthIndexDays = fanHealthIndexDayMapper.selectData(healthLevel, area, equipmentName, subSystem, analysisType, analysisObjType, station, pointName, indexAddress, startTimeTop, endTimeTop,(current-1)*size,size,orgCode );
			fanHealthIndexDays.forEach(item -> {
				item.setHealthIndex(Double.parseDouble(df.format(item.getHealthIndex())));
			});
			Page page = new Page<>();
			page.setCurrent(current);
			page.setSize(size);
			int total = fanHealthIndexDayMapper.selectDataTotal(healthLevel, area, equipmentName, subSystem, analysisType, analysisObjType, station, pointName, indexAddress, startTimeTop, endTimeTop);
			page.setTotal(total);
			page.setRecords(fanHealthIndexDays);
			return 	ResponseHelper.buildResponse(page);
		}else if (requiredType.equals(WarningPeriodEnum.HOUR.getName())){

//			if (null != type && type.equals("0")){
			Date date = new Date();
			date = DateUtil.offsetHour(date,-8);
			date = DateUtil.offsetMinute(date,-59);
			startTimeTop = DateUtil.format(date,DatePattern.NORM_DATETIME_PATTERN);
//			}else{
//				Date endDate = DateUtils.dateAddHours(DateUtils.longStr2Date(endTimeTop), -8);
//				SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//				endTimeTop = formatter.format(endDate);
//				Date startDate = DateUtils.dateAddHours(DateUtils.longStr2Date(startTimeTop), -8);
//				startTimeTop = formatter.format(startDate);
//			}
			List<FanHealthIndexHour> fanHealthIndexHours = fanHealthIndexHourMapper.selectData(healthLevel, area, equipmentName, subSystem, analysisType, analysisObjType, station, pointName, indexAddress, startTimeTop, endTimeTop,(current-1)*size,size, orgCode);
			fanHealthIndexHours.forEach(item -> {
				item.setHealthIndex(Double.parseDouble(df.format(item.getHealthIndex())));
			});
			Page page = new Page<>();
			page.setCurrent(current);
			page.setSize(size);
			int total = fanHealthIndexDayMapper.selectDataTotal(healthLevel, area, equipmentName, subSystem, analysisType, analysisObjType, station, pointName, indexAddress, startTimeTop, endTimeTop);
			page.setTotal(total);
			page.setRecords(fanHealthIndexHours);
			return 	ResponseHelper.buildResponse(page);
		}else {
//			if (null != type && type.equals("0")){
				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);
//			}else{
//				Date endDate = DateUtils.dateAddHours(DateUtils.longStr2Date(endTimeTop), -8);
//				SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//				endTimeTop = formatter.format(endDate);
//				Date startDate = DateUtils.dateAddHours(DateUtils.longStr2Date(startTimeTop), -8);
//				startTimeTop = formatter.format(startDate);
//			}
			List<FanHealthIndexMoment> fanHealthIndexMoments = fanHealthIndexMomentMapper.selectData(healthLevel, area, equipmentName, subSystem, 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);
			int total = fanHealthIndexDayMapper.selectDataTotal(healthLevel, area, equipmentName, subSystem, analysisType, analysisObjType, station, pointName, indexAddress, startTimeTop, endTimeTop);
			page.setTotal(total);
			page.setRecords(fanHealthIndexMoments);
			return 	ResponseHelper.buildResponse(page);
		}
	}


	@TycloudOperation(ApiLevel = UserType.AGENCY,needAuth = false)
	@ApiOperation(httpMethod = "GET",value = "TD 风电测点仪表盘",   notes = "TD 风电测点仪表盘")
	@GetMapping(value = "/pointHealthIndexValue")
	public ResponseModel<Map<String,Object>> pointHealthIndexValue(@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 = "subSystem",required = false) String subSystem,
													 @RequestParam(value = "current",required = false) Integer current,
													 @RequestParam(value = "size",required = false) Integer size){



		if (requiredType.equals(WarningPeriodEnum.DAY.getName())){
//			if (null != type && type.equals("0")){
			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);
//			}else{
//				Date endDate = DateUtils.dateAddHours(DateUtils.longStr2Date(endTimeTop), -8);
//				SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//				endTimeTop = formatter.format(endDate);
//				Date startDate = DateUtils.dateAddHours(DateUtils.longStr2Date(startTimeTop), -8);
//				startTimeTop = formatter.format(startDate);
//			}
			List<FanHealthIndexDay> fanHealthIndexDays = fanHealthIndexDayMapper.selectData(healthLevel, area, equipmentName, subSystem, analysisType, analysisObjType, station, pointName, indexAddress, startTimeTop, endTimeTop,(current-1)*size,size, null);
			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())){

//			if (null != type && type.equals("0")){
			Date date = new Date();
			date = DateUtil.offsetHour(date,-8);
			date = DateUtil.offsetMinute(date,-59);
			startTimeTop = DateUtil.format(date,DatePattern.NORM_DATETIME_PATTERN);
//			}else{
//				Date endDate = DateUtils.dateAddHours(DateUtils.longStr2Date(endTimeTop), -8);
//				SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//				endTimeTop = formatter.format(endDate);
//				Date startDate = DateUtils.dateAddHours(DateUtils.longStr2Date(startTimeTop), -8);
//				startTimeTop = formatter.format(startDate);
//			}
			List<FanHealthIndexHour> fanHealthIndexHours = fanHealthIndexHourMapper.selectData(healthLevel, area, equipmentName, subSystem, analysisType, analysisObjType, station, pointName, indexAddress, startTimeTop, endTimeTop,(current-1)*size,size, null);
			Map<String,Object> map = new HashMap<>();
			map.put("value",Double.parseDouble(df.format(fanHealthIndexHours.get(0).getHealthIndex())));
			return 	ResponseHelper.buildResponse(map);
		}else {
//			if (null != type && type.equals("0")){
			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);
//			}else{
//				Date endDate = DateUtils.dateAddHours(DateUtils.longStr2Date(endTimeTop), -8);
//				SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//				endTimeTop = formatter.format(endDate);
//				Date startDate = DateUtils.dateAddHours(DateUtils.longStr2Date(startTimeTop), -8);
//				startTimeTop = formatter.format(startDate);
//			}
			List<FanHealthIndexMoment> fanHealthIndexMoments = fanHealthIndexMomentMapper.selectData(healthLevel, area, equipmentName, subSystem, analysisType, analysisObjType, station, pointName, indexAddress, startTimeTop, endTimeTop,(current-1)*size,size, null);
			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 = "subSystem",required = false) String subSystem) {

		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<FanHealthIndexDay> fanHealthIndexDays = fanHealthIndexDayMapper.selectData(healthLevel, area, equipmentName, subSystem, analysisType, analysisObjType, station, pointName, indexAddress, startTimeTop, endTimeTop,null,null, orgCode);
			fanHealthIndexDays=	fanHealthIndexDays.stream().sorted(Comparator.comparing(FanHealthIndexDay::getAnalysisTime)).collect(Collectors.toList());

			for (FanHealthIndexDay 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<FanHealthIndexHour> fanHealthIndexHours = fanHealthIndexHourMapper.selectData(healthLevel, area, equipmentName, subSystem, analysisType, analysisObjType, station, pointName, indexAddress, startTimeTop, endTimeTop,null,null, orgCode);
			fanHealthIndexHours=	fanHealthIndexHours.stream().sorted(Comparator.comparing(FanHealthIndexHour::getAnalysisTime)).collect(Collectors.toList());
			for (FanHealthIndexHour 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");
			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<FanHealthIndexMoment> fanHealthIndexMoments = fanHealthIndexMomentMapper.selectData(healthLevel, area, equipmentName, subSystem, analysisType, analysisObjType, station, pointName, indexAddress, startTimeTop, endTimeTop,null,null, gatewayIds);
			fanHealthIndexMoments=	fanHealthIndexMoments.stream().sorted(Comparator.comparing(FanHealthIndexMoment::getAnalysisTime)).collect(Collectors.toList());
			for (FanHealthIndexMoment 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);
		}
	}


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