package com.ssj.dao.weixin.library.dao.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Repository;

import com.ssj.dao.weixin.library.dao.LibVipDao;
import com.ssj.framework.core.persistence.PagingHibernateJdbcDao;

@Repository
public class LibVipDaoImpl implements LibVipDao {
    @Autowired
    private PagingHibernateJdbcDao dao;

    @Override
    public Page<Map<String, Object>> findDistinctVipByTeacherId(Map<String, Object> searchParams, Pageable pageable) {
        StringBuilder sb = new StringBuilder();
        List<Object> queryParams = new ArrayList<Object>();

        sb.append("select distinct t.* from tb_lib_vip t left join scon_problem_picture t1 on t.derver = t1.derver")
                .append(" where teacher_id = ? and t.derver is not null and t.derver !='' order by create_time desc");
        queryParams.add(searchParams.get("teacherId"));
        return dao.findPage(sb.toString(), queryParams.toArray(), pageable);
    }

    @Override
    public Page<Map<String, Object>> findVipByOrgTeacherId(Map<String, Object> searchParams, Pageable pageable) {
        StringBuilder sb = new StringBuilder();
        List<Object> queryParams = new ArrayList<>();
        sb.append("select distinct t.* from tb_lib_vip t " +
                " left join tb_lib_vip_bind t1 on t1.vip_id = t.id " +
                " where (subject is not null or subject != '')" +
                " and t1.teacher_id = ? " +
                " order by t1.create_time desc");
        queryParams.add(searchParams.get("teacherId"));
        return dao.findPage(sb.toString(), queryParams.toArray(), pageable);
    }
    
	@Override
	public List<Map<String, Object>> findVipByLibIdMaxActivateTime(String libId,Date activateTime,String species) {
		StringBuffer selSql = new StringBuffer();
		List<Object> queryParams = new ArrayList<Object>();
		selSql.append(" select v.*,t.end_time from tb_lib_vip v  " );
		selSql.append("	LEFT JOIN ( ");
		selSql.append(" 	SELECT s.vip_id,MAX(s.end_time) as end_time from tb_lib_vip_service s where s.species=? GROUP BY s.vip_id " );
		selSql.append(" )as t ON t.vip_id=v.id " );
		selSql.append(" where v.activate_time is NOT NULL AND v.lib_id=? AND TO_DAYS(v.activate_time)>=TO_DAYS(?) AND TO_DAYS(t.end_time)<TO_DAYS(NOW()) ORDER BY t.end_time asc " );
		queryParams.add(species);
		queryParams.add(libId);
		queryParams.add(activateTime);
		
		return dao.findMap(selSql.toString(), queryParams.toArray());
	}
    
    

}
