package com.ruoyi.business.controller;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.business.domain.*;
import com.ruoyi.business.domain.VO.*;
import com.ruoyi.business.service.*;
import com.ruoyi.common.core.constant.TdEngineConstants;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

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

@RestController
@RequestMapping("/monitorPlatform")
public class HwMonitorPlatformController extends BaseController {

    @Autowired
    private IHwMonitorUnitService hwMonitorUnitService;
    @Autowired
    private IHwDeviceService hwDeviceService;
    @Autowired
    private IHwDeviceModeService hwDeviceModeService;
    @Autowired
    private IHwSceneService hwSceneService;
    @Autowired
    private IHwElectronicFenceService hwElectronicFenceService;
    @Autowired
    private IHwAlarmInfoService hwAlarmInfoService;

    @Autowired
    private IHwMonitorPlatformService hwMonitorPlatformService;

    /**
     * 查询3.	设备各类型占所有设备数量百分比饼状图（首页左下角）
     */
    @GetMapping("/monitorUnitPercentage")
    public TableDataInfo monitorUnitPercentage() {
        List<DeviceModeVo> maps = hwDeviceService.selectDeviceModeNameVo();
        return getDataTable(maps);
    }

    /**
     * 各场景监控单元数量占监控单元总数量百分比图(首页左上)
     */
    @GetMapping("/monitorPercentage")
    public TableDataInfo monitorPercentage() {
        List<HwMonitorUnitVo> maps = hwMonitorUnitService.selectMonitorPercentage();
        return getDataTable(maps);
    }

    /**
     * 	展示总的设备数量和总的监控单元数量（首页中间上方）
     */
    @GetMapping("/allNums")
    public AllNumsVo allNums() {
        AllNumsVo allNumsVos = hwMonitorUnitService.selectAllNums(null);

        return allNumsVos;
    }

    /**
     * @return TableDataInfo
     * @param: hwAlarmInfo
     * @description 获取报警信息（首页右下角，定位场景首页，标准场景首页）
     * @author xins
     * @date 2023-09-15 11:03
     */
    @GetMapping("/getAlarmInfos")
    public TableDataInfo getAlarmInfos(HwAlarmInfo hwAlarmInfo) {
        startPage();
        List<HwAlarmInfo> alarmInfos = hwAlarmInfoService.selectHwAlarmInfoList(hwAlarmInfo);
        return getDataTable(alarmInfos);
    }

    /**
     * 2.	设备实时在运数量曲线图(首页右上角)
     *
     * @param sceneId 场景id
     */
    @GetMapping("/getDeviceOperations/{sceneId}")
    public AjaxResult selectDeviceStatus(@PathVariable("sceneId") Long sceneId) {
        JSONObject data = new JSONObject();
        data.put("10-01", 10);
        data.put("10-02", 20);
        data.put("10-03", 30);
        data.put("10-04", 40);
        data.put("10-05", 16);

        return AjaxResult.success(data);
    }


    /**
     * 	按场景展示总的设备数量和总的监控单元数量
     */
    @GetMapping("/sceneAllNums/{sceneId}")
    public AllNumsVo sceneAllNums(@PathVariable("sceneId") Long sceneId) {
        AllNumsVo allNumsVos = hwMonitorUnitService.selectAllNums(sceneId);
        return allNumsVos;
    }

    /**
     * 分页获取最子集监控单元列表(标准场景右侧)
     */
    @GetMapping("/limitSubMonitorUnit/{sceneId}")
    public TableDataInfo limitSubMonitorUnit(@PathVariable("sceneId") Long sceneId) {
        //todo sceneid should be
        startPage();
        List<HwMonitorUnit> hwMonitorUnits = hwMonitorUnitService.selectLimitSubMonitorUnit();
        return getDataTable(hwMonitorUnits);
    }

    @GetMapping("/getAlarmCountGroupAlarmType/{sceneId}")
    public AjaxResult getAlarmCountGroupAlarmType(@PathVariable("sceneId") Long sceneId) {
        return success(hwAlarmInfoService.selectAlarmsByAlarmType(sceneId));
    }

    /**
     * 按电子围栏定位显示其下设备数量，以及报警的设备数量(定位场景地图气泡图)
     *
     * @param sceneId
     */
    @GetMapping("/ElectronicNumVo/{sceneId}")
    public AjaxResult ElectronicNumVo(@PathVariable("sceneId") Long sceneId) {

//        {
//           type:'多边形',
//            children:[{
//            latitude:'',
//        longtitude:''
//        }]
//        }

//        {
//            type:'圆形',
//            centerpoint:{
//             'lantitude':,
//             'longtitude':,
//        }
//        }
//        }
        return success(hwElectronicFenceService.selectEleTypeNums(sceneId));
    }


    /**
     * 监控单元报警统计
     */
    @GetMapping("/alarmStats/{sceneId}")
    public AjaxResult alarmStats(@PathVariable("sceneId") Long sceneId) {
        List<AlarmStatsVo> alarmStatsVos = hwMonitorUnitService.selectAlarmStats(sceneId);
        return success(alarmStatsVos);
    }

    /**
     * 获取最子级监控单元数量、设备数量和在线设备数量
     *
     * @param sceneId 场景id
     */
    @GetMapping("/subDevice/{sceneId}")
    public SubDeviceSumVo subDevice(@PathVariable("sceneId") Long sceneId) {

        SubDeviceSumVo subDeviceSumVos = hwMonitorUnitService.selectSubDeviceSum(sceneId);

        return subDeviceSumVos;
    }


    /**
     * 树状获取监控单元列表(设备监测左侧树)
     *
     * @param sceneId 场景ID
     * @return list
     * @throws
     */
    @GetMapping("/treeList/{sceneId}")
    public AjaxResult monitorUnitTree(@PathVariable("sceneId") Long sceneId)
    {
        HwMonitorUnit queryMonitorUnit = new HwMonitorUnit();
        queryMonitorUnit.setSceneId(sceneId);
        return success(hwMonitorUnitService.selectMonitorTreeList(queryMonitorUnit));
    }

//    /**
//     *
//     * 选择场景
//     * @param sceneModeId 场景id
//     * @return
//     */
//
//    @PostMapping("/selectHwSceneBySceneModeId")
//    public TableDataInfo selectHwSceneBySceneModeId(Long sceneModeId){
//        List<HwScene> hwScenes = hwSceneService.selectHwSceneBySceneModeId(sceneModeId);
//        return getDataTable(hwScenes);
//    }

    //


    /**
     * 获取监控单元详细信息
     */
//    @RequiresPermissions("business:monitorUnit:query")
    @GetMapping(value = "/getMonitorById/{monitorUnitId}")
    public AjaxResult getMonitorById(@PathVariable("monitorUnitId") Long monitorUnitId) {
        return success(hwMonitorUnitService.selectHwMonitorUnitByMonitorUnitId(monitorUnitId));
    }

    /**
     * 根据监控单元ID获取设备信息，分可控制设备和上传数据设备
     *
     * @param monitorUnitId 监控单元id
     */
    @GetMapping("/selectDevicesByMonitorUnitId/{monitorUnitId}/{sceneId}")
    public AjaxResult selectDeviceByDeviceModeByMonitorUnitId(@PathVariable("monitorUnitId") Long monitorUnitId,
                                                              @PathVariable("sceneId") Long sceneId) {
        HwDevice queryHwDevice = new HwDevice();
        queryHwDevice.setMonitorUnitId(monitorUnitId);
        queryHwDevice.setSceneId(sceneId);

        return success(hwDeviceService.getDevicesByMonitor(queryHwDevice));
    }


    /**
     * @description 根据场景ID获取设备模型列表
     * @author xins
     * @date 2023-09-16 12:44
     */
    @PostMapping("/getDeviceModesBySceneId")
    public AjaxResult getDeviceModesBySceneId(@RequestBody HwDeviceMode queryHwDeviceMode) {
        return success(hwDeviceModeService.selectHwDeviceModeList(queryHwDeviceMode));
    }

    /**
     * @return AjaxResult
     * @param: monitorUnitId
     * @description 根据设备模型获取最新数据
     * @author xins
     * @date 2023-09-16 12:45
     */
    @PostMapping("/selectLatestDataByDeviceMode")
    public AjaxResult selectLatestDataByDeviceMode(@Validated @RequestBody DeviceLatestDataVo deviceLatestData) {
        JSONObject returnObj = new JSONObject();
        List<Map<String, Object>> latestDataMaps = hwMonitorPlatformService.selectLatestDataByTags(deviceLatestData);
        List<DeviceDataColumnVo> deviceDataColumnVos = this.getDeviceDataColumns(latestDataMaps);
        TableDataInfo tableDataInfo = getDataTable(latestDataMaps);
        returnObj.put("deviceDataColumns", deviceDataColumnVos);
        returnObj.put("latestData", tableDataInfo);
        return success(returnObj);
    }


    @GetMapping("/getDeviceInfo/{deviceId}")
    public AjaxResult getDeviceInfo(@PathVariable("deviceId") Long deviceId){
        HwDevice device = hwDeviceService.selectHwDeviceJoinByDeviceId(deviceId);
        return success(device);
    }

    @GetMapping("/getLinkDevices/{deviceId}")
    public AjaxResult getLinkDevices(@PathVariable("deviceId")Long deviceId){
        return success(hwDeviceService.selectLinkDeviceList(deviceId));
    }

    /**
     * @return AjaxResult
     * @param: deviceHistoryData
     * @description 获取设备历史数据
     * @author xins
     * @date 2023-09-16 15:15
     */
    @PostMapping("/getHistoryData")
    public AjaxResult getHistoryData(@Validated @RequestBody DeviceHistoryDataVo deviceHistoryData) {
//        startPage();
        JSONObject returnObj = new JSONObject();
        List<Map<String, Object>> historyDataMaps = hwMonitorPlatformService.getHistoryData(deviceHistoryData);
        List<DeviceDataColumnVo> deviceDataColumnVos = this.getDeviceDataColumns(historyDataMaps);
        TableDataInfo tableDataInfo = getDataTable(historyDataMaps);
        returnObj.put("deviceDataColumns", deviceDataColumnVos);
        returnObj.put("historyData", tableDataInfo);
        return success(returnObj);

    }

    private List<DeviceDataColumnVo> getDeviceDataColumns(List<Map<String, Object>> latestDataMaps){
        List<DeviceDataColumnVo> deviceDataColumnVos = new ArrayList<DeviceDataColumnVo>();
        if (latestDataMaps != null && latestDataMaps.size() > 0) {
            Map<String, Object> latestDataMap = latestDataMaps.get(0);
            for (Map.Entry<String, Object> entry : latestDataMap.entrySet()) {
                DeviceDataColumnVo deviceDataColumnVo = new DeviceDataColumnVo();
                String columnKey = entry.getKey();
                deviceDataColumnVo.setColumnKey(columnKey);
                deviceDataColumnVo.setColumnName(TdEngineConstants.DEVICE_DATA_COLUMN_MAP.get(columnKey) == null
                        ? columnKey : TdEngineConstants.DEVICE_DATA_COLUMN_MAP.get(columnKey));
                deviceDataColumnVos.add(deviceDataColumnVo);
            }
        }
        return deviceDataColumnVos;
    }

    /**
     * 场景选择
     * ，id=0 可以返回所有，其他根据id过滤，默认标识
     */
    @GetMapping("/selectSecnes")
    public AjaxResult selectSecnes(HwScene scene) {
        List<HwScene> hwScenes = hwSceneService.selectHwSceneList(scene);
        return success(hwScenes);
    }

}
