package com.ruoyi.business.service.impl;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

import com.ruoyi.business.domain.HwDevice;
import com.ruoyi.business.domain.VO.*;
import com.ruoyi.business.mapper.HwDeviceMapper;
import com.ruoyi.business.mapper.HwElectronicFenceMapper;
import com.ruoyi.common.core.constant.TdEngineConstants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.tdengine.api.RemoteTdEngineService;
import com.ruoyi.tdengine.api.domain.DeviceStatus;
import com.ruoyi.tdengine.api.domain.TdSelectDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.business.mapper.HwMonitorUnitMapper;
import com.ruoyi.business.domain.HwMonitorUnit;
import com.ruoyi.business.service.IHwMonitorUnitService;

/**
 * 监控单元Service业务层处理
 *
 * @author YINQ
 * @date 2023-08-31
 */
@Service
public class HwMonitorUnitServiceImpl implements IHwMonitorUnitService
{
    @Autowired
    private HwMonitorUnitMapper hwMonitorUnitMapper;
    @Autowired
    private HwElectronicFenceMapper hwElectronicFenceMapper;
    @Autowired
    private RemoteTdEngineService remoteTdEgineService;
    @Autowired
    private HwDeviceMapper hwDeviceMapper;



    /**
     * 查询监控单元
     *
     * @param monitorUnitId 监控单元主键
     * @return 监控单元
     */
    @Override
    public HwMonitorUnit selectHwMonitorUnitByMonitorUnitId(Long monitorUnitId)
    {
        return hwMonitorUnitMapper.selectHwMonitorUnitByMonitorUnitId(monitorUnitId);
    }
    /**
     * 查询区域数量站场景区总数百分比
     * */
    @Override
    public List<HwMonitorUnitVo> selectMonitorPercentage() {
        List<HwMonitorUnitVo> list = hwMonitorUnitMapper.selectMonitorPercentage();
        List<HwMonitorUnitVo> hwScenes = hwMonitorUnitMapper.selectSceneNameById();
        int count = hwScenes.size();
        if (list.size()<=hwScenes.size()) {
            count = list.size();
        }
        for (int i = 0; i < count; i++) {
            for (int j = 0;j<count;j++){
                if (list.get(i).getSceneId().equals(hwScenes.get(i).getSceneId())){
                    list.get(i).setSceneName(hwScenes.get(i).getSceneName());
                }
            }
        }
        Integer value = 0;
        //
        Integer sums = 0;
        if (list.size()>5){
            for (int i = 4; i < list.size(); i++){
                if (list.get(i).sum==null){
                    list.get(i).sum = 0;
                }
                value = value+list.get(i).sum;
            }
        }
        for (int i = 0; i < list.size();i++){
            if (list.get(i).sum==null){
                list.get(i).sum = 0;
            }
            sums = sums+list.get(i).sum;
        }
        for (int i=0;i<list.size();i++){
            list.get(i).setPercentage((double) (list.get(i).getSum()/sums));
        }
        HwMonitorUnitVo  hwMonitorUnitVo = new HwMonitorUnitVo();
        hwMonitorUnitVo.setSceneName("其他");
        hwMonitorUnitVo.setSum(value);

        if (list.size()>5){
            list.add(5,hwMonitorUnitVo);
            return list.subList(0,5);
        }
        else {
            return list;
        }
    }

    //获取总的设备数量与监控单元数量
    @Override
    public AllNumsVo selectAllNums() {
        //监控单元
        String monitor =  hwMonitorUnitMapper.selectSubSetNums();
        String integer = hwMonitorUnitMapper.selectDeviceNums();
        System.out.println(monitor+"   dsaas "+integer);
        Integer monitor1 = 0;
        Integer monitor2 = 0;

        AllNumsVo vo = new AllNumsVo();
        if (monitor == null){
            monitor1 = 0;
        }
        else {
            monitor1 = Integer.valueOf(monitor);
        }
        if (integer == null){
            monitor2 = 0;
        }
        else {
            monitor2 = Integer.valueOf(integer);
        }
        vo.setSubSum(monitor1);
        vo.setSum(monitor2);


        return vo;
    }



    @Override
    public List<AllNumsVo> selectSenceAllNums() {
        List<AllNumsVo> allNumsVos = hwMonitorUnitMapper.selectAllNums();
        List<AllNumsVo> allNums = hwMonitorUnitMapper.selectsum();
        for (int i=0;i< allNums.size();i++){
            for (int j=0;j< allNums.size();j++){
                if (allNums.get(i).getSceneId().equals(allNumsVos.get(i).getSceneId())){
                    allNums.get(i).setSubSum(allNumsVos.get(i).getSubSum());
                }
            }
        }
        return allNums;
    }

    @Override
    public List<HwMonitorUnit> selectLimitSubMonitorUnit() {

        List<HwMonitorUnit> hwMonitorUnits = hwMonitorUnitMapper.selectLimitSubMonitorUnit();
        return hwMonitorUnits;
    }

    @Override
    public List<AlarmStatsVo> selectAlarmStats() {
        return hwMonitorUnitMapper.selectAlarmStats();
    }


    /**
     * 查询监控单元列表
     *
     * @param hwMonitorUnit 监控单元
     * @return 监控单元
     */
    @Override
    public List<HwMonitorUnit> selectHwMonitorUnitList(HwMonitorUnit hwMonitorUnit)
    {
        return hwMonitorUnitMapper.selectHwMonitorUnitList(hwMonitorUnit);
    }

    @Override
    public SubDeviceSumVo selectSubDeviceSum(Long sceneId) {
        int SubSum = hwMonitorUnitMapper.selectSubDeviceSum(sceneId);
        List<HwDevice> hwDevices = hwDeviceMapper.selectDeviceNum(sceneId);
        int onlineDevice = 0;
        for (int i = 0;i<hwDevices.size();i++){
            if (hwDevices.get(i).getActiveStatus().equals("1")&&hwDevices.get(i).getDeviceStatus().equals("1")){
                onlineDevice = onlineDevice+1;
            }
        }
        SubDeviceSumVo subDeviceSumVo = new SubDeviceSumVo();
        subDeviceSumVo.setSubSum(String.valueOf(SubSum));
        subDeviceSumVo.setDeviceNum(String.valueOf(hwDevices.size()));
        subDeviceSumVo.setOnlineDeviceNum(String.valueOf(onlineDevice));
        return subDeviceSumVo;

    }
//todo 电子围栏
    @Override
    public Integer selectElectronicNum(Long sceneId) {
        List<Long> longs = hwMonitorUnitMapper.selectEleInScene(sceneId);
        return null;
    }



    @Override
    public HwMonitorUnit selectHwmonitorUnitSub(Long monitorUnitId) {
        return  hwMonitorUnitMapper.selectHwMonitorUnitByMonitorUnitId(monitorUnitId);
    }

    @Override
    // 加一个begintime参数，endtime参数 stream时间戳 从开始时间0点开始，结束时间23.59.59结束
    public int[] selectTdengine(String beginTime, String endTime, Long sceneId) {
        DeviceStatus queryDeviceStatus = new DeviceStatus();

        Map<String, Object> params = queryDeviceStatus.getParams();
        DateTimeFormatter ofPattern = DateTimeFormatter.ofPattern("yyyy-MM-dd", Locale.CHINA);
        LocalDate parse = LocalDate.parse(beginTime, ofPattern);
        long begintime = parse.atStartOfDay().toInstant(ZoneOffset.of("+8")).toEpochMilli();

        DateTimeFormatter ofPattern1 = DateTimeFormatter.ofPattern("yyyy-MM-dd", Locale.CHINA);
        LocalDate parse1 = LocalDate.parse(endTime, ofPattern);
        long endtime = LocalDateTime.of(parse1, LocalTime.MAX).toInstant(ZoneOffset.of("+8")).toEpochMilli();

        params.put("beginTime",begintime);
        params.put("endTime", endtime);
        queryDeviceStatus.setParams(params);
        if (sceneId != null) {
            queryDeviceStatus.setSceneId(sceneId);
        }

        int sum = 0;
        int values[] = new int[10];
        //todo 使用id(以解决)
        //map key时间戳，value List<DeviceStatus>  对象
        List<DeviceStatus> list = (List<DeviceStatus>) remoteTdEgineService.getOnlineDevicesGroupByDay(queryDeviceStatus);
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getDeviceType()==1) {
                 values[i]=hwMonitorUnitMapper.selectReleatedDeviceIdNums(list.get(i).getDeviceId());
            }
            else {
                values[i] = hwDeviceMapper.selectSumDeviceFlagNot0();
            }
        }
        return values;

            //设备类型==网关 根据releated_device_id = 网关设备设备id查询个数
            //网关子设备数+非网关设备数（getDeviceType()！=1）
    }

    @Override
    public R<Map<String, Map<String, Object>>> selectLatestDataByTags(Long monitorUnitId) {
//
        R<Map<String, Map<String, Object>>> latestDataByTags = new R<Map<String,Map<String, Object>>>();
        List<HwDevice> hwDevices = hwDeviceMapper.selectDeviceByMonitorId(monitorUnitId);
        TdSelectDto tdSelectDto = new TdSelectDto();
        for (int i = 0; i < hwDevices.size(); i++){
        tdSelectDto.setDatabaseName(TdEngineConstants.PLATFORM_DB_NAME);
        tdSelectDto.setTableName(TdEngineConstants.getDeviceDataTableName(hwDevices.get(i).getDeviceId()));
        tdSelectDto.setTagsName(hwDevices.get(i).getDeviceCode());

            latestDataByTags  = remoteTdEgineService.getLatestDataByTags(tdSelectDto);
        }
        return latestDataByTags;
        }

//todo SysDeptServiceImpl类中的递归方法recursionFn(以实现)
@Override
public List<HwMonitorUnit> selectTreeList(List<HwMonitorUnit> hwMonitorUnits) {
    List<HwMonitorUnit> returnList =  new ArrayList<>();
    List<Long> tempList = hwMonitorUnits.stream().map(HwMonitorUnit::getMonitorUnitId).collect(Collectors.toList());

    for (HwMonitorUnit hwMonitorUnit:hwMonitorUnits){
        if (!tempList.contains(hwMonitorUnit.getParentId()))
        recursionFn(hwMonitorUnits,hwMonitorUnit);
        returnList.add(hwMonitorUnit);
    }

    return returnList;
}
    private void recursionFn(List<HwMonitorUnit> list, HwMonitorUnit t)
    {
        // 得到子节点列表
        List<HwMonitorUnit> childList = getChildList(list, t);
        t.setChild(childList);
        for (HwMonitorUnit tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }
    private List<HwMonitorUnit> getChildList(List<HwMonitorUnit> list, HwMonitorUnit t)
    {
        List<HwMonitorUnit> tlist = new ArrayList<HwMonitorUnit>();
        Iterator<HwMonitorUnit> it = list.iterator();
        while (it.hasNext())
        {
            HwMonitorUnit n = (HwMonitorUnit) it.next();
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().longValue() == t.getMonitorUnitId().longValue())
            {
                tlist.add(n);
            }
        }
        return tlist;
    }
    private boolean hasChild(List<HwMonitorUnit> list, HwMonitorUnit t)
    {
        return getChildList(list, t).size() > 0 ? true : false;
    }

    /**
     * 新增监控单元
     *
     * @param hwMonitorUnit 监控单元
     * @return 结果
     */
    @Override
    public int insertHwMonitorUnit(HwMonitorUnit hwMonitorUnit)
    {
        hwMonitorUnit.setCreateTime(DateUtils.getNowDate());
        return hwMonitorUnitMapper.insertHwMonitorUnit(hwMonitorUnit);
    }

    /**
     * 修改监控单元
     *
     * @param hwMonitorUnit 监控单元
     * @return 结果
     */
    @Override
    public int updateHwMonitorUnit(HwMonitorUnit hwMonitorUnit)
    {
        hwMonitorUnit.setUpdateTime(DateUtils.getNowDate());
        return hwMonitorUnitMapper.updateHwMonitorUnit(hwMonitorUnit);
    }

    /**
     * 批量删除监控单元
     *
     * @param monitorUnitIds 需要删除的监控单元主键
     * @return 结果
     */
    @Override
    public int deleteHwMonitorUnitByMonitorUnitIds(Long[] monitorUnitIds)
    {
        return hwMonitorUnitMapper.deleteHwMonitorUnitByMonitorUnitIds(monitorUnitIds);
    }

    /**
     * 删除监控单元信息
     *
     * @param monitorUnitId 监控单元主键
     * @return 结果
     */
    @Override
    public int deleteHwMonitorUnitByMonitorUnitId(Long monitorUnitId)
    {
        return hwMonitorUnitMapper.deleteHwMonitorUnitByMonitorUnitId(monitorUnitId);
    }
}

//remoteTdEngineSevice.getOnlineDevicesGroupByDay方法获取
//        参数实例：
//        //        params.put("beginTime", beginTime);
////        params.put("endTime", endTime);
////        queryDeviceStatus.setParams(params);
////        if (sceneId != null) {
////            queryDeviceStatus.setSceneId(sceneId);
////        }
//
//        这是IDEA参数传的参数Content-Type: application/json
//        {
//        "params": {  "beginTime":1666666666666,"endTime":1766666666666  }
//
//        }
//
//        如果在IDEA测试可以{
//        "params": {"databaseName":"db_scene_1","superTableName":"st_ds_1",
//        "beginTime":1666666666666,"endTime":1766666666666  }
//        }
