package com.casic.PgInterface.devData.manager;

import com.casic.PgInterface.core.hibernate.HibernateEntityDao;
import com.casic.PgInterface.devData.domain.PgCh4;
import com.casic.PgInterface.devData.dto.PgCh4Dto;
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 PgCh4Manager extends HibernateEntityDao<PgCh4> {

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

        try {
            String sql="select distinct to_char(upTime,'yyyy-MM-dd'),ch4 from PG_CH4 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 PgCh4Dto getNewestCH4Data(PgDevice pgDevice) {

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

            List<Object[]> pgCh4List=(List<Object[]>)this.getSession().createSQLQuery(sql).list();

            if(pgCh4List.size()==0) return null;
            Object[] objects = pgCh4List.get(0);
            PgCh4Dto pgCh4Dto=new PgCh4Dto(null);
            pgCh4Dto.setId(objects[0].toString());
            pgCh4Dto.setValue(objects[1].toString());
            pgCh4Dto.setLogTime(objects[2].toString());
            pgCh4Dto.setUpTime(objects[3].toString());
            pgCh4Dto.setDevCode(pgDevice.getDevCode());
            pgCh4Dto.setDevName(pgDevice.getAssetName());
            //获取devName和devCode
            return pgCh4Dto;

        }
        catch(Exception ex)
        {
            return null;
        }

    }

}