package com.zehong.web.controller.operationMonitor;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zehong.common.constant.HttpStatus;
import com.zehong.common.core.page.PageDomain;
import com.zehong.common.core.page.TableSupport;
import com.zehong.common.core.redis.RedisCache;
import com.zehong.system.domain.TConfiguration;
import com.zehong.system.domain.TDeviceInfo;
import com.zehong.system.domain.TDeviceInfoS;
import com.zehong.system.service.ITDeviceInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.zehong.common.annotation.Log;
import com.zehong.common.core.controller.BaseController;
import com.zehong.common.core.domain.AjaxResult;
import com.zehong.common.enums.BusinessType;
import com.zehong.system.domain.TDeviceReportData;
import com.zehong.system.service.ITDeviceReportDataService;
import com.zehong.common.utils.poi.ExcelUtil;
import com.zehong.common.core.page.TableDataInfo;

/**
 * 设备监控Controller
 * 
 * @author zehong
 * @date 2022-02-16
 */
@RestController
@RequestMapping("/system/data")
public class TDeviceReportDataController extends BaseController
{
    @Autowired
    private ITDeviceReportDataService tDeviceReportDataService;
    @Autowired
    private ITDeviceInfoService tDeviceInfoService;
    @Autowired
    private RedisCache redisCache;

    /**
     * 查询设备监控列表
     */
    @GetMapping("/list")
    public TableDataInfo list(TDeviceReportData tDeviceReportData)
    {
        startPage();
        List<TDeviceReportData> list = tDeviceReportDataService.selectTDeviceReportDataList(tDeviceReportData);
        return getDataTable(list);
    }

    @GetMapping("/spaceList")
    public TableDataInfo spaceList(TDeviceReportData tDeviceReportData)
    {
        startPage();
        List<TDeviceReportData> list = tDeviceReportDataService.selectSpaceTDeviceReportDataList(tDeviceReportData);
        return getDataTable(list);
    }

    @GetMapping("/riskList")
    public TableDataInfo riskList(TDeviceReportData tDeviceReportData)
    {
        startPage();
        List<TDeviceReportData> list = tDeviceReportDataService.selectRiskTDeviceReportDataList(tDeviceReportData);
        return getDataTable(list);
    }

    @GetMapping("/redisList")
    public TableDataInfo redisList(TDeviceInfoS tDeviceInfos)
    {
        List<TDeviceInfoS> tDeviceInfoS = tDeviceInfoService.selectDetailInfoAll(tDeviceInfos);
        List<TConfiguration> list = new ArrayList<>();
        for (TDeviceInfoS tDeviceInfo : tDeviceInfoS) {
            JSONObject devicesReport = redisCache.getCacheMapValue("devices_report", tDeviceInfo.getIotNo());
            if(devicesReport!=null){
                if(tDeviceInfo.getDeviceType().equals("探测器")){
                    System.out.println(devicesReport);
                    TConfiguration tConfiguration = new TConfiguration();
                    tConfiguration.setNumber(tDeviceInfo.getIotNo());
                    tConfiguration.setDetectorName(tDeviceInfo.getDeviceName());
                    tConfiguration.setDetectionMedium(tDeviceInfo.getDetectionMedium());
                    List<TDeviceInfo> tDeviceInfoList = new ArrayList<>();
                    if(tDeviceInfo.getRelationDeviceId()!=null){
                        TDeviceInfo tDeviceInfo1 = new TDeviceInfo();
                        tDeviceInfo1.setDeviceId(Long.valueOf(tDeviceInfo.getRelationDeviceId()));
                        tDeviceInfoList = tDeviceInfoService.selectTDeviceInfoList(tDeviceInfo1);
                    }
                    if (tDeviceInfoList != null && tDeviceInfoList.size() > 0) {
                        tConfiguration.setBeyondDevicename(tDeviceInfoList.get(0).getDeviceName());//所属设备名称
                    }
                    tConfiguration.setStatus(devicesReport.get("status").toString());
                    tConfiguration.setTime(devicesReport.get("time").toString());
                    list.add(tConfiguration);
                }else{
                    ObjectMapper mapper = new ObjectMapper();
                    try {
                        TConfiguration tConfiguration = mapper.convertValue(devicesReport, TConfiguration.class);

                        List<TDeviceInfo> tDeviceInfoList = new ArrayList<>();
                        if(tDeviceInfo.getRelationDeviceId()!=null){
                            TDeviceInfo tDeviceInfo1 = new TDeviceInfo();
                            tDeviceInfo1.setDeviceId(Long.valueOf(tDeviceInfo.getRelationDeviceId()));
                            tDeviceInfoList = tDeviceInfoService.selectTDeviceInfoList(tDeviceInfo1);
                        }
                        if (tDeviceInfoList != null && tDeviceInfoList.size() > 0) {
                            tConfiguration.setBeyondDevicename(tDeviceInfoList.get(0).getDeviceName());//所属设备名称
                        }

                        tConfiguration.setDetectorName(tDeviceInfo.getDeviceName());//设备名称
                        if("2".equals(tDeviceInfos.getDeviceType())){
                            tConfiguration.setValue(tConfiguration.getValue()+tDeviceInfo.getRemarksn());
                        }
                        list.add(tConfiguration);
                    } catch (IllegalArgumentException e) {
                        // 处理转换错误
                    }
                }
            }
        }
        List<TConfiguration> page = new ArrayList<>();
        if(list.size()>0){
            List<TConfiguration> sortedList = list.stream()
                    .sorted(Comparator.comparing(TConfiguration::getTime).reversed())
                    .collect(Collectors.toList());
            PageDomain pageDomain = TableSupport.buildPageRequest();
            Integer pageNum = pageDomain.getPageNum();
            Integer pageSize = pageDomain.getPageSize();
            if (pageNum > 0) {
                int fromIndex = (pageNum - 1) * pageSize;
                int toIndex = fromIndex + pageSize;
                if (fromIndex >= sortedList.size()) {
                    System.out.println("Page out of bounds.");
                } else {
                    page = sortedList.subList(fromIndex, Math.min(toIndex, sortedList.size()));
                    System.out.println("Page " + pageNum + " : " + page);
                }
            }
        }
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(page);
        rspData.setTotal(list.size());
        return rspData;
    }

    /**
     * 导出设备监控列表
     */
    @Log(title = "设备监控", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TDeviceReportData tDeviceReportData)
    {
        List<TDeviceReportData> list = tDeviceReportDataService.selectTDeviceReportDataList(tDeviceReportData);
        ExcelUtil<TDeviceReportData> util = new ExcelUtil<TDeviceReportData>(TDeviceReportData.class);
        return util.exportExcel(list, "设备监控数据");
    }

    /**
     * 获取设备监控详细信息
     */
    @GetMapping(value = "/{deviceReportDataId}")
    public AjaxResult getInfo(@PathVariable("deviceReportDataId") Long deviceReportDataId)
    {
        return AjaxResult.success(tDeviceReportDataService.selectTDeviceReportDataById(deviceReportDataId));
    }

    /**
     * 新增设备监控
     */
    @Log(title = "设备监控", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TDeviceReportData tDeviceReportData)
    {
        return toAjax(tDeviceReportDataService.insertTDeviceReportData(tDeviceReportData));
    }

    /**
     * 修改设备监控
     */
    @Log(title = "设备监控", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TDeviceReportData tDeviceReportData)
    {
        return toAjax(tDeviceReportDataService.updateTDeviceReportData(tDeviceReportData));
    }

    /**
     * 删除设备监控
     */
    @Log(title = "设备监控", businessType = BusinessType.DELETE)
	@DeleteMapping("/{deviceReportDataIds}")
    public AjaxResult remove(@PathVariable Long[] deviceReportDataIds)
    {
        return toAjax(tDeviceReportDataService.deleteTDeviceReportDataByIds(deviceReportDataIds));
    }
}
