package com.yihu.wlyy.service.app.health;

import com.yihu.wlyy.entity.education.HealthEduArticle;
import com.yihu.wlyy.entity.education.HealthEduArticlePatient;
import com.yihu.wlyy.repository.education.HealthEduArticleDao;
import com.yihu.wlyy.repository.education.HealthEduArticlePatientDao;
import com.yihu.wlyy.service.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.persistence.DynamicSpecifications;
import org.springside.modules.persistence.SearchFilter;
import org.springside.modules.persistence.SearchFilter.Operator;

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

/**
 * 健康教育患者业务逻辑类
 * @author linz
 *
 */
@Component
@Transactional(rollbackFor = Exception.class)
public class HealthEduArticlePatientService extends BaseService {

	@Autowired
	private HealthEduArticlePatientDao healthEduArticlePatientDao;

	/**
	 * 根据文章标示获取数据
	 * @param article
	 * @return
	 *
	 */
	@Deprecated
	public HealthEduArticlePatient findByArticle(String article) {
		return healthEduArticlePatientDao.findByArticle(article);
	}

	/**
	 * 根据文章id获取数据
	 * @param id
	 * @return
	 */
	public HealthEduArticlePatient findById(Long id) {
		return healthEduArticlePatientDao.findOne(id);
	}

	public List<HealthEduArticlePatient> findByArticleAndPatient(String article,String patient) {
		return healthEduArticlePatientDao.findByArticleAndPatient(article, patient);
	}

	/**
	 * 查询患者文章
	 * @param patient 患者标识
	 * @param pagesize 分页大小
	 * @return
	 */
	public Page<HealthEduArticlePatient> findByPatient(String patient, long id, int pagesize) {
		if (pagesize <= 0) {
			pagesize = 10;
		}
		// 排序
		Sort sort = new Sort(Direction.DESC, "id");
		// 分页信息
		PageRequest pageRequest = new PageRequest(0, pagesize, sort);
		// 设置查询条件
		Map<String, SearchFilter> filters = new HashMap<String, SearchFilter>();
		// 患者过滤
		filters.put("patient", new SearchFilter("patient", Operator.EQ, patient));
		if (id > 0) {
			filters.put("id", new SearchFilter("id", Operator.LT, id));
		}
		Specification<HealthEduArticlePatient> spec = DynamicSpecifications.bySearchFilter(filters.values(), HealthEduArticlePatient.class);
		return healthEduArticlePatientDao.findAll(spec, pageRequest);
	}

	/**
	 * 文章更新为已读
	 * @param patient
	 * @param article
	 * @return
	 */
	public int updateRead(String patient, String article) {
		return healthEduArticlePatientDao.updateRead(patient, article);
	}

}
