package com.casic.PgInterface.devData.manager;

import com.casic.PgInterface.core.hibernate.HibernateEntityDao;
import com.casic.PgInterface.devData.domain.PgO2;
import com.casic.PgInterface.devData.dto.PgHistoryDataDto;
import com.casic.PgInterface.devData.dto.PgO2Dto;
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 PgO2Manager extends HibernateEntityDao<PgO2> {

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

        try {
            String sql="select distinct to_char(upTime,'yyyy-MM-dd'),o2 from PG_O2 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 PgO2Dto getNewestO2Data(PgDevice pgDevice) {

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

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


}
