package cn.iocoder.yudao.module.iot.service.deviceoperationrecord;

import cn.iocoder.yudao.module.iot.controller.admin.deviceoperationrecord.utils.TimeConverterUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import cn.iocoder.yudao.module.iot.controller.admin.deviceoperationrecord.vo.*;
import cn.iocoder.yudao.module.iot.dal.dataobject.deviceoperationrecord.DeviceOperationRecordDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.iot.dal.mysql.deviceoperationrecord.DeviceOperationRecordMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.iot.enums.ErrorCodeConstants.*;

/**
 * 运行记录 Service 实现类
 *
 * @author 必硕科技
 */
@Service
@Validated
@Slf4j
public class DeviceOperationRecordServiceImpl implements DeviceOperationRecordService {

    @Resource
    private DeviceOperationRecordMapper deviceOperationRecordMapper;

    @Override
    public Long createDeviceOperationRecord(DeviceOperationRecordSaveReqVO createReqVO) {
        // 插入
        DeviceOperationRecordDO deviceOperationRecord = BeanUtils.toBean(createReqVO, DeviceOperationRecordDO.class);
        deviceOperationRecordMapper.insert(deviceOperationRecord);
        // 返回
        return deviceOperationRecord.getId();
    }

    @Override
    public void updateDeviceOperationRecord(DeviceOperationRecordSaveReqVO updateReqVO) {
        // 校验存在
        validateDeviceOperationRecordExists(updateReqVO.getId());
        // 更新
        DeviceOperationRecordDO updateObj = BeanUtils.toBean(updateReqVO, DeviceOperationRecordDO.class);
        deviceOperationRecordMapper.updateById(updateObj);
    }

    @Override
    public void deleteDeviceOperationRecord(Long id) {
        // 校验存在
        validateDeviceOperationRecordExists(id);
        // 删除
        deviceOperationRecordMapper.deleteById(id);
    }

    private void validateDeviceOperationRecordExists(Long id) {
        if (deviceOperationRecordMapper.selectById(id) == null) {
            throw exception(DEVICE_OPERATION_RECORD_NOT_EXISTS);
        }
    }

    @Override
    public DeviceOperationRecordDO getDeviceOperationRecord(Long id) {
        return deviceOperationRecordMapper.selectById(id);
    }

    @Override
    public PageResult<DeviceOperationRecordDO> getDeviceOperationRecordPage(DeviceOperationRecordPageReqVO pageReqVO) {
        return deviceOperationRecordMapper.selectPage(pageReqVO);
    }

    @Override
    public PageResult<DeviceTotalTimeRecordRespVO> deviceOperationPage(DeviceTotalTimeRecordReqVO pageReqVO) {

        Page<DeviceTotalTimeRecordRespVO> page = new Page<>(pageReqVO.getPageNo(), pageReqVO.getPageSize());
        IPage<DeviceTotalTimeRecordRespVO> deviceOperationRecordRespVOIPage = deviceOperationRecordMapper.deviceOperationPage(page,pageReqVO);
        // 计算和转换
        if (deviceOperationRecordRespVOIPage != null && !deviceOperationRecordRespVOIPage.getRecords().isEmpty()) {
            calculateAndSetConvertedValues(deviceOperationRecordRespVOIPage.getRecords(),pageReqVO);
        }


        return new PageResult<>(deviceOperationRecordRespVOIPage.getRecords(), deviceOperationRecordRespVOIPage.getTotal());

    }

    private void calculateAndSetConvertedValues(List<DeviceTotalTimeRecordRespVO> records,DeviceTotalTimeRecordReqVO deviceTotalTimeRecordReqVO) {
        for (DeviceTotalTimeRecordRespVO record : records) {
            try {
                //添加时间字段
                if (StringUtils.isNotBlank(deviceTotalTimeRecordReqVO.getStartTime())){
                    record.setStartTime(deviceTotalTimeRecordReqVO.getStartTime());
                }
                if (StringUtils.isNotBlank(deviceTotalTimeRecordReqVO.getEndTime())){
                    record.setEndTime(deviceTotalTimeRecordReqVO.getEndTime());
                }

                // 获取原始秒数
                double runningTimeSec = record.getTotalRunningTime();
                double standbyTimeSec = record.getTotalStandbyTime();
                double faultTimeSec = record.getTotalFaultTime();
                double warningTimeSec = record.getTotalWarningTime();

                // 1. 转换为小时
                double runningHours = TimeConverterUtil.secondsToHours(runningTimeSec, 2);
                double standbyHours = TimeConverterUtil.secondsToHours(standbyTimeSec, 2);
                double faultHours = TimeConverterUtil.secondsToHours(faultTimeSec, 2);
                double warningHours = TimeConverterUtil.secondsToHours(warningTimeSec, 2);

                // 2. 计算稼动率
                double utilizationRate = TimeConverterUtil.calculateUtilizationRate(
                        runningTimeSec, standbyTimeSec, faultTimeSec, warningTimeSec
                );

                // 3. 设置转换后的值（将原来的秒数值覆盖为小时值）
                record.setTotalRunningTime(runningHours);
                record.setTotalStandbyTime(standbyHours);
                record.setTotalFaultTime(faultHours);
                record.setTotalWarningTime(warningHours);
                record.setUtilizationRate(TimeConverterUtil.getPercentString(utilizationRate));

            } catch (Exception e) {
                log.error("计算设备{}时间转换时出错: {}", record.getDeviceCode(), e.getMessage());
                // 设置默认值
                setDefaultValues(record);
            }
        }
    }

    private void setDefaultValues(DeviceTotalTimeRecordRespVO record) {
        record.setTotalRunningTime(0.0);
        record.setTotalStandbyTime(0.0);
        record.setTotalFaultTime(0.0);
        record.setTotalWarningTime(0.0);
        record.setUtilizationRate("0%");
    }

}