package com.ruoyi.ems.record.controller;

import java.text.SimpleDateFormat;
import java.util.*;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson2.JSONArray;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.ems.base.service.IEmsBaseEnergyTypeService;
import com.ruoyi.ems.base.service.IEmsBaseMonitorInfoService;
import com.ruoyi.ems.record.domain.EmsIOTData;
import com.ruoyi.ems.record.domain.EmsIOTInstantMonitorData;
import org.springframework.security.access.prepost.PreAuthorize;
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.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.ems.record.domain.TWTempertureData;
import com.ruoyi.ems.record.service.ITWTempertureDataService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 物联网实时数据Controller
 * 
 * @author Caoql
 * @date 2024-08-21
 */
@RestController
@RequestMapping("/ems/record/recordIOTInstant")
public class TWTempertureDataController extends BaseController
{
    @Autowired
    private ITWTempertureDataService tWTempertureDataService;
    @Autowired
    private IEmsBaseMonitorInfoService emsBaseMonitorInfoService;
    @Autowired
    private IEmsBaseEnergyTypeService emsBaseEnergyTypeService;

    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * 查询物联网实时数据列表
     */
    @PreAuthorize("@ss.hasPermi('ems/record:recordIOTInstant:list')")
    @GetMapping("/list")
    public TableDataInfo list(TWTempertureData tWTempertureData)
    {
        startPage();
        List<TWTempertureData> list = tWTempertureDataService.selectTWTempertureDataList(tWTempertureData);
        return getDataTable(list);
    }

    /**
     * 查询物联网设备实时数据
     * @param tWTempertureData
     * @return
     */
    @GetMapping("/iotInstantList")
    public AjaxResult iotInstantList(TWTempertureData tWTempertureData){
        EmsIOTData emsIOTData = new EmsIOTData();
        int energyTypeid = Integer.parseInt(emsBaseMonitorInfoService.selectEmsBaseMonitorTypeByMonitorCode(tWTempertureData.getMonitorId()));
        String energyName = emsBaseEnergyTypeService.queryEnergyNameByEnergyTypeId(energyTypeid);
        if("温湿度".equals(energyName)){
            emsIOTData.monitorTypeArr.add("温度");
            emsIOTData.monitorTypeArr.add("湿度");
        }
        else{
            emsIOTData.monitorTypeArr.add(energyName);
        }
        emsIOTData.setType("line");
        emsIOTData.setSmooth(true);
        emsIOTData.setShowAllSymbol(true);
        emsIOTData.setSymbol("circle");
        emsIOTData.setSymbolSize(2);
        List<TWTempertureData> list = tWTempertureDataService.selectIotInstantList(tWTempertureData);
        emsIOTData.setDataList(list);
        return success(emsIOTData);
    }

    /**
     * 查询物联网设备实时监控数据
     * @param monitorCodeList
     * @return
     */
    @GetMapping("/iotInstantMonitoring")
    public AjaxResult iotInstantMonitoring(String monitorCodeList){
        List<TWTempertureData> list = new ArrayList<TWTempertureData>();
        if(StringUtils.isNotEmpty(monitorCodeList)){
            String[] split = monitorCodeList.split(",");
            for (String monitorId : split) {

                TWTempertureData tWTempertureData = new TWTempertureData();
                tWTempertureData.setMonitorId(monitorId);
                Map<String,Object> params = new HashMap<>();

                Calendar calendar = Calendar.getInstance();
                calendar.add(Calendar.MINUTE,-5);
                Calendar startTime = (Calendar) calendar.clone();
                params.put("beginRecordTime",sdf.format(startTime.getTime()));
                params.put("endRecordTime",sdf.format(new Date()));
                tWTempertureData.setParams(params);

                List<TWTempertureData> twTempertureData = tWTempertureDataService.selectIotInstantList(tWTempertureData);
                if(twTempertureData.size()>0){
                    Optional<TWTempertureData> first = twTempertureData.stream().sorted(Comparator.comparing(TWTempertureData::getRecodeTime)).findFirst();

                    list.add(first.get());
                }


            }
        }

        System.out.println(JSONArray.toJSONString(list));
        return success(list);
    }

    /**
     * 导出物联网实时数据列表
     */
    @PreAuthorize("@ss.hasPermi('ems/record:recordIOTInstant:export')")
    @Log(title = "物联网实时数据", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TWTempertureData tWTempertureData)
    {
        List<TWTempertureData> list = tWTempertureDataService.selectTWTempertureDataList(tWTempertureData);
        ExcelUtil<TWTempertureData> util = new ExcelUtil<TWTempertureData>(TWTempertureData.class);
        util.exportExcel(response, list, "物联网实时数据数据");
    }

    /**
     * 获取物联网实时数据详细信息
     */
    @PreAuthorize("@ss.hasPermi('ems/record:recordIOTInstant:query')")
    @GetMapping(value = "/{objid}")
    public AjaxResult getInfo(@PathVariable("objid") Long objid)
    {
        return success(tWTempertureDataService.selectTWTempertureDataByObjid(objid));
    }

    /**
     * 新增物联网实时数据
     */
    @PreAuthorize("@ss.hasPermi('ems/record:recordIOTInstant:add')")
    @Log(title = "物联网实时数据", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TWTempertureData tWTempertureData)
    {
        tWTempertureData.setCreateBy(getUsername());
        return toAjax(tWTempertureDataService.insertTWTempertureData(tWTempertureData));
    }

    /**
     * 修改物联网实时数据
     */
    @PreAuthorize("@ss.hasPermi('ems/record:recordIOTInstant:edit')")
    @Log(title = "物联网实时数据", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TWTempertureData tWTempertureData)
    {
        tWTempertureData.setUpdateBy(getUsername());
        return toAjax(tWTempertureDataService.updateTWTempertureData(tWTempertureData));
    }

    /**
     * 删除物联网实时数据
     */
    @PreAuthorize("@ss.hasPermi('ems/record:recordIOTInstant:remove')")
    @Log(title = "物联网实时数据", businessType = BusinessType.DELETE)
	@DeleteMapping("/{objids}")
    public AjaxResult remove(@PathVariable Long[] objids)
    {
        return toAjax(tWTempertureDataService.deleteTWTempertureDataByObjids(objids));
    }

    /**
     * 查询物联网实时分组数据列表
     */
    @PreAuthorize("@ss.hasPermi('ems/record:recordIOTInstant:list')")
    @PostMapping("/selectLastTWTempertureDataList")
    public TableDataInfo selectLastTWTempertureDataList(TWTempertureData tWTempertureData)
    {
        List<TWTempertureData> list = tWTempertureDataService.selectLastTWTempertureDataList(tWTempertureData);
        return getDataTable(list);
    }

}
