package com.wisedu.mooc.app.study.dao;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;

import com.wisedu.coeus.core.dao.BaseDao;
import com.wisedu.coeus.util.Strings;
import com.wisedu.mooc.app.study.bo.UserStudy;


@Repository("userStudyDao")
public class UserStudyDao extends BaseDao {

	public UserStudy queryUserStudy(Long id) {
		return this.load(UserStudy.class, id);
	}
	
	private static final String SQL_QUERY_USERSTUDY_RECORD=" select a.* from mooc_user_study a "
        + " join mooc_unit_item b on a.item_id = b.item_id and b.delete_flag =0"
        + " where a.user_id=:userId";

	
	/**
	 * 用户学习记录
	 * @param courseOpenId
	 * @param userId
	 * @return
	 */
	public List<UserStudy> queryUserStudyRecord(Long userId,Integer isOver) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("userId", userId);
        String sql = SQL_QUERY_USERSTUDY_RECORD;
        if (Strings.isNotEmpty(isOver)){
            sql = sql +" and a.is_over=:isOver";
            params.put("isOver", isOver);
        }
		return this.queryForBeanList(UserStudy.class, sql, params, 0, 0);
		
	}

	public List<UserStudy> queryUserStudy(Long unitId, Integer isOver, Long userId){
		String sql = "select a.* from mooc_user_study a " +
				"join mooc_unit_item b on a.item_id=b.item_id " +
				"join mooc_unit c on b.unit_id=c.unit_id " +
				"where b.delete_flag=0 ";
		if (unitId != null){
			sql += " and c.unit_id=:unitId ";
		}
		if (isOver != null){
			sql += " and a.is_over=:isOver ";
		}
		if (userId != null){
			sql += " and a.user_id=:userId ";
		}
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("unitId", unitId);
		params.put("isOver", isOver);
		params.put("userId", userId);
		return this.queryForBeanList(UserStudy.class, sql, params, 0, 0);
	}
	
	private static final String QUERY_USER_STUDY_BY_ITEMID = "select * from mooc_user_study "
			+ "where item_id=:itemId and user_id=:userId";

	/**
	 * 获取用户某一条目的学习记录
	 * 
	 * @param itemId
	 * @param userId
	 * @return
	 */
	public UserStudy queryUserStudy(Long itemId, Long userId) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("itemId", itemId);
		params.put("userId", userId);
		List<UserStudy> list = this.queryForBeanList(UserStudy.class, QUERY_USER_STUDY_BY_ITEMID,
				params, 0, 0);
		if (CollectionUtils.isEmpty(list)) {
			return null;
		}
		return list.get(0);
	}
}
