package com.casic.PgInterface.devTable.manager;

import com.casic.PgInterface.core.hibernate.HibernateEntityDao;
import com.casic.PgInterface.devTable.domain.PgPartition;
import com.casic.PgInterface.devTable.domain.PipeGallery;
import com.casic.PgInterface.devTable.dto.PipeGalleryDto;
import com.casic.PgInterface.devTable.dto.PipeGalleryStatic;
import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by yxw on 2017/11/4.
 */
@Service
public class PipeGalleryManager extends HibernateEntityDao<PipeGallery> {

    private PgPartitionManager pgPartitionManager;

    @Resource
    public void setPgPartitionManager(PgPartitionManager pgPartitionManager) {
        this.pgPartitionManager = pgPartitionManager;
    }

    public PipeGallery getPipeGalleryByPgName(String pgName,PgPartition pgPartition) {
        if(pgPartition==null)
            return null;
        Criteria criteria = getSession().createCriteria(PipeGallery.class);
        criteria.add(Restrictions.eq("pgName", pgName));
        criteria.add(Restrictions.eq("pgPartitionId",pgPartition));

        List<PipeGallery> pipeGalleryList = criteria.list();

        //TODO LIST:为空判断 pgPartitionList==null?
        if (pipeGalleryList != null && pipeGalleryList.size() > 0)
            return pipeGalleryList.get(0);
        else
            return null;
    }


    public List<PipeGalleryDto> getPipeGalleryByParName(String parName) {

        PgPartition pgPartition = pgPartitionManager.getPartitionByParName(parName);
        Criteria criteria = getSession().createCriteria(PipeGallery.class);
        criteria.add(Restrictions.eq("pgPartitionId", pgPartition));

        List<PipeGallery> pipeGalleryList = criteria.list();

        List<PipeGalleryDto> pipeGalleryDtoList = new ArrayList<PipeGalleryDto>();
        for (PipeGallery pipeGallery : pipeGalleryList) {
            pipeGalleryDtoList.add(new PipeGalleryDto(pipeGallery));
        }

        return pipeGalleryDtoList;
    }

    public List<PipeGalleryStatic> getPgLengthByName() {

        String sql = "select PG_NAME,SUM(PAR_LENGTH) from PG_PIPE_GALLERY group by PG_NAME ";

        List<Object[]> objectList = this.getSession().createSQLQuery(sql).list();
        List<PipeGalleryStatic> pipeGalleryStaticList = new ArrayList<PipeGalleryStatic>();

        for(Object[] objectArray : objectList)
        {
            PipeGalleryStatic pipeGalleryStatic=new PipeGalleryStatic();
            pipeGalleryStatic.setPgName(String.valueOf(objectArray[0]));
            pipeGalleryStatic.setLength(String.valueOf(objectArray[1]));
            pipeGalleryStaticList.add(pipeGalleryStatic);
        }
        return pipeGalleryStaticList;
    }


}
