package com.casic.PgInterface.devData.manager;

import com.casic.PgInterface.core.hibernate.HibernateEntityDao;
import com.casic.PgInterface.devData.domain.PgSh;
import com.casic.PgInterface.devData.dto.PgHistoryDataDto;
import com.casic.PgInterface.devData.dto.PgShDto;
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 PgShManager extends HibernateEntityDao<PgSh> {

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

        try {
            String sql="select distinct to_char(upTime,'yyyy-MM-dd'),sh from PG_SH 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 PgShDto getNewestShData(PgDevice pgDevice) {

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

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


}
