package com.yeejoin.amos.boot.module.jxiop.biz.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.type.TypeReference;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
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.amosprojectentity.StdUserEmpower;
import com.yeejoin.amos.boot.module.jxiop.biz.amosprojectmapper.UserEmpowerMapper;
import com.yeejoin.amos.boot.module.jxiop.biz.core.framework.GatewayIdAutowired;
import com.yeejoin.amos.boot.module.jxiop.biz.dto.FanHealthIndexDto;
import com.yeejoin.amos.boot.module.jxiop.biz.dto.FullViewRecallDataDTO;
import com.yeejoin.amos.boot.module.jxiop.biz.dto.FullViewRecallInfoDTO;
import com.yeejoin.amos.boot.module.jxiop.biz.dto.PvHealthIndexDto;
import com.yeejoin.amos.boot.module.jxiop.biz.entity.IdxBizFanHealthLevel;
import com.yeejoin.amos.boot.module.jxiop.biz.entity.IdxBizPvHealthLevel;
import com.yeejoin.amos.boot.module.jxiop.biz.mapper2.IdxBizFanHealthIndexMapper;
import com.yeejoin.amos.boot.module.jxiop.biz.mapper2.IdxBizFanHealthLevelMapper;
import com.yeejoin.amos.boot.module.jxiop.biz.mapper2.IdxBizPvHealthLevelMapper;
import com.yeejoin.amos.boot.module.jxiop.biz.tdMapper2.FanHealthIndexMapper;
import com.yeejoin.amos.boot.module.jxiop.biz.tdMapper2.FanWaringRecordMapper;
import com.yeejoin.amos.boot.module.jxiop.biz.tdMapper2.PvHealthIndexMapper;
import com.yeejoin.amos.boot.module.jxiop.biz.tdMapper2.PvWaringRecordMapper;
import com.yeejoin.amos.boot.module.jxiop.biz.tdengine.FanHealthIndex;
import com.yeejoin.amos.boot.module.jxiop.biz.tdengine.FanWarningRecord;
import com.yeejoin.amos.boot.module.jxiop.biz.tdengine.PvHealthIndex;
import com.yeejoin.amos.boot.module.jxiop.biz.tdengine.PvWarningRecord;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ObjectUtils;
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 java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

import static com.yeejoin.amos.boot.biz.common.utils.DateUtils.DATE_TIME_PATTERN;

@RestController
@Api(tags = "智能分析相关API - TD数据源")
@RequestMapping(value = "/tdInfoQueryApi")
public class TdInfoQueryController extends BaseController {

    @Autowired
    private FanHealthIndexMapper fanHealthIndexMapper;

    @Autowired
    private PvHealthIndexMapper pvHealthIndexMapper;

    @Autowired
    private FanWaringRecordMapper fanWaringRecordMapper;

    @Autowired
    private PvWaringRecordMapper pvWaringRecordMapper;

    @Autowired
    IdxBizFanHealthLevelMapper idxBizFanHealthLevelMapper;

    @Autowired
    IdxBizPvHealthLevelMapper idxBizPvHealthLevelMapper;

    @Autowired
    IdxBizFanHealthIndexMapper idxBizFanHealthIndexMapper;
    public final DecimalFormat df = new DecimalFormat("#.0");
    @Autowired
    UserEmpowerMapper userEmpowerMapper;

    private  SimpleDateFormat hhmmss = new SimpleDateFormat("HH:mm:ss");
    private SimpleDateFormat mmss = new SimpleDateFormat("mm:ss");
    private SimpleDateFormat ss = new SimpleDateFormat("ss");



//    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
//    @PostMapping(value = "/getFanHealthIndexInfoOld")
//    @ApiOperation(httpMethod = "POST", value = "分页查询健康指数信息 - 风电", notes = "分页查询健康指数信息 - 风电")
//    @GatewayIdAutowired
//    public ResponseModel<Page<FanHealthIndex>> getFanHealthIndexInfoOld(@RequestBody FanHealthIndexDto dto) throws ParseException {
//        ReginParams reginParams = getSelectedOrgInfo();
//        String userId = reginParams.getUserModel().getUserId();
//        StdUserEmpower stdUserEmpower = userEmpowerMapper.selectOne(new QueryWrapper<StdUserEmpower>().eq("amos_user_id", userId).eq("permission_type", "YTH"));
//        String orgCode = "86"+"%";
//        if (!ObjectUtils.isEmpty(stdUserEmpower)) {
//            orgCode = stdUserEmpower.getAmosOrgCode().get(0)+"%";
//        }
//        dto.setOrgCode(orgCode);
//
//        Date currentDate = new Date();
//        if (CharSequenceUtil.isNotEmpty(dto.getStartDate())) {
//            String startDate = dto.getStartDate();
//            if(dto.getAnalysisType() != null && dto.getAnalysisType().equals("按天") && startDate.length() == 10) {
//                Date date = DateUtils.dateParse(startDate + " 00:00:00", DATE_TIME_PATTERN);
//                dto.setStartDate(DateUtils.dateFormat(DateUtils.dateAddHours(date, 0), DATE_TIME_PATTERN));
//            }else  if(dto.getAnalysisType() != null && dto.getAnalysisType().equals("按小时") && startDate.length() == 13) {
//                Date date = DateUtils.dateParse(startDate + ":00:00", DATE_TIME_PATTERN);
//                dto.setStartDate(DateUtils.dateFormat(DateUtils.dateAddHours(date, -9), DATE_TIME_PATTERN));
//            } else  if(dto.getAnalysisType() != null && dto.getAnalysisType().equals("按10分钟") && startDate.length() == 16) {
//                StringBuilder newStartDate = new StringBuilder(startDate);
//                int number = 0;
//                if((newStartDate.charAt(15) - '0') > 0) {
//                    number = 9;
//                }
//                newStartDate.replace(15, 16, number+"");
//                Date startDateDate = DateUtils.dateParse(newStartDate + ":00", DATE_TIME_PATTERN);
//                dto.setStartDate(DateUtils.dateFormat(DateUtils.dateAddHours(startDateDate, -8), DATE_TIME_PATTERN));
//            } else {
//                Date date = DateUtils.dateParse(startDate, DATE_TIME_PATTERN);
//                dto.setStartDate(DateUtils.dateFormat(DateUtils.dateAddHours(date, -8), DATE_TIME_PATTERN));
//            }
//        }
//        if (CharSequenceUtil.isNotEmpty(dto.getEndDate())) {
//            String endDate = dto.getEndDate();
//
//            if(dto.getAnalysisType() != null && dto.getAnalysisType().equals("按天") && endDate.length() == 10) {
//                Date endDateDate = DateUtils.dateParse(endDate + " 23:59:59", DATE_TIME_PATTERN);
//                dto.setEndDate(DateUtils.dateFormat(DateUtils.dateAddHours(endDateDate, 0), DATE_TIME_PATTERN));
//            }else
//            if(dto.getAnalysisType() != null && dto.getAnalysisType().equals("按小时") && endDate.length() == 13) {
//                Date endDateDate = DateUtils.dateParse(endDate + ":59:59", DATE_TIME_PATTERN);
//                dto.setEndDate(DateUtils.dateFormat(DateUtils.dateAddHours(endDateDate, -9), DATE_TIME_PATTERN));
//            } else
//            if(dto.getAnalysisType() != null && dto.getAnalysisType().equals("按10分钟") && endDate.length() == 16) {
//                StringBuilder newEndDate = new StringBuilder(endDate);
//                newEndDate.replace(15, 16, "9");
//                Date endDateDate = DateUtils.dateParse(newEndDate + ":59", DATE_TIME_PATTERN);
//                dto.setEndDate(DateUtils.dateFormat(DateUtils.dateAddHours(endDateDate, -8), DATE_TIME_PATTERN));
//            } else {
//                Date endDateDate = DateUtils.dateParse(endDate, "yyyy-MM-dd HH:mm:ss");
//                dto.setEndDate(DateUtils.dateFormat(DateUtils.dateAddHours(endDateDate, -8), DATE_TIME_PATTERN));
//            }
//        }
//        Page<FanHealthIndex> resultPage = new Page<>(dto.getCurrent(), dto.getSize());
//        dto.setCurrent((dto.getCurrent() - 1) * dto.getSize());
//        if (CharSequenceUtil.isNotEmpty(dto.getSortsString())) {
//            ObjectMapper objectMapper = new ObjectMapper();
//            try {
//                List<Map<String, String>> list = objectMapper.readValue(dto.getSortsString(), new TypeReference<List<Map<String, String>>>(){});
//                dto.setSorts(list);
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
//        List<Map<String, String>> orderWeight = dto.getSorts().stream().sorted(Comparator.comparing(t -> Integer.parseInt(t.get("orderWeight")))).collect(Collectors.toList());
//        List<String> orderByList = new ArrayList<>();
//        for (Map<String, String> map : orderWeight) {
//            String replace = map.get("order").replace("end", "");
//            String columnOrder = convert(map.get("columnKey")) + " " + replace;
//            orderByList.add(columnOrder);
//        }
//        String join = String.join(",", orderByList);
//        dto.setOrderColumns(join);
//        if (CharSequenceUtil.isNotEmpty(dto.getSortOne())) {
//            String[] split = dto.getSortOne().split(",");
//            String replace = split[1].replace("end", "");
//            String orderColumn = convert(split[0]) + " " + replace;
//            dto.setSortOne(orderColumn);
//        }
//
//        List<FanHealthIndex> fanHealthIndexIPage = fanHealthIndexMapper.getInfoByPage(dto);
//        fanHealthIndexIPage.forEach(item -> item.setHealthIndex(Double.valueOf(df.format(item.getHealthIndex()))));
//        Integer infoByPageTotal = fanHealthIndexMapper.getInfoByPageTotal(dto);
//        resultPage.setRecords(fanHealthIndexIPage);
//        resultPage.setTotal(infoByPageTotal);
//        return ResponseHelper.buildResponse(resultPage);
//    }
    
    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @PostMapping(value = "/getFanHealthIndexInfo")
    @ApiOperation(httpMethod = "POST", value = "分页查询健康指数信息 - 风电", notes = "分页查询健康指数信息 - 风电")
    @GatewayIdAutowired
    public ResponseModel<Page<FanHealthIndex>> getFanHealthIndexInfo(@RequestBody FanHealthIndexDto dto) throws Exception {
        if(dto.getEndDate()==null||dto.getStartDate()==null) 
        {
        	 throw new Exception("请选择开始时间和结束时间");
        }
        Page<FanHealthIndex> resultPage = new Page<>(dto.getCurrent(), dto.getSize());
        if(DateUtils.dateParse(dto.getStartDate()).after(DateUtils.dateParse(dto.getEndDate()))){
            return ResponseHelper.buildResponse(resultPage);
        }
        ReginParams reginParams = getSelectedOrgInfo();
        String userId = reginParams.getUserModel().getUserId();
        StdUserEmpower stdUserEmpower = userEmpowerMapper.selectOne(new QueryWrapper<StdUserEmpower>().eq("amos_user_id", userId).eq("permission_type", "YTH"));
        String orgCode = "86"+"%";
        if (!ObjectUtils.isEmpty(stdUserEmpower)) {
            orgCode = stdUserEmpower.getAmosOrgCode().get(0)+"%";
        }
        dto.setOrgCode(orgCode);

        if (CharSequenceUtil.isNotEmpty(dto.getStartDate())) {
            String startDate = dto.getStartDate();
            if(dto.getAnalysisType() != null && dto.getAnalysisType().equals("按天") && startDate.length() == 10) {
            	Long startTs = pvHealthIndexMapper.getTsByRecDateGT("fan_health_index_day", startDate, "Asc ");
                dto.setStartDateTs(startTs);
            }else  if(dto.getAnalysisType() != null && dto.getAnalysisType().equals("按小时") && startDate.length() == 13) {
            	Long startTs = pvHealthIndexMapper.getTsByRecDateGT("fan_health_index_hour", startDate + ":00:00", "Asc ");
                dto.setStartDateTs(startTs);
            } else  if(dto.getAnalysisType() != null && dto.getAnalysisType().equals("按10分钟") && startDate.length() == 16) {
                String nextWholeMinute = DateUtils.getNextWholeMinute(dto.getStartDate()+":00");
                Long startTs = pvHealthIndexMapper.getTsByRecDateGT("fan_health_index_moment", nextWholeMinute, "Asc ");
                dto.setStartDateTs(startTs);
            } else {
            	Long startTs = pvHealthIndexMapper.getTsByRecDateGT("fan_health_index_data", startDate+" 00:00:00", "Asc ");
                dto.setStartDateTs(startTs);
            }
            if(dto.getStartDateTs()==null){
                return ResponseHelper.buildResponse(resultPage);
            }
        }
        if (CharSequenceUtil.isNotEmpty(dto.getEndDate())) {
            String dateNowShortStr = DateUtils.getDateNowShortStr();
            String endDate = dto.getEndDate();
            if (dateNowShortStr.equals(endDate)){
                Date date =  DateUtils.dateAddDays(null, 0);
                SimpleDateFormat formatter = new SimpleDateFormat(DateUtils.DATE_PATTERN);
                endDate= formatter.format(date);
            }
            if(dto.getAnalysisType() != null && dto.getAnalysisType().equals("按天") && endDate.length() == 10) {
            	Long endTs = pvHealthIndexMapper.getTsByRecDateLT("fan_health_index_day", endDate, "desc ");
                dto.setEndDateTs(endTs);
                dto.setTableName("fan_health_index_day");
            }else  if(dto.getAnalysisType() != null && dto.getAnalysisType().equals("按小时") && endDate.length() == 13) {
            	Long endTs = pvHealthIndexMapper.getTsByRecDateLT("fan_health_index_hour", endDate + ":00:00", "desc ");
                dto.setEndDateTs(endTs);
                dto.setTableName("fan_health_index_hour");
            } else  if(dto.getAnalysisType() != null && dto.getAnalysisType().equals("按10分钟") && endDate.length() == 16) {
                String nextWholeMinute = DateUtils.getBeforeWholeMinute(endDate+":00");
                Long endTs = pvHealthIndexMapper.getTsByRecDateLT("fan_health_index_moment", nextWholeMinute, "desc ");
                dto.setEndDateTs(endTs);
                dto.setTableName("fan_health_index_moment");
            } else {
            	Long endTs = pvHealthIndexMapper.getTsByRecDateLT("fan_health_index_data", endDate+" 00:00:00", "desc ");
                dto.setEndDateTs(endTs);
                dto.setTableName("fan_health_index_data");
            }
            if(dto.getEndDateTs()==null){
                return ResponseHelper.buildResponse(resultPage);
            }
        }
        dto.setCurrent((dto.getCurrent() - 1) * dto.getSize());
        if (CharSequenceUtil.isNotEmpty(dto.getSortsString())) {
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                List<Map<String, String>> list = objectMapper.readValue(dto.getSortsString(), new TypeReference<List<Map<String, String>>>(){});
                dto.setSorts(list);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        List<Map<String, String>> orderWeight = dto.getSorts().stream().sorted(Comparator.comparing(t -> Integer.parseInt(t.get("orderWeight")))).collect(Collectors.toList());
        List<String> orderByList = new ArrayList<>();
        for (Map<String, String> map : orderWeight) {
            String replace = map.get("order").replace("end", "");
            String columnOrder = convert(map.get("columnKey")) + " " + replace;
            orderByList.add(columnOrder);
        }
        String join = String.join(",", orderByList);
        dto.setOrderColumns(join);
        if (CharSequenceUtil.isNotEmpty(dto.getSortOne())) {
            String[] split = dto.getSortOne().split(",");
            String replace = split[1].replace("end", "");
            String orderColumn = convert(split[0]) + " " + replace;
            dto.setSortOne(orderColumn);
        }
        if(dto.getEndDateTs()==null&&dto.getStartDateTs()==null)
        {
        	 return ResponseHelper.buildResponse(resultPage);
        }
        List<FanHealthIndex> fanHealthIndexIPage = fanHealthIndexMapper.getInfoByPage(dto);
        fanHealthIndexIPage.forEach(item -> {
            item.setHealthIndex(Double.valueOf(df.format(item.getHealthIndex())));
            if (null != dto.getAnalysisType()){
                item.setAnalysisType(dto.getAnalysisType());
            }
        });
        Integer infoByPageTotal = fanHealthIndexMapper.getInfoByPageTotal(dto);
        resultPage.setRecords(fanHealthIndexIPage);
        resultPage.setTotal(infoByPageTotal);
        return ResponseHelper.buildResponse(resultPage);
    }

    public static String convert(String camelCase) {
        StringBuilder result = new StringBuilder();
//        if (camelCase.equals("analysisTime")) {
//            return "ts";
//        }
        for (int i = 0; i < camelCase.length(); i++) {
            char currentChar = camelCase.charAt(i);
            if (Character.isUpperCase(currentChar)) {
                result.append("_").append(Character.toLowerCase(currentChar));
            } else {
                result.append(currentChar);
            }
        }
        return result.toString();
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @PostMapping(value = "/getPvHealthIndexInfo")
    @ApiOperation(httpMethod = "POST", value = "分页查询健康指数信息 - 光伏", notes = "分页查询健康指数信息 - 光伏")
    @GatewayIdAutowired
    public ResponseModel<Page<PvHealthIndex>> getPvHealthIndexInfo(@RequestBody PvHealthIndexDto dto) throws Exception {
        if(dto.getEndDate()==null||dto.getStartDate()==null) 
        {
        	 throw new Exception("请选择开始时间和结束时间");
        }
        Page<PvHealthIndex> resultPage = new Page<>(dto.getCurrent(), dto.getSize());
        if(DateUtils.dateParse(dto.getStartDate()).after(DateUtils.dateParse(dto.getEndDate()))){
            return ResponseHelper.buildResponse(resultPage);
        }
        ReginParams reginParams = getSelectedOrgInfo();
        String userId = reginParams.getUserModel().getUserId();
        StdUserEmpower stdUserEmpower = userEmpowerMapper.selectOne(new QueryWrapper<StdUserEmpower>().eq("amos_user_id", userId).eq("permission_type", "YTH"));
        String orgCode = "86"+"%";
        if (!ObjectUtils.isEmpty(stdUserEmpower)) {
            orgCode = stdUserEmpower.getAmosOrgCode().get(0)+"%";
        }
        dto.setOrgCode(orgCode);

        if (CharSequenceUtil.isNotEmpty(dto.getStartDate())) {
            String startDate = dto.getStartDate();

            if(dto.getAnalysisType() != null && dto.getAnalysisType().equals("按天") && startDate.length() == 10) {
            	Long startTs = pvHealthIndexMapper.getTsByRecDateGT("pv_health_index_day", startDate, "Asc ");
                dto.setStartDateTs(startTs);
            }else  if(dto.getAnalysisType() != null && dto.getAnalysisType().equals("按小时") && startDate.length() == 13) {
            	Long startTs = pvHealthIndexMapper.getTsByRecDateGT("pv_health_index_hour", startDate + ":00:00", "Asc ");
                dto.setStartDateTs(startTs);
            } else  if(dto.getAnalysisType() != null && dto.getAnalysisType().equals("按10分钟") && startDate.length() == 16) {
                String nextWholeMinute = DateUtils.getNextWholeMinute(dto.getStartDate()+":00");
                Long startTs = pvHealthIndexMapper.getTsByRecDateGT("pv_health_index_moment", nextWholeMinute, "Asc ");
                dto.setStartDateTs(startTs);
            } else {
            	Long startTs = pvHealthIndexMapper.getTsByRecDateGT("pv_health_index_data", startDate+" 00:00:00", "Asc ");
                dto.setStartDateTs(startTs);
            }
            if(dto.getStartDateTs()==null){
                return ResponseHelper.buildResponse(resultPage);
            }
        }
        if (CharSequenceUtil.isNotEmpty(dto.getEndDate())) {
            String dateNowShortStr = DateUtils.getDateNowShortStr();
            String endDate = dto.getEndDate();
            if (dateNowShortStr.equals(endDate)){
                Date date =  DateUtils.dateAddDays(null, 0);
                SimpleDateFormat formatter = new SimpleDateFormat(DateUtils.DATE_PATTERN);
                endDate= formatter.format(date);
            }
            if(dto.getAnalysisType() != null && dto.getAnalysisType().equals("按天") && endDate.length() == 10) {
            	Long endTs = pvHealthIndexMapper.getTsByRecDateLT("pv_health_index_day", endDate, "desc ");
                dto.setEndDateTs(endTs);
                dto.setTableName("pv_health_index_day");
            }else  if(dto.getAnalysisType() != null && dto.getAnalysisType().equals("按小时") && endDate.length() == 13) {
            	Long endTs = pvHealthIndexMapper.getTsByRecDateLT("pv_health_index_hour", endDate + ":00:00", "desc ");
                dto.setEndDateTs(endTs);
                dto.setTableName("pv_health_index_hour");
            } else  if(dto.getAnalysisType() != null && dto.getAnalysisType().equals("按10分钟") && endDate.length() == 16) {
                String nextWholeMinute = DateUtils.getBeforeWholeMinute(endDate+":00");
                Long endTs = pvHealthIndexMapper.getTsByRecDateLT("pv_health_index_moment", nextWholeMinute, "desc ");
                dto.setEndDateTs(endTs);
                dto.setTableName("pv_health_index_moment");
            } else {
            	Long endTs = pvHealthIndexMapper.getTsByRecDateLT("pv_health_index_data", endDate+" 00:00:00", "desc ");
                dto.setEndDateTs(endTs);
                dto.setTableName("pv_health_index_data");
            }
            if(dto.getEndDateTs()==null){
                return ResponseHelper.buildResponse(resultPage);
            }
        }
        if (CharSequenceUtil.isNotEmpty(dto.getSortsString())) {
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                List<Map<String, String>> list = objectMapper.readValue(dto.getSortsString(), new TypeReference<List<Map<String, String>>>(){});
                dto.setSorts(list);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        dto.setCurrent((dto.getCurrent() - 1) * dto.getSize());
        List<Map<String, String>> orderWeight = dto.getSorts().stream().sorted(Comparator.comparing(t -> Integer.parseInt(t.get("orderWeight")))).collect(Collectors.toList());
        List<String> orderByList = new ArrayList<>();
        for (Map<String, String> map : orderWeight) {
            String replace = map.get("order").replace("end", "");
            String columnOrder = convert(map.get("columnKey")) + " " + replace;
            orderByList.add(columnOrder);
        }
        if (CharSequenceUtil.isNotEmpty(dto.getSortOne())) {
            String[] split = dto.getSortOne().split(",");
            String replace = split[1].replace("end", "");
            String orderColumn = convert(split[0]) + " " + replace;
            dto.setSortOne(orderColumn);
        }
        String join = String.join(",", orderByList);
        dto.setOrderColumns(join);
        if(dto.getEndDateTs()==null&&dto.getStartDateTs()==null)
        {
        	 return ResponseHelper.buildResponse(resultPage);
        }
        List<PvHealthIndex> pvHealthIndexIPage = pvHealthIndexMapper.getInfoByPage(dto);
        pvHealthIndexIPage.forEach(item -> {
            item.setHealthIndex(Double.valueOf(df.format(item.getHealthIndex())));
            if (null != dto.getAnalysisType()){
                item.setAnalysisType(dto.getAnalysisType());
            }
        });
        Integer infoByPageTotal = pvHealthIndexMapper.getInfoByPageTotal(dto);
        resultPage.setRecords(pvHealthIndexIPage);
        resultPage.setTotal(infoByPageTotal);
        return ResponseHelper.buildResponse(resultPage);
    }
    
//    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
//    @PostMapping(value = "/getPvHealthIndexInfoOld")
//    @ApiOperation(httpMethod = "POST", value = "分页查询健康指数信息 - 光伏", notes = "分页查询健康指数信息 - 光伏")
//    @GatewayIdAutowired
//    public ResponseModel<Page<PvHealthIndex>> getPvHealthIndexInfoOld(@RequestBody PvHealthIndexDto dto) throws ParseException {
//        ReginParams reginParams = getSelectedOrgInfo();
//        String userId = reginParams.getUserModel().getUserId();
//        StdUserEmpower stdUserEmpower = userEmpowerMapper.selectOne(new QueryWrapper<StdUserEmpower>().eq("amos_user_id", userId).eq("permission_type", "YTH"));
//        String orgCode = "86"+"%";
//        if (!ObjectUtils.isEmpty(stdUserEmpower)) {
//            orgCode = stdUserEmpower.getAmosOrgCode().get(0)+"%";
//        }
//        dto.setOrgCode(orgCode);
//
//        if (CharSequenceUtil.isNotEmpty(dto.getStartDate())) {
//            String startDate = dto.getStartDate();
//
//            if(dto.getAnalysisType() != null && dto.getAnalysisType().equals("按天") && startDate.length() == 10) {
//                Date date = DateUtils.dateParse(startDate + " 00:00:00", DATE_TIME_PATTERN);
//                dto.setStartDate(DateUtils.dateFormat(DateUtils.dateAddHours(date, 0), DATE_TIME_PATTERN));
//            }else  if(dto.getAnalysisType() != null && dto.getAnalysisType().equals("按小时") && startDate.length() == 13) {
//                Date date = DateUtils.dateParse(startDate + ":00:00", DATE_TIME_PATTERN);
//                dto.setStartDate(DateUtils.dateFormat(DateUtils.dateAddHours(date, -9), DATE_TIME_PATTERN));
//            } else  if(dto.getAnalysisType() != null && dto.getAnalysisType().equals("按10分钟") && startDate.length() == 16) {
//                StringBuilder newStartDate = new StringBuilder(startDate);
//                int number = 0;
//                if((newStartDate.charAt(15) - '0') > 0) {
//                    number = 9;
//                }
//                newStartDate.replace(15, 16, number+"");
//                Date startDateDate = DateUtils.dateParse(newStartDate + ":00", DATE_TIME_PATTERN);
//                dto.setStartDate(DateUtils.dateFormat(DateUtils.dateAddHours(startDateDate, -8), DATE_TIME_PATTERN));
//            } else {
//                Date date = DateUtils.dateParse(startDate, DATE_TIME_PATTERN);
//                dto.setStartDate(DateUtils.dateFormat(DateUtils.dateAddHours(date, -8), DATE_TIME_PATTERN));
//            }
//
//
//
//        }
//        if (CharSequenceUtil.isNotEmpty(dto.getEndDate())) {
//            String endDate = dto.getEndDate();
//
//            if(dto.getAnalysisType() != null && dto.getAnalysisType().equals("按天") && endDate.length() == 10) {
//                Date endDateDate = DateUtils.dateParse(endDate + " 23:59:59", DATE_TIME_PATTERN);
//                dto.setEndDate(DateUtils.dateFormat(DateUtils.dateAddHours(endDateDate, 0), DATE_TIME_PATTERN));
//            }else
//            if(dto.getAnalysisType() != null && dto.getAnalysisType().equals("按小时") && endDate.length() == 13) {
//                Date endDateDate = DateUtils.dateParse(endDate + ":59:59", DATE_TIME_PATTERN);
//                dto.setEndDate(DateUtils.dateFormat(DateUtils.dateAddHours(endDateDate, -9), DATE_TIME_PATTERN));
//            } else
//            if(dto.getAnalysisType() != null && dto.getAnalysisType().equals("按10分钟") && endDate.length() == 16) {
//                StringBuilder newEndDate = new StringBuilder(endDate);
//                newEndDate.replace(15, 16, "9");
//                Date endDateDate = DateUtils.dateParse(newEndDate + ":59", DATE_TIME_PATTERN);
//                dto.setEndDate(DateUtils.dateFormat(DateUtils.dateAddHours(endDateDate, -8), DATE_TIME_PATTERN));
//            } else {
//                Date endDateDate = DateUtils.dateParse(endDate, "yyyy-MM-dd HH:mm:ss");
//                dto.setEndDate(DateUtils.dateFormat(DateUtils.dateAddHours(endDateDate, -8), DATE_TIME_PATTERN));
//            }
//
//        }
//        if (CharSequenceUtil.isNotEmpty(dto.getSortsString())) {
//            ObjectMapper objectMapper = new ObjectMapper();
//            try {
//                List<Map<String, String>> list = objectMapper.readValue(dto.getSortsString(), new TypeReference<List<Map<String, String>>>(){});
//                dto.setSorts(list);
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
//        Page<PvHealthIndex> resultPage = new Page<>(dto.getCurrent(), dto.getSize());
//        dto.setCurrent((dto.getCurrent() - 1) * dto.getSize());
//        List<Map<String, String>> orderWeight = dto.getSorts().stream().sorted(Comparator.comparing(t -> Integer.parseInt(t.get("orderWeight")))).collect(Collectors.toList());
//        List<String> orderByList = new ArrayList<>();
//        for (Map<String, String> map : orderWeight) {
//            String replace = map.get("order").replace("end", "");
//            String columnOrder = convert(map.get("columnKey")) + " " + replace;
//            orderByList.add(columnOrder);
//        }
//        if (CharSequenceUtil.isNotEmpty(dto.getSortOne())) {
//            String[] split = dto.getSortOne().split(",");
//            String replace = split[1].replace("end", "");
//            String orderColumn = convert(split[0]) + " " + replace;
//            dto.setSortOne(orderColumn);
//        }
//        String join = String.join(",", orderByList);
//        dto.setOrderColumns(join);
//        List<PvHealthIndex> pvHealthIndexIPage = pvHealthIndexMapper.getInfoByPage(dto);
//        pvHealthIndexIPage.forEach(item -> item.setHealthIndex(Double.valueOf(df.format(item.getHealthIndex()))));
//        Integer infoByPageTotal = pvHealthIndexMapper.getInfoByPageTotal(dto);
//        resultPage.setRecords(pvHealthIndexIPage);
//        resultPage.setTotal(infoByPageTotal);
//        return ResponseHelper.buildResponse(resultPage);
//    }

    

    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @PostMapping(value = "/getFanWarningRecordInfo")
    @ApiOperation(httpMethod = "POST", value = "分页查询健康指数信息 - 风电", notes = "分页查询健康指数信息 - 风电")
    @GatewayIdAutowired
    public ResponseModel<Page<FanWarningRecord>> getFanWarningRecordInfo(@RequestBody FanHealthIndexDto dto) throws ParseException {
        ReginParams reginParams = getSelectedOrgInfo();
        String userId = reginParams.getUserModel().getUserId();
        StdUserEmpower stdUserEmpower = userEmpowerMapper.selectOne(new QueryWrapper<StdUserEmpower>().eq("amos_user_id", userId).eq("permission_type", "YTH"));
        String orgCode = "86"+"%";
        if (!ObjectUtils.isEmpty(stdUserEmpower)) {
            orgCode = stdUserEmpower.getAmosOrgCode().get(0)+"%";
        }
        dto.setOrgCode(orgCode);

        if (CharSequenceUtil.isNotEmpty(dto.getStartDate())) {
            String startDate = dto.getStartDate();

            if(startDate.length() == 10) {
                Date date = DateUtils.dateParse(startDate + " 00:00:00", DATE_TIME_PATTERN);
                dto.setStartDate(DateUtils.dateFormat(DateUtils.dateAddHours(date, -8), DATE_TIME_PATTERN));
            } else {
                Date date = DateUtils.dateParse(startDate, DATE_TIME_PATTERN);
                dto.setStartDate(DateUtils.dateFormat(DateUtils.dateAddHours(date, -8), DATE_TIME_PATTERN));
            }
        }
        if (CharSequenceUtil.isNotEmpty(dto.getEndDate())) {
            String endDate = dto.getEndDate();
            if(endDate.length() == 10) {
                Date endDateDate = DateUtils.dateParse(endDate + " 23:59:59", DATE_TIME_PATTERN);
                dto.setEndDate(DateUtils.dateFormat(DateUtils.dateAddHours(endDateDate, -8), DATE_TIME_PATTERN));
            } else {
                Date endDateDate = DateUtils.dateParse(endDate, DATE_TIME_PATTERN);
                dto.setEndDate(DateUtils.dateFormat(DateUtils.dateAddHours(endDateDate, -8), DATE_TIME_PATTERN));
            }
        }
        if (CharSequenceUtil.isNotEmpty(dto.getSortsString())) {
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                List<Map<String, String>> list = objectMapper.readValue(dto.getSortsString(), new TypeReference<List<Map<String, String>>>(){});
                dto.setSorts(list);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        Page<FanWarningRecord> resultPage = new Page<>(dto.getCurrent(), dto.getSize());
        dto.setCurrent((dto.getCurrent() - 1) * dto.getSize());
        List<Map<String, String>> orderWeight = dto.getSorts().stream().sorted(Comparator.comparing(t -> Integer.parseInt(t.get("orderWeight")))).collect(Collectors.toList());
        List<String> orderByList = new ArrayList<>();
        for (Map<String, String> map : orderWeight) {
            String replace = map.get("order").replace("end", "");
            String columnOrder = convert(map.get("columnKey")) + " " + replace;
            orderByList.add(columnOrder);
        }
        if (CharSequenceUtil.isNotEmpty(dto.getSortOne())) {
            String[] split = dto.getSortOne().split(",");
            String replace = split[1].replace("end", "");
            String orderColumn = convert(split[0]) + " " + replace;
            dto.setSortOne(orderColumn);
        }
        String join = String.join(",", orderByList);
        dto.setOrderColumns(join);
        List<FanWarningRecord> fanWarningRecordsIPage = fanWaringRecordMapper.getInfoByPage(dto);
        Integer infoByPageTotal = fanWaringRecordMapper.getInfoByPageTotal(dto);
        resultPage.setRecords(fanWarningRecordsIPage);
        resultPage.setTotal(infoByPageTotal);
        return ResponseHelper.buildResponse(resultPage);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @PostMapping(value = "/getPvWarningRecordInfo")
    @ApiOperation(httpMethod = "POST", value = "分页查询健康指数信息 - 光伏", notes = "分页查询健康指数信息 - 光伏")
    @GatewayIdAutowired
    public ResponseModel<Page<PvWarningRecord>> getPvWarningRecordInfo(@RequestBody FanHealthIndexDto dto) throws ParseException {
        ReginParams reginParams = getSelectedOrgInfo();
        String userId = reginParams.getUserModel().getUserId();
        StdUserEmpower stdUserEmpower = userEmpowerMapper.selectOne(new QueryWrapper<StdUserEmpower>().eq("amos_user_id", userId).eq("permission_type", "YTH"));
        String orgCode = "86"+"%";
        if (!ObjectUtils.isEmpty(stdUserEmpower)) {
            orgCode = stdUserEmpower.getAmosOrgCode().get(0)+"%";
        }
        dto.setOrgCode(orgCode);

        if (CharSequenceUtil.isNotEmpty(dto.getStartDate())) {
            String startDate = dto.getStartDate();

            if(startDate.length() == 10) {
                Date date = DateUtils.dateParse(startDate + " 00:00:00", DATE_TIME_PATTERN);
                dto.setStartDate(DateUtils.dateFormat(DateUtils.dateAddHours(date, -8), DATE_TIME_PATTERN));
            } else {
                Date date = DateUtils.dateParse(startDate, DATE_TIME_PATTERN);
                dto.setStartDate(DateUtils.dateFormat(DateUtils.dateAddHours(date, -8), DATE_TIME_PATTERN));
            }
        }
        if (CharSequenceUtil.isNotEmpty(dto.getEndDate())) {
            String endDate = dto.getEndDate();
            if(endDate.length() == 10) {
                Date endDateDate = DateUtils.dateParse(endDate + " 23:59:59", DATE_TIME_PATTERN);
                dto.setEndDate(DateUtils.dateFormat(DateUtils.dateAddHours(endDateDate, -8), DATE_TIME_PATTERN));
            } else {
                Date endDateDate = DateUtils.dateParse(endDate, DATE_TIME_PATTERN);
                dto.setEndDate(DateUtils.dateFormat(DateUtils.dateAddHours(endDateDate, -8), DATE_TIME_PATTERN));
            }
        }


        if (CharSequenceUtil.isNotEmpty(dto.getSortsString())) {
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                List<Map<String, String>> list = objectMapper.readValue(dto.getSortsString(), new TypeReference<List<Map<String, String>>>(){});
                dto.setSorts(list);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        Page<PvWarningRecord> resultPage = new Page<>(dto.getCurrent(), dto.getSize());
        dto.setCurrent((dto.getCurrent() - 1) * dto.getSize());
        List<Map<String, String>> orderWeight = dto.getSorts().stream().sorted(Comparator.comparing(t -> Integer.parseInt(t.get("orderWeight")))).collect(Collectors.toList());
        List<String> orderByList = new ArrayList<>();
        for (Map<String, String> map : orderWeight) {
            String replace = map.get("order").replace("end", "");
            String columnOrder = convert(map.get("columnKey")) + " " + replace;
            orderByList.add(columnOrder);
        }
        if (CharSequenceUtil.isNotEmpty(dto.getSortOne())) {
            String[] split = dto.getSortOne().split(",");
            String replace = split[1].replace("end", "");
            String orderColumn = convert(split[0]) + " " + replace;
            dto.setSortOne(orderColumn);
        }
        String join = String.join(",", orderByList);
        dto.setOrderColumns(join);
        List<PvWarningRecord> pvWarningRecords = pvWaringRecordMapper.getInfoByPage(dto);
        Integer infoByPageTotal = pvWaringRecordMapper.getInfoByPageTotal(dto);
        resultPage.setRecords(pvWarningRecords);
        resultPage.setTotal(infoByPageTotal);
        return ResponseHelper.buildResponse(resultPage);
    }

}
