package com.casic.PgInterface.overtimeInPG.manager;

import com.casic.PgInterface.core.hibernate.HibernateEntityDao;
import com.casic.PgInterface.maintenance.dto.PgAssetPlanStatic;
import com.casic.PgInterface.overtimeInPG.domain.PGTagPosition;
import com.casic.PgInterface.overtimeInPG.domain.PGTagPositionView;
import com.casic.PgInterface.overtimeInPG.dto.PGPositionDto;
import com.casic.PgInterface.overtimeInPG.dto.PGPositionSimpleDto;
import com.casic.PgInterface.overtimeInPG.dto.PGTagPositionDto;
import com.casic.PgInterface.overtimeInPG.task.TagmacRun;
import com.sun.org.apache.xpath.internal.operations.Or;
import org.hibernate.Criteria;
import org.hibernate.SQLQuery;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.hibernate.procedure.ProcedureCall;
import org.hibernate.transform.Transformers;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.ParameterMode;
import javax.persistence.criteria.CriteriaBuilder;
import java.math.BigDecimal;
import java.util.*;

@Service
public class PGTagPositionManager extends HibernateEntityDao<PGTagPosition>{

    @Resource
    private TagmacRun tagmacRun;

    public boolean findTagPosition(String dateStr,String hostId)
    {
        Criteria criteria = createCriteria(PGTagPosition.class);
        criteria.add(Restrictions.and(Restrictions.eq("hostId",hostId),Restrictions.eq("positionUpdatetime",dateStr)));
        criteria.add(Restrictions.sqlRestriction(" queryTime between sysdate-10 and sysdate"));
        return  criteria.setMaxResults(1).list().size()>0;
    }

    public Map<String,Object> getAllPosition()
    {
        Map<String,Object> retMap = new HashMap<>();
        List<PGPositionDto> pgPositionDtoList ;
        String querySql = " select * from tagPositionView ";
        SQLQuery sqlQuery = (SQLQuery) this.getSession().createSQLQuery(querySql).setResultTransformer(Transformers.aliasToBean(PGPositionDto.class));
        pgPositionDtoList = sqlQuery.list();
        retMap.put("message","success");
        retMap.put("result",pgPositionDtoList);
        return retMap;
    }

    public long getMaxId(String tagMac)
    {
        String hSql = "select max(id) from pg_tagposition where tagmac = '"+tagMac+"'";
        return ((BigDecimal)this.getSession().createSQLQuery(hSql).uniqueResult()).longValue();
    }
//
//    public Map<Object,Object> getHisByHostId(Date inTime, Date outTime, String hostId) {
//        Map<Object,Object> retMap = new HashMap<>();
//        List<PGPositionSimpleDto> pgPositionSimpleDtoList ;
//
//        Criteria criteria = createCriteria(PGTagPosition.class);
//        criteria.add(Restrictions.between("parsedtime",inTime,outTime));
//        criteria.add(Restrictions.eq("hostid",hostId));
//        criteria.addOrder(Order.asc("id"));
//        pgPositionSimpleDtoList = criteria.list();
//        retMap.put("XY",pgPositionSimpleDtoList);
//        return  retMap;
//    }


    public Map<Object,Object> getHisByHostId(Date inTime, Date outTime, String hostId)
    {
        Map<Object,Object> retMap = new HashMap<>();
        List<Object> pgPositionSimpleDtoList ;
//        List<PGPositionSimpleDto> pgPositionSimpleDtoList ;
        String querySql = " select id,binName,partition,positionUpdateTime from pg_position_tag_dev " +
//                "where hostid = 1 " +
                "where parsedtime between ? and ? and hostid = ? " +
                " order by id asc";
//        SQLQuery sqlQuery = (SQLQuery) this.getSession().createSQLQuery(querySql);

        SQLQuery sqlQuery = (SQLQuery) this.getSession().createSQLQuery(querySql).addScalar("id")
                .addScalar("binName").addScalar("positionUpdateTime").addScalar("partition")
                .setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
//        SQLQuery sqlQuery = (SQLQuery) this.getSession().createSQLQuery(querySql).addScalar("id").setResultTransformer(Transformers.aliasToBean(PGPositionSimpleDto.class));
//        SQLQuery sqlQuery = (SQLQuery) this.getSession().createSQLQuery(querySql).setResultTransformer(Transformers.aliasToBean(PGPositionSimpleDto.class));
        sqlQuery.setParameter(0,inTime);
        sqlQuery.setParameter(1,outTime);
        sqlQuery.setParameter(2,hostId);
        pgPositionSimpleDtoList = sqlQuery.list();
        System.out.println("XY:"+ pgPositionSimpleDtoList.toString());
        retMap.put("XY",pgPositionSimpleDtoList);
        return retMap;
    }


    public Map<Object,Object> getHisByHostIdView(Date inTime, Date outTime, String hostId)
    {
        Map<Object,Object> retMap = new HashMap<>();
        List<PGTagPositionView> pgTagPositionViewList ;
        Criteria criteria = createCriteria(PGTagPositionView.class);
        criteria.add(Restrictions.between("parsedTime",inTime,outTime));
        criteria.add(Restrictions.eq("hostId",hostId));
        criteria.addOrder(Order.asc("id"));
        pgTagPositionViewList =  criteria.list();
//        System.out.println("XY:"+ pgPositionSimpleDtoList.toString());
        retMap.put("XY",PGPositionSimpleDto.Conver2SimpleList(pgTagPositionViewList));
//        retMap.put("XY",criteria.list());
        return retMap;
    }

    public boolean getPersonInPgByAcu(String acu) {

        boolean result = false;

        try {
            //读取定位信息
            tagmacRun.getMacPosition();

            String sql = "select count(*) from PG_POSITION_TAG_DEV t where partition = '"
                    + acu +
                    "' and parsedtime > sysdate-1/(24*60)";

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

            Object object = this.getSession().createSQLQuery(sql).uniqueResult();

            result = Integer.parseInt(String.valueOf(object)) > 0 ? true : false;

        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return result;
    }

    public List<Map<String, Object>> getPersonInPgByAcuList(String acuList) {
        List<Map<String, Object>> result = new ArrayList<>();
        try {
            //读取定位信息
            tagmacRun.getMacPosition();

            String[] acus = acuList.split(",");
            acuList = "";
            for ( int i = 0; i < acus.length; i++) {
                acuList += "'" + acus[i] + "'" + ",";
            }
            acuList = acuList.substring(0, acuList.length() - 1);

            String sql = "select partition, count(*) from PG_POSITION_TAG_DEV t where partition in ("
                    + acuList +
                    ") and parsedtime > sysdate-3 * 365 group by partition";

            List<Object[]> objects = this.getSession().createSQLQuery(sql).list();
            if (objects.isEmpty() == false) {
                for (Object[] item: objects ) {
                    Map<String, Object> obj = new HashMap<>();
                    obj.put("acu", item[0]);
                    obj.put("person", ((Number) item[1]).intValue() > 0 ? true : false);

                    result.add(obj);
                }
            }

            return  result;

        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return null;
    }

}