package iot.lidee.iot.tdengine.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import iot.lidee.common.utils.DateUtils;
import iot.lidee.iot.domain.Device;
import iot.lidee.iot.domain.DeviceLog;
import iot.lidee.iot.model.DeviceStatistic;
import iot.lidee.iot.model.HistoryModel;
import iot.lidee.iot.model.ThingsModelLogCountVO;
import iot.lidee.iot.model.param.DataCenterParam;
import iot.lidee.iot.tdengine.service.ILogService;
import iot.lidee.iot.model.MonitorModel;
import iot.lidee.iot.mapper.TDDeviceLogMapper;
import iot.lidee.iot.tdengine.service.model.TdLogDto;
import iot.lidee.iot.util.SnowflakeIdWorker;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 类名: TdengineLogServiceImpl
 * 描述: TDengine存储日志数据实现类
 * 时间: 2022/5/22,0022 13:38
 * 开发人: admin
 */
@Slf4j
@Primary
@ConditionalOnProperty(name = "spring.datasource.dynamic.datasource.taos.enabled", havingValue = "true")
@DS("taos")
@Service("Tdengine")
public class TdengineLogServiceImpl implements ILogService {

    @Autowired
    private TDDeviceLogMapper tDDeviceLogMapper;

    private SnowflakeIdWorker snowflakeIdWorker = new SnowflakeIdWorker(1);

    @Value("${spring.datasource.dynamic.datasource.taos.dbName}")
    private String dbName;


    @Override
    public int createSTable(String database) {
        return tDDeviceLogMapper.createSTable(database);
    }

    /***
     * 新增设备日志
     * @return
     */
    @Override
    public int saveDeviceLog(DeviceLog deviceLog) {
        long logId = snowflakeIdWorker.nextId();
        deviceLog.setLogId(logId);
        return tDDeviceLogMapper.save(dbName, deviceLog);
    }

    /**
     * 批量保存日志
     */
    @Override
    public int saveBatch(TdLogDto dto) {
        return tDDeviceLogMapper.saveBatch(dbName, dto);
    }

    /***
     * 设备属性、功能、事件和监测数据总数
     * @return
     */
    @Override
    public DeviceStatistic selectCategoryLogCount(Device device) {
        DeviceStatistic statistic = new DeviceStatistic();
        Long property = tDDeviceLogMapper.selectPropertyLogCount(dbName, device);
        Long function = tDDeviceLogMapper.selectFunctionLogCount(dbName, device);
        Long event = tDDeviceLogMapper.selectEventLogCount(dbName, device);
        Long monitor = tDDeviceLogMapper.selectMonitorLogCount(dbName, device);
        statistic.setPropertyCount(property == null ? 0 : property);
        statistic.setFunctionCount(function == null ? 0 : function);
        statistic.setEventCount(event == null ? 0 : event);
        statistic.setMonitorCount(monitor == null ? 0 : monitor);
        return statistic;
    }

    /***
     * 日志列表
     * @return
     */
    @Override
    public List<DeviceLog> selectDeviceLogList(DeviceLog deviceLog) {
        return tDDeviceLogMapper.selectDeviceLogList(dbName, deviceLog);
    }

    /***
     * 监测数据列表
     * @return
     */
    @Override
    public List<MonitorModel> selectMonitorList(DeviceLog deviceLog) {
        if (deviceLog.getIdentity() != null) {
            deviceLog.setIdentity("%" + deviceLog.getIdentity() + "%");
        }
        return tDDeviceLogMapper.selectMonitorList(dbName, deviceLog);
    }

    /***
     * 根据设备ID删除设备日志
     * @return
     */
    @Override
    public int deleteDeviceLogByDeviceNumber(String deviceNumber) {
        return tDDeviceLogMapper.deleteDeviceLogByDeviceNumber(dbName, deviceNumber);
    }

    /**
     * 查询历史数据
     * is_Montor=1 或 is_history=1
     */
    @Override
    public Map<String, List<HistoryModel>> selectHistoryList(DeviceLog deviceLog) {
        List<HistoryModel> historyList = tDDeviceLogMapper.selectHistoryList(dbName, deviceLog);
        return historyList.stream().collect(Collectors.groupingBy(HistoryModel::getIdentity));
    }

    @Override
    public List<HistoryModel> listHistory(DeviceLog deviceLog) {
        // 8时区问题
//        if (StringUtils.isNotEmpty(deviceLog.getBeginTime())) {
//            LocalDateTime localDateTime = DateUtils.toLocalDateTime(deviceLog.getBeginTime(), DateUtils.YYYY_MM_DD_HH_MM_SS);
//            deviceLog.setBeginTime(DateUtils.localDateTimeToStr(localDateTime.minusHours(8), DateUtils.YYYY_MM_DD_HH_MM_SS));
//        }
//        if (StringUtils.isNotEmpty(deviceLog.getEndTime())) {
//            LocalDateTime localDateTime = DateUtils.toLocalDateTime(deviceLog.getEndTime(), DateUtils.YYYY_MM_DD_HH_MM_SS);
//            deviceLog.setEndTime(DateUtils.localDateTimeToStr(localDateTime.minusHours(8), DateUtils.YYYY_MM_DD_HH_MM_SS));
//        }
        List<HistoryModel> historyModelList = tDDeviceLogMapper.listHistory(dbName, deviceLog);
        for (HistoryModel historyModel : historyModelList) {
            historyModel.setTime(DateUtils.dateRemoveMs(historyModel.getTime()));
        }
        return historyModelList;
    }

    @Override
    public List<HistoryModel> listhistoryGroupByCreateTime(DeviceLog deviceLog) {
        return tDDeviceLogMapper.listhistoryGroupByCreateTime(dbName, deviceLog);
    }

    @Override
    public List<String> selectStatsValue(DeviceLog deviceLog) {
        return tDDeviceLogMapper.selectStatsValue(dbName, deviceLog);
    }

    @Override
    public List<ThingsModelLogCountVO> countThingsModelInvoke(DataCenterParam dataCenterParam) {
        return tDDeviceLogMapper.countThingsModelInvoke(dbName, dataCenterParam);
    }

    public DeviceLog selectLastReport(DeviceLog deviceLog) {
        return null;
    }
}
