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

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yeejoin.amos.boot.biz.common.controller.BaseController;
import com.yeejoin.amos.boot.module.jxiop.api.entity.StationBasic;
import com.yeejoin.amos.boot.module.jxiop.api.mapper.EquipmentsJxiopDocMysqlMapper;
import com.yeejoin.amos.boot.module.jxiop.api.mapper.MonitorFanIndicatorMapper;
import com.yeejoin.amos.boot.module.jxiop.biz.ESDto.ESEquipments;
import com.yeejoin.amos.boot.module.jxiop.biz.constants.CommonConstans;
import com.yeejoin.amos.boot.module.jxiop.biz.dto.CoreValuesDto;
import com.yeejoin.amos.boot.module.jxiop.biz.dto.PointImportDto;
import com.yeejoin.amos.boot.module.jxiop.biz.dto.QueryDto;
import com.yeejoin.amos.boot.module.jxiop.biz.dto.StationCacheInfoDto;
import com.yeejoin.amos.boot.module.jxiop.biz.entity.EquipmentsJxiopDocMysql;
import com.yeejoin.amos.boot.module.jxiop.biz.entity.Test;
import com.yeejoin.amos.boot.module.jxiop.biz.feign.CoreFeignClient;
import com.yeejoin.amos.boot.module.jxiop.biz.repository.ESEquipmentsRepository;
import com.yeejoin.amos.boot.module.jxiop.biz.service.CoreCommonService;
import com.yeejoin.amos.boot.module.jxiop.biz.service.MonitorService;
import com.yeejoin.amos.boot.module.jxiop.biz.service.impl.*;
//import com.yeejoin.amos.boot.module.jxiop.biz.utils.InfluxDButils;
//import com.yeejoin.amos.component.influxdb.InfluxDbConnection;
import com.yeejoin.amos.boot.module.jxiop.biz.utils.ElasticSearchUtil;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import org.elasticsearch.action.admin.indices.stats.CommonStats;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.AvgAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.ParsedAvg;
import org.elasticsearch.search.aggregations.metrics.ParsedSum;
import org.elasticsearch.search.aggregations.metrics.SumAggregationBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.Query;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.typroject.tyboot.component.emq.EmqKeeper;
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.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.*;

@RestController
@Api(tags = "Demo-test")
@RequestMapping(value = "/demo")
public class DemoController extends BaseController {
	@Autowired
	private CoreCommonService coreCommonService;
	// @Autowired
//    LargeScreenImpl largeScreenImpl;
	private final String ss = "瞬时风速";
	private final String zfs = "WTX-801_25_WTX-801_总辐射";
	private final String zfslj = "WTX-801_25_WTX-801_总辐射累计";

//    @Resource
//    InfluxDbConnection influxDbConnection;

	// @Autowired
//    InfluxDButils influxDButils;
	private final String dayvalue = "日发电量";
	private final String moonValue = "月发电量";
	private final String yearValue = "年发电量";
	private final String dayDateFormat = "yyyy-MM-dd";
	private final String moonDateFormat = "yyyy-MM";
	private final String yearDateFormat = "yyyy";
	// @Autowired
//    PowerGenerationImpl powerGenerationImpl;
	private final String dayType = "day";
	private final String moonType = "moon";
	private final String yearType = "year";
	Logger logger = LoggerFactory.getLogger(DemoController.class);
	@Autowired
	StationBasicServiceImpl stationBasicServiceimpl;
//	@Autowired
//	TestServiceImpl testServiceimpl;
	@Autowired
	EmqKeeper emqKeeper;
	@Autowired
	ESEquipmentsRepository equipmentsRepository;
	@Autowired
	CommonServiceImpl commonServiceImpl;
	@Autowired
	ElasticSearchUtil elasticSearchUtil;
	@Autowired
	private MonitorFanIndicatorMapper monitorFanIndicatorregionMapper;
	@Autowired
	private ElasticsearchRestTemplate elasticsearchTemplate;

	@Autowired
	private EquipmentsJxiopDocMysqlMapper equipmentsJxiopDocMysqlMapper;
	@Autowired
	private MonitorService monitorService;

	@TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "手动更新场站缓存信息接口")
	@GetMapping("/updateStationCacheInfo")
	public String updateStationCacheInfo() {
		String updateResult = "更新场站信息缓存成功";
		try {

		} catch (Exception e) {
			updateResult = "更新场站信息缓存成功";
			throw new RuntimeException(e);
		}
		return updateResult;
	}

	@TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "初始化influxdb-风电、光伏、升压站")
	@GetMapping("doc/test4")
	public ResponseModel<Integer> demoTest3() {
		// 数据说明 夏造风电、泰和光伏、夏造升压站、泰和升压站
		String[] strings = { "1668801435891929089", "1669524885619085313", "1668801570352926721",
				"1669525017559306241" };
		elasticsearchTemplate.deleteIndex(ESEquipments.class);
		int num = 0;
		for (int i = 0; i < strings.length; i++) {
			QueryWrapper<EquipmentsJxiopDocMysql> QueryWrapper = new QueryWrapper<>();
//        夏造风电
//        QueryWrapper.eq("gateway", "1668801435891929089");
//        泰和光伏
			QueryWrapper.eq("gateway", strings[i]);
			long DATE = new Date().getTime();
			System.out.println(DATE);
			List<EquipmentsJxiopDocMysql> list = equipmentsJxiopDocMysqlMapper.selectList(QueryWrapper);
			num = num + list.size();
			List<ESEquipments> listit = new ArrayList<>();
			for (EquipmentsJxiopDocMysql monitorFanIndicator : list) {

				ESEquipments eSEquipments = new ESEquipments(monitorFanIndicator.getValueF(),
						monitorFanIndicator.getId(), monitorFanIndicator.getAddress(),
						monitorFanIndicator.getDataType(), monitorFanIndicator.getEquipmentSpecificName(),
						monitorFanIndicator.getGatewayId(), monitorFanIndicator.getIsAlarm(),
						monitorFanIndicator.getCreatedTime(), monitorFanIndicator.getUnit(),
						monitorFanIndicator.getValue(), monitorFanIndicator.getValueLabel(),
						monitorFanIndicator.getTraceId(), monitorFanIndicator.getEquipmentIndexName(),
						monitorFanIndicator.getEquipmentNumber(), monitorFanIndicator.getFrontModule(),
						monitorFanIndicator.getSystemType(), monitorFanIndicator.getPictureName(),
						monitorFanIndicator.getDisplayName());

				listit.add(eSEquipments);

//                Map<String, String> tag = new HashMap<>();
//                Map<String, Object> maps2 = new HashMap<>();
//
//                maps2.put("address", monitorFanIndicator.getIndexAddress());
//                maps2.put("dataType", monitorFanIndicator.getDataType());
//                maps2.put("equipmentSpecificName", monitorFanIndicator.getFanCode());
//                tag.put("equipmentsIdx", monitorFanIndicator.getAddressGateway());
//                maps2.put("gatewayId", monitorFanIndicator.getGateway());
//                maps2.put("isAlarm", monitorFanIndicator.getIsAlarm());
//                maps2.put("createdTime", "2023-07-05 18:30:26");
//                maps2.put("unit", monitorFanIndicator.getUnit());
//                maps2.put("value", "");
//                maps2.put("valueLabel","" );
//                maps2.put("traceId", "");
//                maps2.put("equipmentIndexName", monitorFanIndicator.getIndicator());
//                maps2.put("equipmentNumber", monitorFanIndicator.getEquipmentNumber());
//                maps2.put("frontModule", monitorFanIndicator.getFrontModule());
//                maps2.put("systemType", monitorFanIndicator.getSystemType());
//                maps2.put("pictureName", monitorFanIndicator.getPictureName());
//                //升压站的字段显示名称
//                maps2.put("displayName", "");
//                influxDbConnection.insert("indicators_" + monitorFanIndicator.getGateway(), tag, maps2, 1688558007051L, TimeUnit.MILLISECONDS);

			}
			equipmentsRepository.saveAll(listit);
		}
		return ResponseHelper.buildResponse(num);
	}

	@TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "从ES获取数据反向插入mysql")
	@GetMapping("doc/getDatafromEsToMysql")
	public void getDatafromEsToMysql() {
		try {
			List<ESEquipments> result = elasticSearchUtil.searchResponse("jxiop_equipments", null,
					hit -> JSONObject.parseObject(hit.getSourceAsString(), ESEquipments.class));
			result.forEach(esEquipments -> {
				EquipmentsJxiopDocMysql equipmentsJxiopDocMysql = new EquipmentsJxiopDocMysql();
				BeanUtils.copyProperties(esEquipments, equipmentsJxiopDocMysql);
				if (ObjectUtils.isEmpty(equipmentsJxiopDocMysqlMapper.selectList(
						new QueryWrapper<EquipmentsJxiopDocMysql>().eq("id", equipmentsJxiopDocMysql.getId())))) {
					equipmentsJxiopDocMysqlMapper.insert(equipmentsJxiopDocMysql);
				} else {
					equipmentsJxiopDocMysqlMapper.updateById(equipmentsJxiopDocMysql);
				}

			});
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	@TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "从Mysql同步数据到ES")
	@GetMapping("doc/getDatafromMySqlToES")
	public void getDatafromMySqlToES() {
//        List<EquipmentsJxiopDocMysql> equipmentsJxiopDocMysqlList = equipmentsJxiopDocMysqlMapper.selectList(new QueryWrapper<EquipmentsJxiopDocMysql>().eq("id","24_1669525017559306241"));
		List<EquipmentsJxiopDocMysql> equipmentsJxiopDocMysqlList = equipmentsJxiopDocMysqlMapper
				.selectList(new QueryWrapper<EquipmentsJxiopDocMysql>().isNotNull("id"));
		int i = 0;
		for (EquipmentsJxiopDocMysql equipmentsJxiopDocMysql : equipmentsJxiopDocMysqlList) {
			// ESEquipments esEquipments =
			// equipmentsRepository.findById(equipmentsJxiopDocMysql.getId()).get();
			ESEquipments esEquipments = new ESEquipments();
			esEquipments.setId(equipmentsJxiopDocMysql.getId());
			esEquipments.setAddress(equipmentsJxiopDocMysql.getAddress());
			esEquipments.setDataType(equipmentsJxiopDocMysql.getDataType());
			esEquipments.setEquipmentSpecificName(equipmentsJxiopDocMysql.getEquipmentSpecificName());
			esEquipments.setGatewayId(equipmentsJxiopDocMysql.getGatewayId());
			esEquipments.setIsAlarm(equipmentsJxiopDocMysql.getIsAlarm());
			// 更新单位
			esEquipments.setUnit(
					ObjectUtils.isEmpty(equipmentsJxiopDocMysql.getUnit()) ? "" : equipmentsJxiopDocMysql.getUnit());
			esEquipments.setCreatedTime(equipmentsJxiopDocMysql.getCreatedTime());
			esEquipments.setValue(
					ObjectUtils.isEmpty(equipmentsJxiopDocMysql.getValue()) ? "" : equipmentsJxiopDocMysql.getValue());
			esEquipments.setValueF(
					ObjectUtils.isEmpty(equipmentsJxiopDocMysql.getValueF()) ? 0 : equipmentsJxiopDocMysql.getValueF());
			esEquipments.setValueLabel(ObjectUtils.isEmpty(equipmentsJxiopDocMysql.getValueLabel()) ? ""
					: equipmentsJxiopDocMysql.getValueLabel());
			// 更新排序号
			esEquipments.setTraceId(ObjectUtils.isEmpty(equipmentsJxiopDocMysql.getTraceId()) ? ""
					: equipmentsJxiopDocMysql.getTraceId());
			esEquipments.setEquipmentIndexName(ObjectUtils.isEmpty(equipmentsJxiopDocMysql.getEquipmentIndexName()) ? ""
					: equipmentsJxiopDocMysql.getEquipmentIndexName());
			esEquipments.setEquipmentNumber(ObjectUtils.isEmpty(equipmentsJxiopDocMysql.getEquipmentNumber()) ? ""
					: equipmentsJxiopDocMysql.getEquipmentNumber());
			// 更新显示名称
			esEquipments.setDisplayName(ObjectUtils.isEmpty(equipmentsJxiopDocMysql.getDisplayName()) ? ""
					: equipmentsJxiopDocMysql.getDisplayName());
			// 更新frontModule
			esEquipments.setFrontModule(ObjectUtils.isEmpty(equipmentsJxiopDocMysql.getFrontModule()) ? ""
					: equipmentsJxiopDocMysql.getFrontModule());
			// 更新systemType
			esEquipments.setSystemType(ObjectUtils.isEmpty(equipmentsJxiopDocMysql.getSystemType()) ? ""
					: equipmentsJxiopDocMysql.getSystemType());
			// 更新图片名称
			esEquipments.setPictureName(ObjectUtils.isEmpty(equipmentsJxiopDocMysql.getPictureName()) ? ""
					: equipmentsJxiopDocMysql.getPictureName());
			System.out.println("开始保存es" + ++i);
			try {
				equipmentsRepository.save(esEquipments);
			} catch (Exception e) {
				e.printStackTrace();
			}
			System.out.println("结束保存es" + i);
		}
	}

	@TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "导入整理的测点数据到MySQL同时更新es")
	@PostMapping("doc/importDatafAndUpdateEs")
	public void getDatafromMySqlToES(@RequestParam String filePath) {
		try {
			InputStream inputStream = new FileInputStream(filePath);
			List<Object> pointImportDtoList = EasyExcel.read(inputStream).head(PointImportDto.class).sheet(0)
					.headRowNumber(1).doReadSync();
			pointImportDtoList.forEach(o -> {
				PointImportDto pointImportDto = (PointImportDto) o;
				List<EquipmentsJxiopDocMysql> equipmentsJxiopDocMysqlList = equipmentsJxiopDocMysqlMapper.selectList(
						new QueryWrapper<EquipmentsJxiopDocMysql>().eq("gateway_id", pointImportDto.getGatewayId())
								.eq("equipment_index_name", pointImportDto.getEquipmentIndexName()));
				if (!ObjectUtils.isEmpty(equipmentsJxiopDocMysqlList)) {
					equipmentsJxiopDocMysqlList.forEach(equipmentsJxiopDocMysql -> {
						ESEquipments esEquipments = equipmentsRepository.findById(equipmentsJxiopDocMysql.getId())
								.get();
						// 更新模块
						if (!equipmentsJxiopDocMysql.getFrontModule().contains(pointImportDto.getFrontModule())) {
							equipmentsJxiopDocMysql.setFrontModule(
									equipmentsJxiopDocMysql.getFrontModule() + "," + pointImportDto.getFrontModule());
							esEquipments.setFrontModule(
									equipmentsJxiopDocMysql.getFrontModule() + "," + pointImportDto.getFrontModule());
						}
						// 更新类型
						if (!equipmentsJxiopDocMysql.getSystemType().contains(pointImportDto.getSystemType())) {
							equipmentsJxiopDocMysql.setSystemType(
									equipmentsJxiopDocMysql.getSystemType() + "," + pointImportDto.getSystemType());
							esEquipments.setSystemType(
									equipmentsJxiopDocMysql.getSystemType() + "," + pointImportDto.getSystemType());
						}
						// 更新排序号
						equipmentsJxiopDocMysql.setTraceId(pointImportDto.getTraceId());
						esEquipments.setTraceId(pointImportDto.getTraceId());
						// 更新显示名称
						equipmentsJxiopDocMysql.setDisplayName(pointImportDto.getDisplayName());
						esEquipments.setDisplayName(pointImportDto.getDisplayName());
						// 更新单位 如果单位为空或者单位超过周期性数据存储长度则丢弃单位更新操作
						if (!ObjectUtils.isEmpty(pointImportDto.getUnit())
								&& (pointImportDto.getUnit().toCharArray().length < 24)) {
							equipmentsJxiopDocMysql.setUnit(pointImportDto.getUnit());
							esEquipments.setUnit(pointImportDto.getUnit());
						}
						equipmentsJxiopDocMysqlMapper.updateById(equipmentsJxiopDocMysql);
						equipmentsRepository.save(esEquipments);
					});
				}
			});
		} catch (Exception e) {

		}

	}

	@TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "测试消息发送")
	@GetMapping("/test5")
	public void demoTest4() {
		HashMap<String, String> hashMap = new HashMap<>();
		hashMap.put("test", String.valueOf(Math.random() * 1000));
		hashMap.put("test1", String.valueOf(Math.random() * 100));
		try {
			emqKeeper.getMqttClient().publish("test_topic", JSON.toJSON(hashMap).toString().getBytes("UTF-8"), 1, true);
			emqKeeper.getMqttClient().publish("test_topic1", JSON.toJSON(hashMap).toString().getBytes("UTF-8"), 1,
					true);
			logger.info("++++++++++++++++++++++++++++++++++发送消息成功++++++++++++++++++++++++++++++++++++++");
		} catch (Exception exception) {
			logger.error("============================================================发送消息报错");
		}
	}

	@TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "初始化升压站")
	@GetMapping("/test6")
	public ResponseModel<Integer> demoTest5() {
		// 数据说明 夏造风电、泰和光伏、夏造升压站、泰和升压站
		String[] strings = { "1668801570352926721", "1669525017559306241" };
//        String [] strings = {"1669525017559306241"};
//        Object o=this.monitorFanIndicatorImpl.getIndicatoralueAvage("1668801435891929089","60秒平均风速");
//        System.out.println(o.toString());

		int num = 0;
		for (int i = 0; i < strings.length; i++) {
			QueryWrapper<EquipmentsJxiopDocMysql> QueryWrapper = new QueryWrapper<>();
//        夏造风电
//        QueryWrapper.eq("gateway", "1668801435891929089");
//        泰和光伏
			QueryWrapper.eq("gateway", strings[i]);
			long DATE = new Date().getTime();
			System.out.println(DATE);
			List<EquipmentsJxiopDocMysql> list = equipmentsJxiopDocMysqlMapper.selectList(QueryWrapper);
			num = num + list.size();

			List<ESEquipments> listit = new ArrayList<>();
			for (EquipmentsJxiopDocMysql monitorFanIndicator : list) {

				ESEquipments eSEquipments = new ESEquipments(monitorFanIndicator.getValueF(),
						monitorFanIndicator.getId(), monitorFanIndicator.getAddress(),
						monitorFanIndicator.getDataType(), monitorFanIndicator.getEquipmentSpecificName(),
						monitorFanIndicator.getGatewayId(), monitorFanIndicator.getIsAlarm(),
						monitorFanIndicator.getCreatedTime(), monitorFanIndicator.getUnit(),
						monitorFanIndicator.getValue(), monitorFanIndicator.getValueLabel(),
						monitorFanIndicator.getTraceId(), monitorFanIndicator.getEquipmentIndexName(),
						monitorFanIndicator.getEquipmentNumber(), monitorFanIndicator.getFrontModule(),
						monitorFanIndicator.getSystemType(), monitorFanIndicator.getPictureName(),
						monitorFanIndicator.getDisplayName());

				listit.add(eSEquipments);

//                Map<String, String> tag = new HashMap<>();
//                Map<String, Object> maps2 = new HashMap<>();
//
//                maps2.put("address", monitorFanIndicator.getIndexAddress());
//                maps2.put("dataType", monitorFanIndicator.getDataType());
//                maps2.put("equipmentSpecificName", monitorFanIndicator.getFanCode());
//                tag.put("equipmentsIdx", monitorFanIndicator.getAddressGateway());
//                maps2.put("gatewayId", monitorFanIndicator.getGateway());
//                maps2.put("isAlarm", monitorFanIndicator.getIsAlarm());
//                maps2.put("createdTime", "2023-07-05 18:30:26");
//                maps2.put("unit", monitorFanIndicator.getUnit());
//                maps2.put("value", "");
//                maps2.put("valueLabel","" );
//                maps2.put("traceId", "");
//                maps2.put("equipmentIndexName", monitorFanIndicator.getIndicator());
//                maps2.put("equipmentNumber", monitorFanIndicator.getEquipmentNumber());
//                maps2.put("frontModule", monitorFanIndicator.getFrontModule());
//                maps2.put("systemType", monitorFanIndicator.getSystemType());
//                maps2.put("pictureName", monitorFanIndicator.getPictureName());
//                //升压站的字段显示名称
//                maps2.put("displayName", monitorFanIndicator.getEquipmentNumber());
//                influxDbConnection.insert("indicators_" + monitorFanIndicator.getGateway(), tag, maps2, 1688558007051L, TimeUnit.MILLISECONDS);
			}

			equipmentsRepository.saveAll(listit);
		}
		return ResponseHelper.buildResponse(num);
	}

	@TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "测试动态图片")
	@GetMapping("/test7")
	public ResponseModel<HashMap<String, String>> demoTest6() {
		HashMap<String, String> hashMap = new HashMap<>();
		hashMap.put("url", "upload/jxiop/amos_studio/758F6F4BC695B777899485DB0C7E5D3.gif");

		return ResponseHelper.buildResponse(hashMap);
	}

	@TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "测试求和")
	@GetMapping("/test8")
	public ResponseModel<Object> demoTest8() {

		QueryBuilder queryBuilder = QueryBuilders.matchQuery("equipmentIndexName", "有功功率");
		SumAggregationBuilder buyCountSum = AggregationBuilders.sum("buyCountSum").field("valueF");
		Query query = new NativeSearchQueryBuilder().withQuery(queryBuilder).addAggregation(buyCountSum)
				.withPageable(PageRequest.of(0, 1)).build();
		query.setTrackTotalHits(true); // 允许返回查询结果的total - search.getTotalHits()
		SearchHits<ESEquipments> search = elasticsearchTemplate.search(query, ESEquipments.class);
		return ResponseHelper.buildResponse(search);

	}

	@TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "测试平均数")
	@GetMapping("/test9")
	public ResponseModel<Object> demoTest9() {
		QueryBuilder queryBuilder = QueryBuilders.matchQuery("equipmentIndexName", "有功功率");

		AvgAggregationBuilder buyCountAvg = AggregationBuilders.avg("buyCountAvg").field("valueF");
		Query query = new NativeSearchQueryBuilder().withQuery(queryBuilder).addAggregation(buyCountAvg)
				.withPageable(PageRequest.of(0, 1)).build();

		query.setTrackTotalHits(true);
		SearchHits<ESEquipments> search = elasticsearchTemplate.search(query, ESEquipments.class);
		return ResponseHelper.buildResponse(search);
	}

	@TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "分组求和数")
	@GetMapping("/test10")
	public SearchHits demoTest10() {
		QueryBuilder queryBuilder = QueryBuilders.matchQuery("equipmentIndexName", "年发电量");

		// 如果只对一个字段进行分组写一个就好
		TermsAggregationBuilder tb1 = AggregationBuilders.terms("group_gatewayId").field("gatewayId.keyword");// gatewayId
																												// 是分组字段名，group_gatewayId是查询结果的别名
//        TermsAggregationBuilder tb2 = AggregationBuilders.terms("group_equipmentNumber").field("equipmentNumber.keyword");//equipmentNumber 是分组字段名，group_equipmentNumber是查询结果的别名
		SumAggregationBuilder sb = AggregationBuilders.sum("sum_valueDouble").field("valueF");// valueF是求和字段名称，sun_valueDouble是结果别名

		// 注意顺序,决定先通过谁分组
		tb1.subAggregation(sb); // 通过typeId字段分组统计总数
//        tb2.subAggregation(sb); // 通过houseId字段分组统计总数
//        tb1.subAggregation(tb2); // 合并

		Query query = new NativeSearchQueryBuilder().withQuery(queryBuilder).addAggregation(tb1)
				.withPageable(PageRequest.of(0, 1)).build();

		query.setTrackTotalHits(true);
		SearchHits search = elasticsearchTemplate.search(query, ESEquipments.class);

		return search;
	}

	@TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "分组求和数")
	@GetMapping("/test11")
	public Map demoTest11() {

		List<QueryDto> queryDto = new ArrayList<>();
		QueryDto ff1 = new QueryDto("gatewayId.keyword", "1668801435891929089");
		QueryDto ff2 = new QueryDto("equipmentIndexName.keyword", "有功功率");
		queryDto.add(ff1);
		queryDto.add(ff2);
		Double avg = commonServiceImpl.getavg(queryDto, "valueF", ESEquipments.class);
		Double sum = commonServiceImpl.getsum(queryDto, "valueF", ESEquipments.class);

		Map<String, Double> map = new HashMap();
		map.put("1668801435891929089_avg", avg);
		map.put("1668801435891929089_sum", sum);
		return map;
	}

	@TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "取缓存数据")
	@GetMapping("/test12")
	public List<StationCacheInfoDto> demoTest12() {
		return commonServiceImpl.getListStationCacheInfoDto();
	}

	@TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "es获取数据")
	@GetMapping("/test19")
	public void test19() {
		Map<String, List<String>> queryConditon = new HashMap<>();
		queryConditon.put("equipmentIndexName.keyword", Arrays.asList("日发电量", "月发电量", "年发电量"));
		commonServiceImpl.getListDataByCondtions(queryConditon, null, ESEquipments.class);
	}

	@TycloudOperation( ApiLevel = UserType.AGENCY,needAuth = false)
	@ApiOperation(value = "测试feign调用")
	@GetMapping("/testFeignCall")
	public List<CoreValuesDto> testFeignCall() {
//         List<CoreValuesDto> coreValuesDtos =coreCommonService.getValuesByStationNamesAndPointsNames(null,null);
//		 monitorService.getTotalData();
		monitorService.getNationWideInfo("江西省","gis");
//		monitorService.getCompletionOfPowerIndicatorsByProvinceName(1,20,"陕西省");
//		Double sum  = coreCommonService.getSumOfByPointName(coreValuesDtos, CommonConstans.DAY_POWER_GENERATION);
//		Double avg  = coreCommonService.getAverageOfByPointName(coreValuesDtos, CommonConstans.DAY_POWER_GENERATION);
		return null;
	}
}
