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

import com.yihu.wlyy.entity.dict.Medicines;
import com.yihu.wlyy.entity.education.Sports;
import com.yihu.wlyy.entity.education.SportsType;
import com.yihu.wlyy.entity.patient.PatientHealthRecordDiet;
import com.yihu.wlyy.entity.patient.PatientHealthRecordMedication;
import com.yihu.wlyy.entity.patient.PatientHealthRecordSports;
import com.yihu.wlyy.repository.dict.MedicinesDao;
import com.yihu.wlyy.repository.education.SportsDao;
import com.yihu.wlyy.repository.education.SportsTypeDao;
import com.yihu.wlyy.repository.patient.PatientHealthRecordDietDao;
import com.yihu.wlyy.repository.patient.PatientHealthRecordMedicationDao;
import com.yihu.wlyy.repository.patient.PatientHealthRecordSportsDao;
import com.yihu.wlyy.service.BaseService;
import com.yihu.wlyy.util.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
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.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
@Transactional(rollbackFor = Exception.class)
public class PatientHealthRecordService extends BaseService {

	@Autowired
	private SportsTypeDao sportsTypeDao;

	@Autowired
	private SportsDao sportsDao;

	@Autowired
	private MedicinesDao medicinesDao;

	@Autowired
	private PatientHealthRecordMedicationDao patientHealthRecordMedicationDao;

	@Autowired
	private PatientHealthRecordDietDao patientHealthRecordDietDao;

	@Autowired
	private PatientHealthRecordSportsDao patientHealthRecordSportsDao;

	/**
	 * 更改保健记录（包括手动记录的修改和所有的删除）
	 *
	 * @param id
	 * @param type   饮食1，运动2，用药3
	 * @param value1 记录时间
	 * @param value2 饮食内容CONTETN  时长 用药
	 * @param value3 上传图片 强度
	 * @param value4 运动项目
	 */
	public void modifyHealthCare(long id, int type, String value1, String value2, String value3, String value4) throws Exception {
		//value类字段值均为空为删除
		if (StringUtils.isEmpty(value1) && StringUtils.isEmpty(value2) && StringUtils.isEmpty(value3) && StringUtils.isEmpty(value4)) {
			switch (type) {
				case 1:
					patientHealthRecordDietDao.deleteDiet(id);
					break;
				case 2:
					patientHealthRecordSportsDao.deleteSports(id);
					break;
				case 3:
					patientHealthRecordMedicationDao.deleteMedication(id);
					break;
			}
		} else {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date recordDate = sdf.parse(value1);
			switch (type) {
				case 1:
					patientHealthRecordDietDao.modifyDiet(id, recordDate, value2, value3);
					break;
				case 2:
					SportsType sportsType = sportsTypeDao.findByCode(value3);
					String typeName = sportsType.getName();
					Sports sport = sportsDao.findByCode(value4);
					String sportName = sport.getName();
					Double sportsTime = Double.parseDouble(value2);
					patientHealthRecordSportsDao.modifySports(id, recordDate, sportsTime, value3, typeName, value4, sportName);
					break;
				case 3:
					Medicines medicines = medicinesDao.findByCode(value2);
					String medicinesName = medicines.getName();
					patientHealthRecordMedicationDao.modifyMedication(id, recordDate, value2, medicinesName);
					break;
			}
		}

	}

	/**
	 * 添加运动记录
	 * @param record 运动记录对象
	 * @return
	 */
	public PatientHealthRecordSports addSports(PatientHealthRecordSports record, String sportsType, String sports) {
		record.setCode(getCode());
		record.setSportsType(sportsType);
		record.setSportsTypeName(sportsTypeDao.findByCode(sportsType).getName());
		record.setSports(sports);
		record.setSportsName(sportsDao.findByCode(sports).getName());
		return patientHealthRecordSportsDao.save(record);
	}

	/**
	 * 添加用药记录
	 * @param record 用药记录对象
	 * @return
	 */
	public PatientHealthRecordMedication addMedication(PatientHealthRecordMedication record) {
		record.setCode(getCode());
		return patientHealthRecordMedicationDao.save(record);
	}

	/**
	 * 添加饮食记录
	 * @param record 饮食记录对象
	 * @return
	 */
	public PatientHealthRecordDiet addDiet(PatientHealthRecordDiet record) {
		record.setCode(getCode());
		return	 patientHealthRecordDietDao.save(record);
	}

	/**
	 * 按分类查询患者运动记录
	 * @param patient 患者标识
	 * @param
	 * @param pageSize 分页大小
	 * @return
	 */
	public Page<PatientHealthRecordSports> findSportsByPatient(String patient, Date sortDate, int pageSize) {
		if (pageSize <= 0) {
			pageSize = 10;
		}
		// 排序
		Sort sort = new Sort(Direction.DESC, "sortDate");
		// 分页信息
		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(sortDate != null){
			filters.put("sortDate", new SearchFilter("sortDate", Operator.LT, sortDate));
		}
		// 未作废
		filters.put("del", new SearchFilter("del", Operator.EQ, "1"));
		Specification<PatientHealthRecordSports> spec = DynamicSpecifications.bySearchFilter(filters.values(), PatientHealthRecordSports.class);
		return patientHealthRecordSportsDao.findAll(spec, pageRequest);
	}

	/**
	 * 查询运动记录
	 *
	 * @param patient
	 * @param start
	 * @param end
	 * @param page
	 * @param pagesize
	 * @return
	 */
	public Page<PatientHealthRecordSports> findSportsByPatientPage(String patient,String start,String end,int page,int pagesize){
		if(page > 0) {
			page = page -1;
		}
		PageRequest pageRequest = new PageRequest(page,pagesize);

		return patientHealthRecordSportsDao.findSportsByPatient(patient, DateUtil.strToDate(start,DateUtil.YYYY_MM_DD_HH_MM_SS)
				,DateUtil.strToDate(end,DateUtil.YYYY_MM_DD_HH_MM_SS),pageRequest);
	}

	/**
	 * 查询用药记录
	 *
	 * @param patient
	 * @param start
	 * @param end
	 * @param page
	 * @param pagesize
	 * @return
	 */
	public Page<PatientHealthRecordMedication> findMedicalByPatientPage(String patient,String start,String end,int page,int pagesize){
		if(page > 0)
		{
			page = page -1;
		}
		PageRequest pageRequest = new PageRequest(page,pagesize);
		return patientHealthRecordMedicationDao.findMedicalByPatient(patient, DateUtil.strToDate(start,DateUtil.YYYY_MM_DD_HH_MM_SS)
				,DateUtil.strToDate(end,DateUtil.YYYY_MM_DD_HH_MM_SS),pageRequest);
	}

	/**
	 * 查询饮食记录
	 *
	 * @param patient
	 * @param start
	 * @param end
	 * @param page
	 * @param pagesize
	 * @return
	 */
	public Page<PatientHealthRecordDiet> findDietByPatientPage(String patient,String start,String end,int page,int pagesize){
		if(page > 0) {
			page = page -1;
		}
		PageRequest pageRequest = new PageRequest(page,pagesize);
		return patientHealthRecordDietDao.findDietByPatient(patient, DateUtil.strToDate(start,DateUtil.YYYY_MM_DD_HH_MM_SS)
				,DateUtil.strToDate(end,DateUtil.YYYY_MM_DD_HH_MM_SS),pageRequest);
	}

	/**
	 * 按分类查询患者用药记录
	 * @param patient 患者标识
	 * @param pageSize 分页大小
	 * @return
	 */
	public Page<PatientHealthRecordMedication> findMedicationByPatient(String patient, Date sortDate,Integer page, int pageSize) {
		if(page==null){
			page = 0;
		}else if(page > 0)
		{
			page = page -1;
		}

		if (pageSize <= 0) {
			pageSize = 10;
		}
		// 排序
		Sort sort = new Sort(Direction.DESC, "sortDate");
		// 分页信息
		PageRequest pageRequest = new PageRequest(page, pageSize, sort);

		// 设置查询条件
		Map<String, SearchFilter> filters = new HashMap<String, SearchFilter>();
		// 患者标志
		filters.put("patient", new SearchFilter("patient", Operator.EQ, patient));
		if(sortDate != null){
			filters.put("sortDate", new SearchFilter("sortDate", Operator.LT, sortDate));
		}
		// 未作废
		filters.put("del", new SearchFilter("del", Operator.EQ, "1"));
		Specification<PatientHealthRecordMedication> spec = DynamicSpecifications.bySearchFilter(filters.values(), PatientHealthRecordMedication.class);
		return patientHealthRecordMedicationDao.findAll(spec, pageRequest);
	}



	/**
	 * 按分类查询患者饮食记录
	 * @param patient 患者标识
	 * @param
	 * @param pageSize 分页大小
	 * @return
	 */
	public Page<PatientHealthRecordDiet> findDietByPatient(String patient, Date sortDate, int pageSize) {
		if (pageSize <= 0) {
			pageSize = 10;
		}
		// 排序
		Sort sort = new Sort(Direction.DESC, "sortDate");
		// 分页信息
		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(sortDate != null){
			filters.put("sortDate", new SearchFilter("sortDate", Operator.LT, sortDate));
		}
		// 未作废
		filters.put("del", new SearchFilter("del", Operator.EQ, "1"));
		Specification<PatientHealthRecordDiet> spec = DynamicSpecifications.bySearchFilter(filters.values(), PatientHealthRecordDiet.class);
		return patientHealthRecordDietDao.findAll(spec, pageRequest);
	}

	/**
	 * 查询患者最近填写的运动、用药、饮食内容
	 * @param patient
	 * @return
	 */
	public JSONObject findRecentByPatient(String patient) {
		JSONObject jsonObject = new JSONObject();
		// 查询最近的运动
		Page<PatientHealthRecordSports> sports = patientHealthRecordSportsDao.findRecentByPatient(patient, new PageRequest(0, 1));
		// 查询最近的用药
		Page<PatientHealthRecordMedication> medication = patientHealthRecordMedicationDao.findRecentByPatient(patient, new PageRequest(0, 1));
		// 查询最近的饮食
		Page<PatientHealthRecordDiet> diet = patientHealthRecordDietDao.findRecentByPatient(patient, new PageRequest(0, 1));
		if (sports != null && sports.getSize() > 0) {
			JSONObject sportObject = new JSONObject();
			for (PatientHealthRecordSports temp : sports) {
				sportObject.put("sports", temp.getSportsName());
				sportObject.put("sports_time", temp.getSportsTime());
				sportObject.put("sports_type", temp.getSportsType());
				sportObject.put("sports_typeName", temp.getSportsTypeName());
				sportObject.put("czrq", DateUtil.dateToStr(temp.getCzrq(), DateUtil.YYYY_MM_DD));
				sportObject.put("recordDate", DateUtil.dateToStr(temp.getRecordDate(), DateUtil.YYYY_MM_DD));
				sportObject.put("source","1".equals(temp.getSource())?1:0);
			}
			jsonObject.put("sprot",sportObject);
		}
		if (medication != null) {
			JSONObject medicationObject = new JSONObject();
			for (PatientHealthRecordMedication temp : medication) {
				medicationObject.put("medication", temp.getMedicinesName());
				medicationObject.put("recordDate",DateUtil.dateToStr(temp.getRecordDate(), DateUtil.YYYY_MM_DD));
				medicationObject.put("source","1".equals(temp.getSource())?1:0);

			}
			jsonObject.put("medication",medicationObject);

		}
		if (diet != null) {
			JSONObject dietObject = new JSONObject();
			for (PatientHealthRecordDiet temp : diet) {
				dietObject.put("diet", temp.getContent());
				dietObject.put("recordDate",DateUtil.dateToStr(temp.getRecordDate(), DateUtil.YYYY_MM_DD));
				dietObject.put("images",temp.getImages());
				dietObject.put("source","1".equals(temp.getSource())?1:0);

			}
			jsonObject.put("diet",dietObject);

		}
		return jsonObject;
	}

}
