package cn.iocoder.yudao.module.pms.service.iotdevicerunlog;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.pms.controller.admin.iotdevicerunlog.vo.IotDeviceRunLogPageReqVO;
import cn.iocoder.yudao.module.pms.controller.admin.iotdevicerunlog.vo.IotDeviceRunLogRespVO;
import cn.iocoder.yudao.module.pms.controller.admin.iotdevicerunlog.vo.IotDeviceRunLogSaveReqVO;
import cn.iocoder.yudao.module.pms.dal.dataobject.iotdevicerunlog.IotDeviceRunLogDO;
import cn.iocoder.yudao.module.pms.dal.mysql.iotdevicemaxrunlog.IotDeviceMaxRunLogMapper;
import cn.iocoder.yudao.module.pms.dal.mysql.iotdevicerunlog.IotDeviceRunLogMapper;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;

import java.math.BigDecimal;
import java.util.*;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.pms.enums.ErrorCodeConstant.IOT_DEVICE_RUN_LOG_NOT_EXISTS;

/**
 * 设备运行数据记录 中间表 Service 实现类
 *
 * @author ruiqi
 */
@Service
@Validated
public class IotDeviceRunLogServiceImpl implements IotDeviceRunLogService {

    @Resource
    private IotDeviceRunLogMapper iotDeviceRunLogMapper;
    @Resource
    private IotDeviceMaxRunLogMapper iotDeviceMaxRunLogMapper;

    @Override
    public Long createIotDeviceRunLog(IotDeviceRunLogSaveReqVO createReqVO) {
        // 插入
        IotDeviceRunLogDO iotDeviceRunLog = BeanUtils.toBean(createReqVO, IotDeviceRunLogDO.class);
        iotDeviceRunLogMapper.insert(iotDeviceRunLog);
        // 返回
        return iotDeviceRunLog.getId();
    }

    @Override
    public void updateIotDeviceRunLog(IotDeviceRunLogSaveReqVO updateReqVO) {
        // 校验存在
        validateIotDeviceRunLogExists(updateReqVO.getId());
        // 更新
        IotDeviceRunLogDO updateObj = BeanUtils.toBean(updateReqVO, IotDeviceRunLogDO.class);
        iotDeviceRunLogMapper.updateById(updateObj);
    }

    @Override
    public void deleteIotDeviceRunLog(Long id) {
        // 校验存在
        validateIotDeviceRunLogExists(id);
        // 删除
        iotDeviceRunLogMapper.deleteById(id);
    }

    private void validateIotDeviceRunLogExists(Long id) {
        if (iotDeviceRunLogMapper.selectById(id) == null) {
            throw exception(IOT_DEVICE_RUN_LOG_NOT_EXISTS);
        }
    }

    @Override
    public IotDeviceRunLogDO getIotDeviceRunLog(Long id) {
        return iotDeviceRunLogMapper.selectById(id);
    }

    @Override
    public PageResult<IotDeviceRunLogDO> getIotDeviceRunLogPage(IotDeviceRunLogPageReqVO pageReqVO) {
        return iotDeviceRunLogMapper.selectPage(pageReqVO);
    }

    @Override
    public List<IotDeviceRunLogRespVO> distinctDevices(List<Long> ids, List<Long> deviceCategoryIds,
                                                       Map<Long, Long> deviceCategoryPair, String actualStartTime) {
        // 先根据设备分类集合查询出所有正常累积的 公里数 时长
        List<IotDeviceRunLogRespVO> normalCumulativeAttrs = iotDeviceRunLogMapper.normalCumulativeAttrs(deviceCategoryIds);
        List<IotDeviceRunLogRespVO> tempDeviceRunLogs = iotDeviceRunLogMapper.distinctDevices(ids, deviceCategoryIds, actualStartTime);
        Set<Long> categoryIds = new HashSet<>();
        if (CollUtil.isNotEmpty(normalCumulativeAttrs)) {
            normalCumulativeAttrs.forEach(attr -> {
                categoryIds.add(attr.getDeviceCategoryId());
            });
        }
        List<IotDeviceRunLogRespVO> normalAttrDeviceRunLogs = new ArrayList<>();
        if (CollUtil.isNotEmpty(tempDeviceRunLogs)) {
            tempDeviceRunLogs.forEach(runLog -> {
                if (deviceCategoryPair.containsKey(runLog.getDeviceId())) {
                    if (categoryIds.contains(deviceCategoryPair.get(runLog.getDeviceId()))) {
                        normalAttrDeviceRunLogs.add(runLog);
                    }
                }
            });
        }
        return normalAttrDeviceRunLogs;
    }

    @Override
    public List<IotDeviceRunLogRespVO> distinctDevicesSearch(List<Long> ids, List<Long> deviceCategoryIds,
                                                       Map<Long, Long> deviceCategoryPair, List<IotDeviceRunLogRespVO> runLogs) {
        // 先根据设备分类集合查询出所有正常累积的 公里数 时长
        List<IotDeviceRunLogRespVO> normalCumulativeAttrs = iotDeviceRunLogMapper.normalCumulativeAttrs(deviceCategoryIds);
        Set<Long> categoryIds = new HashSet<>();
        // key设备类别id   value单累计属性对象集合
        Map<Long, List<IotDeviceRunLogRespVO>> deviceCategoryRunLogPair = new HashMap<>();
        if (CollUtil.isNotEmpty(normalCumulativeAttrs)) {
            normalCumulativeAttrs.forEach(attr -> {
                categoryIds.add(attr.getDeviceCategoryId());
                Long categoryId = attr.getDeviceCategoryId();
                if (deviceCategoryRunLogPair.containsKey(categoryId)) {
                    List<IotDeviceRunLogRespVO> tempRunLogs = deviceCategoryRunLogPair.get(categoryId);
                    tempRunLogs.add(attr);
                    deviceCategoryRunLogPair.put(categoryId, tempRunLogs);
                } else {
                    List<IotDeviceRunLogRespVO> tempRunLogs = new ArrayList<>();
                    tempRunLogs.add(attr);
                    deviceCategoryRunLogPair.put(categoryId, tempRunLogs);
                }
            });
        }
        List<IotDeviceRunLogRespVO> normalAttrDeviceRunLogs = new ArrayList<>();
        if (CollUtil.isNotEmpty(runLogs)) {
            runLogs.forEach(runLog -> {
                if (deviceCategoryPair.containsKey(runLog.getDeviceId())) {
                    Long deviceCategoryId = deviceCategoryPair.get(runLog.getDeviceId());
                    if (categoryIds.contains(deviceCategoryId)) {
                        if (deviceCategoryRunLogPair.containsKey(deviceCategoryId)) {
                            List<IotDeviceRunLogRespVO> categoryRunLogs = deviceCategoryRunLogPair.get(deviceCategoryId);
                            categoryRunLogs.forEach(log -> {
                                if (("sc".equals(log.getPointCode()) || "gls".equals(log.getPointCode())) && runLog.getPointName().equals(log.getPointName())) {
                                    IotDeviceRunLogRespVO tempLog = new IotDeviceRunLogRespVO();
                                    tempLog.setDeviceId(runLog.getDeviceId());
                                    tempLog.setPointName(runLog.getPointName());
                                    if ("sc".equals(log.getPointCode())) {
                                        // 累计时长 属性
                                        tempLog.setTotalRunTime(runLog.getTotalRunTime());
                                        tempLog.setPointCode("sc");
                                    }
                                    if ("gls".equals(log.getPointCode())) {
                                        // 累计公里数 属性
                                        tempLog.setTotalMileage(runLog.getTotalRunTime());
                                        tempLog.setPointCode("gls");
                                    }
                                    // 避免 totalRunTime totalMileage NULL 值
                                    if (ObjUtil.isEmpty(tempLog.getTotalRunTime())) {
                                        tempLog.setTotalRunTime(BigDecimal.ZERO);
                                    }
                                    if (ObjUtil.isEmpty(tempLog.getTotalMileage())) {
                                        tempLog.setTotalMileage(BigDecimal.ZERO);
                                    }
                                    normalAttrDeviceRunLogs.add(tempLog);
                                }
                            });
                        }
                    }
                }
            });
        }
        return normalAttrDeviceRunLogs;
    }

    @Override
    public List<IotDeviceRunLogRespVO> multipleAccumulatedData(Collection<Long> deviceIds, Collection<String> attrNames, String actualStartTime) {
        return iotDeviceRunLogMapper.multipleAccumulatedData(deviceIds, attrNames, actualStartTime);
    }

    @Override
    public List<IotDeviceRunLogRespVO> deviceAttrRunLogsSearch(List<Long> deviceIds) {
        List<IotDeviceRunLogRespVO> multiTotalAttrRunLogs = iotDeviceRunLogMapper.distinctDevicesSearch(deviceIds);;
        return multiTotalAttrRunLogs;
    }

}