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

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.transaction.Transactional;

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.springside.modules.persistence.DynamicSpecifications;
import org.springside.modules.persistence.SearchFilter;
import org.springside.modules.persistence.SearchFilter.Operator;

import com.yihu.wlyy.entity.follow.FollowUpPlanRemind;
import com.yihu.wlyy.repository.followup.FollowUpPlanRemindDao;
import com.yihu.wlyy.service.BaseService;

/**
 * 随访提醒业务处理类型
 * @author George
 *
 */
@Component
@Transactional(rollbackOn = Exception.class)
public class FollowUpPlanRemindService extends BaseService {

	@Autowired
	private FollowUpPlanRemindDao followUpPlanRemindDao;

	/**
	 * 添加随访提醒
	 * @param patient 患者标识
	 * @param doctor 医生标识
	 * @param doctorName 医生姓名
	 * @param plan 随访计划标识
	 * @param content 提醒内容
	 * @return
	 */
	public FollowUpPlanRemind add(String patient, String doctor, String doctorName, String plan, String content) {
		FollowUpPlanRemind remind = new FollowUpPlanRemind();
		remind.setContent(content);
		remind.setCzrq(new Date());
		remind.setDoctor(doctor);
		remind.setDoctorName(doctorName);
		remind.setPatient(patient);
		remind.setPlan(plan);
		remind.setRead(1);
		return followUpPlanRemindDao.save(remind);
	}

	/**
	 * 更新为已读
	 * @param id
	 * @return
	 */
	public int read(long id) {
		return followUpPlanRemindDao.updateRead(id);
	}

	/**
	 * 根据id查询随访提醒
	 * @param id
	 * @return
	 */
	public FollowUpPlanRemind findById(long id) {
		FollowUpPlanRemind remind = followUpPlanRemindDao.findOne(id);
		// 更新为已读
		if (remind.getRead() == 1) {
			remind.setRead(0);
			followUpPlanRemindDao.save(remind);
		}
		return remind;
	}

	/**
	 * 查询患者的随访提醒列表
	 * @param patient
	 * @param id
	 * @param pagesize
	 * @return
	 */
	public Page<FollowUpPlanRemind> 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<FollowUpPlanRemind> spec = DynamicSpecifications.bySearchFilter(filters.values(), FollowUpPlanRemind.class);
		return followUpPlanRemindDao.findAll(spec, pageRequest);
	}

}
