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

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
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 com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.biz.common.controller.BaseController;
import com.yeejoin.amos.boot.module.jxiop.biz.dto.IdxBizPvWarningRecordDto;
import com.yeejoin.amos.boot.module.jxiop.biz.entity.IdxBizFanPointProcessVariableClassification;
import com.yeejoin.amos.boot.module.jxiop.biz.entity.IdxBizPvPointProcessVariableClassification;
import com.yeejoin.amos.boot.module.jxiop.biz.mapper2.IdxBizPvPointProcessVariableClassificationMapper;
import com.yeejoin.amos.boot.module.jxiop.biz.service.impl.IdxBizPvWarningRecordServiceImpl;
import com.yeejoin.amos.boot.module.jxiop.biz.tdMapper2.PvWaringRecordMapper;
import com.yeejoin.amos.boot.module.jxiop.biz.tdengine.FanWarningRecord;
import com.yeejoin.amos.boot.module.jxiop.biz.tdengine.PvWarningRecord;
import com.yeejoin.amos.boot.module.jxiop.biz.tdengine.PvWarningRecord;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

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

    @Autowired
    IdxBizPvWarningRecordServiceImpl idxBizPvWarningRecordServiceImpl;

    
	@Autowired
	PvWaringRecordMapper pvWaringRecordMapper;
	
	
	@Autowired
	IdxBizPvPointProcessVariableClassificationMapper idxBizPvPointProcessVariableClassificationMapper;
	
    /**
     * 新增
     *
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
	@PostMapping(value = "/save")
	@ApiOperation(httpMethod = "POST", value = "新增", notes = "新增")
	public ResponseModel<IdxBizPvWarningRecordDto> save(@RequestBody IdxBizPvWarningRecordDto model) {
	    model = idxBizPvWarningRecordServiceImpl.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<IdxBizPvWarningRecordDto> updateBySequenceNbrIdxBizPvWarningRecord(@RequestBody IdxBizPvWarningRecordDto model,@PathVariable(value = "sequenceNbr") String sequenceNbr) {
	    model.setSequenceNbr(sequenceNbr);
	    return ResponseHelper.buildResponse(idxBizPvWarningRecordServiceImpl.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(idxBizPvWarningRecordServiceImpl.removeById(sequenceNbr));
    }

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

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

	/**
	 * 列表全部数据查询
     *
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(httpMethod = "GET",value = "列表全部数据查询",   notes = "列表全部数据查询")
	@GetMapping(value = "/list")
	public ResponseModel<List<IdxBizPvWarningRecordDto>> selectForList() {
	    return ResponseHelper.buildResponse(idxBizPvWarningRecordServiceImpl.queryForIdxBizPvWarningRecordList());
	}
	
	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	@GetMapping(value = "/selectFanWarningNum")
	@ApiOperation(httpMethod = "GET", value = "查询各风机预警状况", notes = "查询各风机预警状况")
	public ResponseModel<Map<String, Object>> selectFanWarningNum(@RequestParam String station) {

		LambdaQueryWrapper<IdxBizPvPointProcessVariableClassification> wrapper = new LambdaQueryWrapper<>();
		wrapper.select(IdxBizPvPointProcessVariableClassification::getSubarray);
		wrapper.eq(IdxBizPvPointProcessVariableClassification::getStation, station);
		wrapper.groupBy(IdxBizPvPointProcessVariableClassification::getSubarray);
		wrapper.last(" ORDER BY RIGHT(SUBARRAY,6) desc");
		List<IdxBizPvPointProcessVariableClassification> variableClassificationList = idxBizPvPointProcessVariableClassificationMapper
				.selectList(wrapper);

		QueryWrapper<PvWarningRecord> lambdaQw = new QueryWrapper<>();
		lambdaQw.select("COUNT(1) AS c,subarray AS subarray,warning_name AS warningname");
		lambdaQw.lambda().eq(PvWarningRecord::getStation, station);
		lambdaQw.lambda().eq(PvWarningRecord::getDisposotionState, "待确认");
		lambdaQw.lambda().groupBy(PvWarningRecord::getSubarray);
		lambdaQw.lambda().groupBy(PvWarningRecord::getWarningName);
		List<Map<String, Object>> lists = pvWaringRecordMapper.selectMaps(lambdaQw);

//		Map<String, Object> resultMap = new HashMap<>();
//		List<String> gatewayIds = this.getGatewayIds();
//		List<Map<String, Object>> maps = fanWaringRecordMapper.selectFanWarningNum(station, gatewayIds);
//		Map<String, Map<String, Object>> equipmentNameInfoMap = maps.stream()
//				.collect(Collectors.toMap(t -> t.get("EQUIPMENT_NAME").toString(), t -> t));

		List<Integer> wxList = new ArrayList<>();
		List<Integer> zyList = new ArrayList<>();
		List<Integer> jgList = new ArrayList<>();
		List<String> list = new ArrayList<>();

		Map<String, Map<String, Integer>> countMap = new HashMap<>();
		for (Map<String, Object> map : lists) {
			String subarray = String.valueOf(map.get("subarray"));
			int count = Integer.valueOf(String.valueOf(map.get("c")));
			String warningName = String.valueOf(map.get("warningname"));
			Map<String, Integer> equipMap = countMap.get(subarray);
			if (equipMap == null) {
				equipMap = new HashMap<>();
			}
			equipMap.put(warningName, count);
			countMap.put(subarray, equipMap);
		}

		variableClassificationList.forEach(item -> {
			Map<String, Integer> equipMap = countMap.get(item.getSubarray());
			if(equipMap!=null) 
			{
				wxList.add(equipMap.get("危险") != null ? equipMap.get("危险") : 0);
				zyList.add(equipMap.get("注意") != null ? equipMap.get("注意") : 0);
				jgList.add(equipMap.get("警告") != null ? equipMap.get("警告") : 0);
			}else 
			{
				wxList.add(0);
				zyList.add(0);
				jgList.add(0);
			}
			list.add(item.getSubarray());
		});

//		for (Map<String, Object> map : maps) {
//			wxList.add(Integer.valueOf(map.get("危险").toString()));
//			zyList.add(Integer.valueOf(map.get("注意").toString()));
//			jgList.add(Integer.valueOf(map.get("警告").toString()));
//			list.add(map.get("EQUIPMENT_NAME").toString());
//
//		}

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

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

	}
	
	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	@GetMapping(value = "/selectEquipWarningTotal")
	@ApiOperation(httpMethod = "GET", value = "预警信息统计富文本", notes = "预警信息统计富文本")
	public ResponseModel<Map<String, Object>> selectEquipWarningTotal(@RequestParam String STATION,
			@RequestParam String EQUIPMENTNAME) {
//		List<String> gatewayIds = this.getGatewayIds();
//		Map<String, Object> maps = fanWaringRecordMapper.selectEquipWarningTotal(STATION, EQUIPMENTNAME, gatewayIds);
		QueryWrapper<PvWarningRecord> lambdaQw = new QueryWrapper<>();
		lambdaQw.select("COUNT(1) AS c,warning_name AS warningname");
		lambdaQw.lambda().eq(PvWarningRecord::getStation, STATION);
		lambdaQw.lambda().eq(PvWarningRecord::getDisposotionState, "待确认");
		lambdaQw.lambda().eq(PvWarningRecord::getEquipmentName, EQUIPMENTNAME);
		lambdaQw.lambda().groupBy(PvWarningRecord::getEquipmentName);
		lambdaQw.lambda().groupBy(PvWarningRecord::getWarningName);
		List<Map<String, Object>> lists = pvWaringRecordMapper.selectMaps(lambdaQw);
		Map<String, Object> maps = new HashMap<>();
		maps.put("zhuyi", 0);
		maps.put("weixian", 0);
		maps.put("jinggao", 0);
		int total = 0;
		for (Map<String, Object> map : lists) {
			if ("注意".equals(String.valueOf(map.get("warningname")))) {
				maps.put("zhuyi", map.get("c"));
				total+=Integer.valueOf(String.valueOf(map.get("c")));
			} else if ("危险".equals(String.valueOf(map.get("warningname")))) {
				maps.put("weixian", map.get("c"));
				total+=Integer.valueOf(String.valueOf(map.get("c")));
			} else if ("警告".equals(String.valueOf(map.get("warningname")))) {
				maps.put("jinggao", map.get("c"));
				total+=Integer.valueOf(String.valueOf(map.get("c")));
			}
		}
		maps.put("total", total);
		return ResponseHelper.buildResponse(maps);
	}


	
	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	@GetMapping(value = "/selectWarningPoint")
	@ApiOperation(httpMethod = "GET", value = "预警监测设备右侧预警重复列表", notes = "预警监测设备右侧预警重复列表")
	public ResponseModel<Page<PvWarningRecord>> selectWarningPoint(@RequestParam String STATION,
			@RequestParam String EQUIPMENTNAME, @RequestParam Integer current, @RequestParam Integer size) {
		Page<PvWarningRecord> page = new Page<>();
		page.setCurrent(current);
		page.setSize(size);
		// List<String> gatewayIds = this.getGatewayIds();
		LambdaQueryWrapper<PvWarningRecord> lambdaQw = new LambdaQueryWrapper<>();
		lambdaQw.eq(PvWarningRecord::getStation, STATION);
		lambdaQw.eq(PvWarningRecord::getEquipmentName, EQUIPMENTNAME);
		lambdaQw.eq(PvWarningRecord::getDisposotionState, "待确认");
	

		int total = pvWaringRecordMapper.selectCount(lambdaQw);
		page.setTotal(total);

		lambdaQw.orderByDesc(PvWarningRecord::getTs);
		String limit = "LIMIT " + (current - 1) * size + "," + size;
		lambdaQw.last(limit);
		List<PvWarningRecord> list = pvWaringRecordMapper.selectList(lambdaQw);

		// List<PvWarningRecord> maps =
		// fanWaringRecordMapper.selectWarningPoint(STATION, EQUIPMENTNAME, (current -
		// 1) * size, size, gatewayIds);
		page.setRecords(list);

		return ResponseHelper.buildResponse(page);
	}

}
