package com.zcxk.rmcp.web.service.impl;

import com.zcxk.core.common.exception.BusinessException;
import com.zcxk.core.common.pojo.PageResult;
import com.zcxk.core.oauth2.util.UserUtil;
import com.zcxk.rmcp.api.dto.meterreadrecord.MeterReadRecordDeviceDto;
import com.zcxk.rmcp.api.dto.meterreadrecord.MeterReadRecordDto;
import com.zcxk.rmcp.api.dto.meterreadrecord.MeterReadRecordUpdateDto;
import com.zcxk.rmcp.api.enums.RmcpErrorEnum;
import com.zcxk.rmcp.api.vo.MeterReadRecordVo;
import com.zcxk.rmcp.core.dao.mongo.MeterReadRecordDao;
import com.zcxk.rmcp.core.mongo.MeterReadRecord;
import com.zcxk.rmcp.web.service.MeterReadRecordService;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @author Andy
 * @version V1.0
 * @description: 抄表记录
 * @date 2021/7/22
 **/
@Service
public class MeterReadRecordServiceImpl implements MeterReadRecordService {

    @Resource
    private MeterReadRecordDao meterReadRecordDao;


    @Override
    public void saveMeterReadRecord(MeterReadRecord readRecord) {
        for (MeterReadRecord.MeterReadInfo datum : readRecord.getData()) {
            datum.setReadTime(new Date().getTime());
        }
        meterReadRecordDao.saveMeterReadRecord(readRecord);
    }

    @Override
    public long updateReadData(MeterReadRecordUpdateDto dto) {
        long total =  meterReadRecordDao.updateReadData(dto);
        if (total == 0) {
            throw BusinessException.builder(RmcpErrorEnum.RMCP_UPDATE_FAIL);
        }
        return total;
    }

    @Override
    public PageResult<MeterReadRecordVo> pageMeterReadRecord(MeterReadRecordDto dto) {
        return meterReadRecordDao.pageMeterReadRecord(dto, UserUtil.getCurrentUser().getUserCondition(),
                PageRequest.of(dto.getPageNum() - 1, dto.getPageSize()));
    }

    @Override
    public List<MeterReadRecordVo> listMeterReadRecord(MeterReadRecordDto dto) {
        return meterReadRecordDao.listMeterReadRecord(dto, UserUtil.getCurrentUser().getUserCondition());
    }

    @Override
    public List<MeterReadRecordVo> listSingleDeviceTimeWaterConsumption(MeterReadRecordDeviceDto dto) {
        return meterReadRecordDao.queryDeviceMeterReadRecordWithCondtion(dto.getDeviceId(), dto.getStartDate(),dto.getEndDate());
    }
}
