package com.casic.PgInterface.devData.manager;

/**
 * Created by yxw on 2017/11/28.
 */

import com.casic.PgInterface.core.hibernate.HibernateEntityDao;
import com.casic.PgInterface.devData.domain.PgTempHum;
import com.casic.PgInterface.devData.dto.PgHistoryTempDto;
import com.casic.PgInterface.devData.dto.PgTempHumDto;
import com.casic.PgInterface.devTable.domain.PgDevice;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class PgTempHumManager extends HibernateEntityDao<PgTempHum> {

    //获取设备时间段内所有的监测数据
    public List<PgHistoryTempDto> getAllTempHumData(PgDevice pgDevice, String startDate, String endDate) {

        try {
            String sql="select distinct to_char(upTime,'yyyy-MM-dd'),temp,hum from PG_TEMPHUM where PGDEVICEID="+pgDevice.getId();
            if(startDate!=null)
                sql+=" and upTime > to_date('"+startDate+"','yyyy-MM-dd')";
            if(endDate!=null)
                sql+=" and upTime < to_date('"+endDate+"','yyyy-MM-dd')";

            List<PgHistoryTempDto> pgHistoryTempDtoList=new ArrayList<>();
            List<Object[]> objects=this.getSession().createSQLQuery(sql).list();
            for(Object[] objects1:objects){
                PgHistoryTempDto pgHistoryTempDto=new PgHistoryTempDto();
                pgHistoryTempDto.setUpTime(String.valueOf(objects1[0]));
                pgHistoryTempDto.setTemp(String.valueOf(objects1[1]));
                pgHistoryTempDto.setHum(String.valueOf(objects1[2]));

                pgHistoryTempDtoList.add(pgHistoryTempDto);
            }

            return pgHistoryTempDtoList;
        }
        catch(Exception ex)
        {
            return null;
        }
    }

    //获取设备最新数据
    public PgTempHumDto getNewestTempHumData(PgDevice pgDevice) {

        try {
            String sql="select id,TEMP,HUM,LOGTIME,UPTIME from PG_TEMPHUM where PGDEVICEID = '"+pgDevice.getId()+"' AND  rownum < 2 order by UPTIME";

            List<Object[]> pgTempHumList=(List<Object[]>)this.getSession().createSQLQuery(sql).list();
            if(pgTempHumList.size()==0) return null;

            Object[] objects = pgTempHumList.get(0);
            PgTempHumDto pgTempHumDto=new PgTempHumDto(null);
            pgTempHumDto.setId(objects[0].toString());
            pgTempHumDto.setValueTemp(objects[1].toString());
            pgTempHumDto.setValueHum(objects[2].toString());
            pgTempHumDto.setLogTime(objects[3].toString());
            pgTempHumDto.setUpTime(objects[4].toString());
            pgTempHumDto.setDevCode(pgDevice.getDevCode());
            pgTempHumDto.setDevName(pgDevice.getAssetName());
            //获取devName和devCode
            return pgTempHumDto;
        }
        catch(Exception ex)
        {
            return null;
        }
    }

}