package com.casic.PgInterface.devTable.manager;

import com.casic.PgInterface.core.hibernate.HibernateEntityDao;
import com.casic.PgInterface.core.page.Page;
import com.casic.PgInterface.core.util.DateUtils;
import com.casic.PgInterface.core.util.StringUtils;
import com.casic.PgInterface.devTable.domain.PgAlarm;
import com.casic.PgInterface.devTable.domain.PgAlarmType;
import com.casic.PgInterface.devTable.domain.PgDevice;
import com.casic.PgInterface.devTable.dto.PgAlarmDto;
import com.casic.PgInterface.devTable.dto.PgAlarmTjDto;
import com.casic.PgInterface.patroler.dto.PgInPgInfoDto;
import com.casic.PgInterface.patroler.manager.PgInPgStatusManager;
import org.apache.poi.util.StringUtil;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Property;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * Created by yxw on 2017/10/30.
 */
@Service
public class PgAlarmManager extends HibernateEntityDao<PgAlarm> {

    @Resource
    private PgAlarmTypeManager pgAlarmTypeManager;

    @Resource
    private PgInPgStatusManager pgInPgStatusManager;

    public List<PgAlarmDto> getAlarmByTypeAndTime(String alarmType,String startTime,String endTime){
        try {
            Criteria criteria = createCriteria(PgAlarm.class);
            if (StringUtils.isNotBlank(alarmType)&&!alarmType.contains("全部")) {
                criteria.add(Restrictions.eq("alarmTypeId", pgAlarmTypeManager.getAlarmTypeByAlarmType(alarmType)));
            }

            if (StringUtils.isNotBlank(startTime)) {
                criteria.add(Restrictions.ge("alarmDate", DateUtils.sdf_day.parse(startTime)));
            }
            if (StringUtils.isNotBlank(endTime)) {
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(DateUtils.sdf_day.parse(endTime));
                calendar.add(Calendar.DATE, 1);
                criteria.add(Restrictions.le("alarmDate", calendar.getTime()));
            }
            criteria.add(Restrictions.eq("active", 1));
            criteria.addOrder(Order.desc("id"));

            List<PgAlarm> pgAlarmList=criteria.list();
            List<PgAlarmDto> pgAlarmDtoList=new ArrayList<PgAlarmDto>();
            for(PgAlarm pgAlarm : pgAlarmList)
            {
                pgAlarmDtoList.add(new PgAlarmDto(pgAlarm));
            }

            return pgAlarmDtoList;
        }
        catch(Exception e)
        {
            e.printStackTrace();
            return null;
        }
    }

    public int getAlarmNum(String isDevFault) {
        String hql = "select count(distinct alarmDevId) from PgAlarm pgAlarm ";

        if(StringUtils.isNotBlank(isDevFault)) {
            if (isDevFault.equals("true"))
                hql += " where pgAlarm.alarmTypeId.alarmType = '设备运行状态报警'";
            else
                hql += " where pgAlarm.alarmTypeId.alarmType != '设备运行状态报警'";
        }

        Object object = this.getSession().createQuery(hql).uniqueResult();
        return Integer.valueOf(object.toString());
    }

    public int getMonthAlarmNum(String isDevFault) {

        String hql = "select count(distinct pgAlarm.alarmDevId) from PgAlarm pgAlarm where to_char(pgAlarm.alarmDate, 'yyyy-mm')" +
                " = to_char(sysdate,'yyyy-mm')";

        if(isDevFault!=null) {
            if (isDevFault.equals("true"))
                hql += " and pgAlarm.alarmTypeId.alarmType = '设备运行状态报警'";
            else
                hql += " and pgAlarm.alarmTypeId.alarmType != '设备运行状态报警'";
        }
        Object object = this.getSession().createQuery(hql).uniqueResult();
        return Integer.parseInt(String.valueOf(object));
    }

    public int getWeekAlarmNum(String isDevFault) {

        String hql = "select count(distinct pgAlarm.alarmDevId) from PgAlarm pgAlarm where to_char(pgAlarm.alarmDate, 'iw')" +
                " = to_char(sysdate,'iw')";

        if(isDevFault!=null) {
            if (isDevFault.equals("true"))
                hql += " and pgAlarm.alarmTypeId.alarmType = '设备运行状态报警'";
            else
                hql += " and pgAlarm.alarmTypeId.alarmType != '设备运行状态报警'";
        }

        Object object = this.getSession().createQuery(hql).uniqueResult();
        return Integer.parseInt(String.valueOf(object));
    }

    public List<PgAlarmTjDto> getDayAlarmStatistic() {
        String today=DateUtils.sdf_day.format(new Date());
        String startDay=pgInPgStatusManager.getStartDayString();
        List<PgAlarmTjDto> pgAlarmTjDtoList = createDTO(startDay);

        String hql = "select count(distinct alarmDevId), to_char(pgAlarm.alarmDate, 'yyyy-mm-dd') from PgAlarm pgAlarm "
                +"where pgAlarm.alarmDate > to_date('"+startDay+"','yyyy-mm-dd') and pgAlarm.alarmDate < to_date('"+today+"','yyyy-mm-dd')"
                +" group by to_char(pgAlarm.alarmDate, 'yyyy-mm-dd') order by to_char(pgAlarm.alarmDate,'yyyy-mm-dd')";

        List<Object[]> objects = (List<Object[]>)this.getSession().createQuery(hql).list();
        for (int i = 0; i < objects.size(); i++) {
            for(PgAlarmTjDto pgAlarmTjDto:pgAlarmTjDtoList){
                if(pgAlarmTjDto.getAlarmDate().equals(objects.get(i)[1].toString()))
                    pgAlarmTjDto.setAlarmNum(objects.get(i)[0].toString());
            }
        }
        return pgAlarmTjDtoList;
    }

    public List<PgAlarmDto> getAlarmList(String isDevFault) {

        PgAlarmType pgAlarmType=pgAlarmTypeManager.getAlarmTypeByAlarmType("设备运行状态报警");

        String hql="from PgAlarm a where a.active = 1";

        if(StringUtils.isNotBlank(isDevFault))
            if(isDevFault.equals("true"))
                hql+=" and a.alarmTypeId = " + pgAlarmType.getId();
            else if(isDevFault.equals("false"))
                hql+=" and a.alarmTypeId != " + pgAlarmType.getId();
        Query query=this.getSession().createQuery(hql);

        List<PgAlarm>pgAlarmList=query.list();
        List<PgAlarmDto> pgAlarmDtoList=new ArrayList<>();
        for(PgAlarm pgAlarm : pgAlarmList)
        {
            pgAlarmDtoList.add(new PgAlarmDto(pgAlarm));
        }

        return pgAlarmDtoList;
    }

    //获取历史报警消息列表
    public  Map<String, Object> getAllAlarm(String alarmType,String partition,String startDay,String endDay,
                                            String alarmGrade,String isNew,int page,int rows) {

        Map<String, Object> resultMap = new HashMap<>();
        String msg="";

        try {
            Criteria criteria = createCriteria(PgAlarm.class);

            if (StringUtils.isNotBlank(partition)&&!partition.contains("全部")) {
                DetachedCriteria inCriteria = DetachedCriteria.forClass(PgDevice.class);
                inCriteria.add(Restrictions.eq("partition", partition));
                inCriteria.setProjection(Property.forName("id"));
                criteria.add(Property.forName("alarmDevId").in(inCriteria));
            }

            if (StringUtils.isNotBlank(alarmType)&&!alarmType.contains("全部")&&pgAlarmTypeManager.getAlarmTypeByAlarmType(alarmType)!=null)
                criteria.add(Restrictions.eq("alarmTypeId", pgAlarmTypeManager.getAlarmTypeByAlarmType(alarmType)));

            if (StringUtils.isNotBlank(startDay)) {
                criteria.add(Restrictions.ge("alarmDate", DateUtils.sdf_day.parse(startDay)));
            }
            if (StringUtils.isNotBlank(endDay)) {
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(DateUtils.sdf_day.parse(endDay));
                calendar.add(Calendar.DATE, 1);;
                criteria.add(Restrictions.le("alarmDate", calendar.getTime()));
            }

            if(StringUtils.isNotBlank(alarmGrade))
                criteria.add(Restrictions.eq("alarmGrade",alarmGrade));

            if(StringUtils.isNotBlank(isNew)) {
                if(isNew.equals("false"))
                criteria.add(Restrictions.eq("active", 0));
            else if(isNew.equals("true"))
                criteria.add(Restrictions.eq("active", 1));
            }
            criteria.addOrder(Order.desc("alarmGrade"));
            Page pg = pagedQuery(criteria, page, rows);

            List<PgAlarm> pgAlarmList = (List<PgAlarm>)pg.getResult();
            List<PgAlarmDto> pgAlarmDtoList = new ArrayList<>();
            for (PgAlarm pgAlarm : pgAlarmList) {
                pgAlarmDtoList.add(new PgAlarmDto(pgAlarm));
            }
            if(pgAlarmDtoList==null||pgAlarmDtoList.size()==0) {
                resultMap.put("msg", "没有报警信息");
                resultMap.put("code","0");
            }else {
                resultMap.put("code","200");
                resultMap.put("msg", "报警信息获取成功");
            }
            resultMap.put("count",pg.getTotalCount());
            resultMap.put("result",pgAlarmDtoList);
            return resultMap;
        }
        catch(Exception ex){
            ex.printStackTrace();
            return null;
        }

    }

    private List<PgAlarmTjDto> createDTO(String startDay) {
        List<PgAlarmTjDto> pgAlarmTjDtoList = new ArrayList<PgAlarmTjDto>();

        try {
            Date dt1 = DateUtils.sdf_day.parse(startDay);
            Date dt;

            for(int i=0;i<7;i++)
            {
                PgAlarmTjDto pgAlarmTjDto=new PgAlarmTjDto();
                Calendar calendar = new GregorianCalendar();
                calendar.setTime(dt1);
                calendar.add(calendar.DATE,i);
                dt=calendar.getTime();
                pgAlarmTjDto.setAlarmDate(DateUtils.sdf_day.format(dt));
                pgAlarmTjDto.setAlarmNum("0");
                pgAlarmTjDtoList.add(pgAlarmTjDto);
            }
        }
        catch(Exception ex){
            ex.printStackTrace();
        }
        return pgAlarmTjDtoList;
    }

}