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

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
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.SmartAnalyseEnum;
import com.yeejoin.amos.boot.module.jxiop.biz.entity.IdxBizFanHealthIndex;
import com.yeejoin.amos.boot.module.jxiop.biz.entity.IdxBizPvPointProcessVariableClassification;
import com.yeejoin.amos.boot.module.jxiop.biz.mapper2.IdxBizFanHealthIndexMapper;
import com.yeejoin.amos.boot.module.jxiop.biz.service.IAlarmInfoDetailService;
import com.yeejoin.amos.boot.module.jxiop.biz.service.IPermissionService;
import com.yeejoin.amos.boot.module.jxiop.biz.service.impl.CommonServiceImpl;
import com.yeejoin.amos.boot.module.jxiop.biz.tdMapper2.FanHealthIndexMapper;
import com.yeejoin.amos.boot.module.jxiop.biz.tdMapper2.PvHealthIndexMapper;
import com.yeejoin.amos.boot.module.jxiop.biz.tdengine.FanHealthIndex;
import com.yeejoin.amos.boot.module.jxiop.biz.tdengine.FanHealthIndexDay;
import com.yeejoin.amos.boot.module.jxiop.biz.tdengine.PvHealthIndex;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
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.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author system_generator
 * @date 2023-08-11
 */
@RestController
@Api(tags = "智能分析")
@RequestMapping(value = "/analyse")
public class AnalyseController extends BaseController {

	@Autowired
	CommonServiceImpl commonServiceImpl;
//	@Autowired
//	IdxBizFanHealthIndexMapper idxBizFanHealthIndexMapper;

	@Autowired
	IAlarmInfoDetailService iAlarmInfoDetailService;

	@Autowired
	FanHealthIndexMapper fanHealthIndexMapper;
	@Autowired
	PvHealthIndexMapper pvHealthIndexMapper;

	@Autowired
	IPermissionService permissionService;

	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	@ApiOperation(httpMethod = "GET", value = "获取执行结果", notes = "获取执行结果")
	@GetMapping(value = "/isRun")
	public ResponseModel<String> isRun(@RequestParam(required = true) String key) {
		return ResponseHelper.buildResponse(commonServiceImpl.isRun(key));
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	@ApiOperation(httpMethod = "GET", value = "工况测点区间划分-风机", notes = "工况测点区间划分-风机")
	@GetMapping(value = "/getFanConditionVariablesByTime")
	public ResponseModel<String> getFanConditionVariablesByTime(@RequestParam(required = false) String startTime,
			@RequestParam(required = false) String endTime) {
		if (StringUtils.isEmpty(startTime) && StringUtils.isEmpty(endTime)) {
			Date currentDayStartTime = DateUtils.getCurrentDayStartTime(new Date());
			Date currentDayEndTime = DateUtils.getCurrentDayEndTime(new Date());
			startTime = DateUtils.convertDateToString(currentDayStartTime, DateUtils.DATE_TIME_PATTERN);
			endTime = DateUtils.convertDateToString(currentDayEndTime, DateUtils.DATE_TIME_PATTERN);
		}
		return ResponseHelper.buildResponse(commonServiceImpl.getFanConditionVariablesByTimeThread(startTime, endTime));
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	@ApiOperation(httpMethod = "GET", value = "工况测点区间划分-光伏", notes = "工况测点区间划分-光伏")
	@GetMapping(value = "/getPvConditionVariablesByTime")
	public ResponseModel<String> getPvConditionVariablesByTime(@RequestParam(required = false) String startTime,
			@RequestParam(required = false) String endTime) {
		if (StringUtils.isEmpty(startTime) && StringUtils.isEmpty(endTime)) {
			Date currentDayStartTime = DateUtils.getCurrentDayStartTime(new Date());
			Date currentDayEndTime = DateUtils.getCurrentDayEndTime(new Date());
			startTime = DateUtils.convertDateToString(currentDayStartTime, DateUtils.DATE_TIME_PATTERN);
			endTime = DateUtils.convertDateToString(currentDayEndTime, DateUtils.DATE_TIME_PATTERN);
		}
		return ResponseHelper.buildResponse(commonServiceImpl.getPvConditionVariablesByTimeThread(startTime, endTime));
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	@ApiOperation(httpMethod = "GET", value = "相关性分析-风机", notes = "相关性分析-风机")
	@GetMapping(value = "/getFanConditionVariablesByTimeAnalyse")
	public ResponseModel<String> getFanConditionVariablesByTimeAnalyse(@RequestParam(required = false) String startTime,
			@RequestParam(required = false) String endTime) {
		if (StringUtils.isEmpty(startTime) && StringUtils.isEmpty(endTime)) {
			Date currentDayStartTime = DateUtils.getCurrentDayStartTime(new Date());
			Date currentDayEndTime = DateUtils.getCurrentDayEndTime(new Date());
			startTime = DateUtils.convertDateToString(currentDayStartTime, DateUtils.DATE_TIME_PATTERN);
			endTime = DateUtils.convertDateToString(currentDayEndTime, DateUtils.DATE_TIME_PATTERN);
		}
		return ResponseHelper
				.buildResponse(commonServiceImpl.getFanConditionVariablesByTimeAnalyseThread(startTime, endTime));
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	@PostMapping(value = "/getFanConditionVariablesByTimeAnalyseNew")
	@ApiOperation(httpMethod = "POST", value = "相关性分析 - 风机 - 新", notes = "相关性分析 - 风机 - 新")
	public ResponseModel<Object> getFanConditionVariablesByTimeAnalyseNew() throws InterruptedException {
		commonServiceImpl.chuli();
		return ResponseHelper.buildResponse(null);
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	@ApiOperation(httpMethod = "GET", value = "相关性分析 - 光伏 - 新", notes = "相关性分析 - 光伏 - 新")
	@GetMapping(value = "/getPvConditionVariablesByTimeAnalyseNew")
	public ResponseModel<String> getPvConditionVariablesByTimeAnalyseNew(
			@RequestParam(required = false) String startTime, @RequestParam(required = false) String endTime)
			throws InterruptedException {
		if (StringUtils.isEmpty(startTime) && StringUtils.isEmpty(endTime)) {
			startTime = DateUtils.convertDateToString(DateUtil.beginOfYear(new Date()), DateUtils.DATE_TIME_PATTERN);
			endTime = DateUtils.convertDateToString(DateUtils.getCurrentDayEndTime(new Date()),
					DateUtils.DATE_TIME_PATTERN);
		}
		commonServiceImpl.chuliPv(startTime, endTime);
		return ResponseHelper
				.buildResponse(commonServiceImpl.getPvConditionVariablesByTimeAnalyseThread(startTime, endTime));
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	@ApiOperation(httpMethod = "GET", value = "相关性分析-风机", notes = "相关性分析-风机")
	@GetMapping(value = "/getPvConditionVariablesByTimeAnalyse")
	public ResponseModel<String> getPvConditionVariablesByTimeAnalyse(@RequestParam(required = false) String startTime,
			@RequestParam(required = false) String endTime) {
		if (StringUtils.isEmpty(startTime) && StringUtils.isEmpty(endTime)) {
			Date currentDayStartTime = DateUtils.getCurrentDayStartTime(new Date());
			Date currentDayEndTime = DateUtils.getCurrentDayEndTime(new Date());
			startTime = DateUtils.convertDateToString(currentDayStartTime, DateUtils.DATE_TIME_PATTERN);
			endTime = DateUtils.convertDateToString(currentDayEndTime, DateUtils.DATE_TIME_PATTERN);
		}
		return ResponseHelper
				.buildResponse(commonServiceImpl.getPvConditionVariablesByTimeAnalyseThread(startTime, endTime));
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	@ApiOperation(httpMethod = "GET", value = "中心值计算-风机", notes = "中心值计算-风机")
	@GetMapping(value = "/getFanConditionVariablesByTimeAnalyse1")
	public ResponseModel<String> getFanConditionVariablesByTimeAnalyse1(
			@RequestParam(required = false) String startTime, @RequestParam(required = false) String endTime) {
		if (StringUtils.isEmpty(startTime) && StringUtils.isEmpty(endTime)) {
			Date currentDayStartTime = DateUtils.getCurrentDayStartTime(new Date());
			Date currentDayEndTime = DateUtils.getCurrentDayEndTime(new Date());
			startTime = DateUtils.convertDateToString(currentDayStartTime, DateUtils.DATE_TIME_PATTERN);
			endTime = DateUtils.convertDateToString(currentDayEndTime, DateUtils.DATE_TIME_PATTERN);
		}
		return ResponseHelper
				.buildResponse(commonServiceImpl.getFanConditionVariablesByTimeAnalyse1Thread(startTime, endTime));
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	@ApiOperation(httpMethod = "GET", value = "中心值计算-光伏", notes = "中心值计算-光伏")
	@GetMapping(value = "/getPvConditionVariablesByTimeAnalyse1")
	public ResponseModel<String> getPvConditionVariablesByTimeAnalyse1(@RequestParam(required = false) String startTime,
			@RequestParam(required = false) String endTime) {
		if (StringUtils.isEmpty(startTime) && StringUtils.isEmpty(endTime)) {
			Date currentDayStartTime = DateUtils.getCurrentDayStartTime(new Date());
			Date currentDayEndTime = DateUtils.getCurrentDayEndTime(new Date());
			startTime = DateUtils.convertDateToString(currentDayStartTime, DateUtils.DATE_TIME_PATTERN);
			endTime = DateUtils.convertDateToString(currentDayEndTime, DateUtils.DATE_TIME_PATTERN);
		}
		return ResponseHelper
				.buildResponse(commonServiceImpl.getPvConditionVariablesByTimeAnalyse1Thread(startTime, endTime));
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	@ApiOperation(httpMethod = "GET", value = "获取influxdb数据", notes = "获取influxdb数据")
	@GetMapping(value = "/getInfluxdbDataByConditon")
	public ResponseModel<Map<String, Object>> getInfluxdbDataByConditon(@RequestParam String stationType,
			@RequestParam(required = false) String pointId, @RequestParam(required = false) String startTime,
			@RequestParam(required = false) String endTime) {

		if (!StringUtils.isEmpty(startTime)) {
			try {
				Date date = DateUtils.dateAddHours(DateUtils.dateParse(startTime, DateUtils.DATE_TIME_PATTERN), -8);
				startTime = DateUtils.convertDateToString(date, DateUtils.DATE_TIME_PATTERN);
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		if (!StringUtils.isEmpty(endTime)) {
			try {
				Date date = DateUtils.dateAddHours(DateUtils.dateParse(endTime, DateUtils.DATE_TIME_PATTERN), -8);
				endTime = DateUtils.convertDateToString(date, DateUtils.DATE_TIME_PATTERN);
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		if (StringUtils.isEmpty(startTime)) {
			Date sevenAgoDayStartTime = null;
			try {
				sevenAgoDayStartTime = DateUtils.dateAddDays(new Date(), -7);
			} catch (Exception e) {
				e.printStackTrace();
			}
			startTime = DateUtils.convertDateToString(DateUtils.dateAddHours(sevenAgoDayStartTime, -8),
					DateUtils.DATE_TIME_PATTERN);
		}
		DateUtils.dateAddHours(DateUtils.getCurrentDayStartTime(new Date()), -8);
		if (StringUtils.isEmpty(endTime)) {
			endTime = DateUtils.convertDateToString(DateUtils.dateAddHours(new Date(), -8),
					DateUtils.DATE_TIME_PATTERN);
		}
		return ResponseHelper
				.buildResponse(commonServiceImpl.getInfluxdbDataByConditon(stationType, pointId, startTime, endTime));
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	@ApiOperation(httpMethod = "GET", value = "根据测点查单位信息", notes = "根据测点查单位信息")
	@GetMapping(value = "/getUnitByIndexAddress")
	public ResponseModel<Map<String, String>> getUnitByIndexAddress(@RequestParam String stationType,
			@RequestParam String pointId) {
		return ResponseHelper.buildResponse(commonServiceImpl.getUnitByIndexAddress(stationType, pointId));
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	@ApiOperation(httpMethod = "post", value = "获取influxdb数据", notes = "获取influxdb数据")
	@PostMapping(value = "/getInfluxdbDataByConditon")
	public ResponseModel<Map<String, Object>> getDataByConditon(@RequestParam String stationType,
			@RequestParam(required = false) String pointId, @RequestParam(required = false) String startTime,
			@RequestParam(required = false) String endTime, @RequestBody Map<String, Object> map) {
		if ("FD".equals(stationType)) {
			if (ObjectUtils.isEmpty(map.get("EQUIPINDEX"))
					|| CharSequenceUtil.isEmpty(map.get("EQUIPINDEX").toString())) {
				return ResponseHelper.buildResponse(new HashMap<>());
			}
			LambdaQueryWrapper<FanHealthIndex> indexLambdaQueryWrapper = new LambdaQueryWrapper<>();
			indexLambdaQueryWrapper.eq(FanHealthIndex::getStation, map.get("STATION"));
			indexLambdaQueryWrapper.eq(FanHealthIndex::getEquipmentName, map.get("EQUIPNAME"));
			indexLambdaQueryWrapper.eq(FanHealthIndex::getPointName, map.get("EQUIPINDEX")).last("limit 1");

			List<FanHealthIndex> idxBizFanHealthIndices = fanHealthIndexMapper
					.selectList(indexLambdaQueryWrapper);
			if (CollectionUtils.isNotEmpty(idxBizFanHealthIndices)) {
				pointId = idxBizFanHealthIndices.get(0).getIndexAddress();
			}
		}

		if (!StringUtils.isEmpty(startTime)) {
			try {
				Date date = DateUtils.dateAddHours(DateUtils.dateParse(startTime, DateUtils.DATE_TIME_PATTERN), -8);
				startTime = DateUtils.convertDateToString(date, DateUtils.DATE_TIME_PATTERN);
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		if (!StringUtils.isEmpty(endTime)) {
			try {
				Date date = DateUtils.dateAddHours(DateUtils.dateParse(endTime, DateUtils.DATE_TIME_PATTERN), -8);
				endTime = DateUtils.convertDateToString(date, DateUtils.DATE_TIME_PATTERN);
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		if (StringUtils.isEmpty(startTime)) {
			Date sevenAgoDayStartTime = null;
			try {
				sevenAgoDayStartTime = DateUtils.dateAddDays(new Date(), -7);
			} catch (Exception e) {
				e.printStackTrace();
			}
			startTime = DateUtils.convertDateToString(DateUtils.dateAddHours(sevenAgoDayStartTime, -8),
					DateUtils.DATE_TIME_PATTERN);
		}
		DateUtils.dateAddHours(DateUtils.getCurrentDayStartTime(new Date()), -8);
		if (StringUtils.isEmpty(endTime)) {
			endTime = DateUtils.convertDateToString(DateUtils.dateAddHours(new Date(), -8),
					DateUtils.DATE_TIME_PATTERN);
		}
		return ResponseHelper
				.buildResponse(commonServiceImpl.getInfluxdbDataByConditon(stationType, pointId, startTime, endTime));
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	@ApiOperation(httpMethod = "GET", value = "预警详情信息", notes = "预警详情信息")
	@GetMapping(value = "/getAlramInfoDetail")
	public ResponseModel<Map<String, Object>> getAlramInfoDetailOfFan(@RequestParam(required = true) String id,
			@RequestParam(required = true) String type) {
		if ("FAN".equals(type)) {
			return ResponseHelper.buildResponse(iAlarmInfoDetailService.getAlramInfoDetailOfFan(id));
		} else {
			return ResponseHelper.buildResponse(iAlarmInfoDetailService.getAlramInfoDetailOfPv(id));
		}

	}

	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	@ApiOperation(httpMethod = "GET", value = "预警详情信息-光伏", notes = "预警详情信息-光伏")
	@GetMapping(value = "/queryIndexByArae")
	public ResponseModel<Map<String, Object>> queryIndexByArae(@RequestParam(required = false) String area,
			String analysisType, String startTimeTop, String endTimeTop) {

		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<FanHealthIndex> fanHealthIndices = fanHealthIndexMapper.selectData(null, area, null, null, analysisType,
				"片区", null, null, null, startTimeTop, endTimeTop);
		List<PvHealthIndex> pvHealthIndices = pvHealthIndexMapper.selectData(null, area, null, null, analysisType, "片区",
				null, null, null, startTimeTop, endTimeTop);

		for (PvHealthIndex pvHealthIndex : pvHealthIndices) {
			FanHealthIndex fanHealthIndex = new FanHealthIndex();
			BeanUtils.copyProperties(pvHealthIndex, fanHealthIndex);
			fanHealthIndices.add(fanHealthIndex);
		}
		Map<String, Object> map = new HashMap<>();
		List<Object> axisData = new ArrayList<>();
		List<Object> seriesData = new ArrayList<>();
		Map<String, List<FanHealthIndex>> mapList = fanHealthIndices.stream()
				.collect(Collectors.groupingBy(FanHealthIndex::getAnalysisTime));
		for (String s : mapList.keySet()) {
			List<FanHealthIndex> fanHealthIndices1 = mapList.get(s);
			Double healtnIndex = fanHealthIndices1.stream()
					.collect(Collectors.averagingDouble(FanHealthIndex::getHealthIndex));
			seriesData.add(healtnIndex.intValue());
			axisData.add(s);
		}

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

	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	@ApiOperation(httpMethod = "GET", value = "获取当前人的权限-全国、片区、场站", notes = "获取当前人的权限-全国、片区、场站")
	@GetMapping(value = "/getCurrentUserPermissions")
	public ResponseModel<List<String>> getCurrentUserPermissions() {
		return ResponseHelper.buildResponse(permissionService.getCurrentUserPermissions());
	}
}
