package com.casic.PgInterface.devData.manager;

import com.casic.PgInterface.core.hibernate.HibernateEntityDao;
import com.casic.PgInterface.devData.domain.PgCo;
import com.casic.PgInterface.devData.dto.PgCoDto;
import com.casic.PgInterface.devData.dto.PgHistoryDataDto;
import com.casic.PgInterface.devTable.domain.PgDevice;
import org.springframework.stereotype.Service;

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

/**
 * Created by yxw on 2017/11/28.
 */
@Service
public class PgCoManager extends HibernateEntityDao<PgCo> {

    //获取设备时间段内所有的监测数据
    public List<PgHistoryDataDto> getAllCoData(PgDevice pgDevice,String startDate,String endDate) {
        try {
            String sql="select distinct to_char(upTime,'yyyy-MM-dd'),co from PG_CO 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<PgHistoryDataDto> pgHistoryDataDtoList=new ArrayList<>();
            List<Object[]> objects=this.getSession().createSQLQuery(sql).list();
            for(Object[] objects1:objects){
                PgHistoryDataDto pgHistoryDataDto=new PgHistoryDataDto();
                pgHistoryDataDto.setUpTime(String.valueOf(objects1[0]));
                pgHistoryDataDto.setValue(String.valueOf(objects1[1]));

                pgHistoryDataDtoList.add(pgHistoryDataDto);
            }

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

    //获取设备最新数据
    public PgCoDto getNewestCoData(PgDevice pgDevice) {
        try {
            String sql="select id,CO,LOGTIME,UPTIME from PG_CO where PGDEVICEID = '"+pgDevice.getId()+"' AND rownum < 2 order by UPTIME";

            List<Object[]> pgCoList=(List<Object[]>)this.getSession().createSQLQuery(sql).list();
            if(pgCoList.size()==0) return null;
            Object[] objects = pgCoList.get(0);
            PgCoDto pgCoDto=new PgCoDto(null);
            pgCoDto.setId(objects[0].toString());
            pgCoDto.setValue(objects[1].toString());
            pgCoDto.setLogTime(objects[2].toString());
            pgCoDto.setUpTime(objects[3].toString());
            pgCoDto.setDevCode(pgDevice.getDevCode());
            pgCoDto.setDevName(pgDevice.getAssetName());
            //获取devName和devCode
            return pgCoDto;
        }
        catch(Exception ex)
        {
            return null;
        }
    }


}
