package com.ssj.dao.course.dao;

import java.util.List;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import com.ssj.bean.course.domain.CourseSeries;


@Repository
public interface ICSDao extends JpaRepository<CourseSeries, String> {

	Page<CourseSeries> findAll(Specification<CourseSeries> specification, Pageable initPage);

	@Query(nativeQuery = true, value = "SELECT\n" +
			"	s.*\n" +
			"FROM\n" +
			"  tb_course_series s join \n" +
			"	tb_course_series_order t\n" +
			"  on  s.id = t.course_series_id\n" +
			"WHERE\n" +
			"	t.stat = 1 and s.state =1 \n" +
			"AND t.lib_id =?1\n" +
			"AND TO_DAYS(t.end_time) >= TO_DAYS(now())\n" +
			"ORDER BY\n" +
			"	t.create_time DESC")
	List<CourseSeries> findByBuy(String libId);
	
	@Query(nativeQuery = true, value ="SELECT   DATE_FORMAT(MAX(last_update_time),'%m月%d日')  from  tb_course_series \n" +
			"where INSTR (course_hot_lable,?1) and state =1 ")
	public String getLatestTime(int type);
	
	@Query(nativeQuery = true, value ="SELECT  	ROUND(avg(score), 1)  from  tb_course_series  \n" +
			"where INSTR (course_hot_lable,?1) and state =1 ")
	public Double getAvg(int type);
	@Query(nativeQuery = true, value ="SELECT  count(1) from  ( \n" +
			"SELECT count(n.course_series_id) from  tb_course_series_join n LEFT JOIN  tb_course_series s \n" +
			"on n.course_series_id = s.id \n" +
			"WHERE INSTR (s.course_hot_lable,?1)  and s.state =1  \n" +
			"GROUP BY n.course_series_id,n.vip_id \n" +
			") t")
	public Long getCountVip(int type);
	@Query(nativeQuery = true, value ="SELECT  count(1)  from  tb_course_series \n" +
			"where INSTR (course_hot_lable,?1)  and state =1 ")
	public Long getfinAll(int type);
	@Query(nativeQuery = true, value ="SELECT  \n" +
			"cast(sum(\n" +
			"CASE type \n" +
			"WHEN 0 THEN  1\n" +
			"ELSE 0 END\n" +
			") /count(1)*100 as decimal(9,2))\n" +
			" from  (\n" +
			"SELECT  \n" +
			"if((j.duration - s.course_duration) >=0,1,0) as type \n" +
			"from  tb_course_series_join j join  tb_course_series_details s \n" +
			"on j.course_details_id =s .id \n" +
			"where j.lib_id =?1  and s.state =1 \n" +
			"and   j.course_series_id =?2 \n" +
			") a")
	public String getDurationByLibIdAndCourseSeriesId(String libId,String courseSeriesId);
}
