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

import com.yihu.wlyy.entity.doctor.profile.Doctor;
import com.yihu.wlyy.entity.patient.Patient;
import com.yihu.wlyy.entity.patient.PatientHealthGuidance;
import com.yihu.wlyy.entity.patient.SignFamily;
import com.yihu.wlyy.repository.doctor.DoctorDao;
import com.yihu.wlyy.repository.patient.PatientDao;
import com.yihu.wlyy.repository.patient.PatientHealthGuidanceDao;
import com.yihu.wlyy.repository.patient.SignFamilyDao;
import com.yihu.wlyy.service.BaseService;
import com.yihu.wlyy.service.common.account.PatientService;
import com.yihu.wlyy.task.PushMsgTask;
import com.yihu.wlyy.util.DateUtil;
import com.yihu.wlyy.wechat.util.WeiXinAccessTokenUtils;
import com.yihu.wlyy.wechat.util.WeiXinOpenIdUtils;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
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.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * 健康指导业务处理类
 * @author George
 *
 */
@Component
@Transactional(rollbackFor = Exception.class)
public class PatientHealthGuidanceService extends BaseService {

	@Autowired
	private DoctorDao doctorDao;
	@Autowired
	private PatientDao patientDao;
	@Autowired
	private PatientHealthGuidanceDao patientHealthGuidanceDao;
	@Autowired
	SignFamilyDao signFamilyDao;
	@Autowired
	JdbcTemplate jdbcTemplate;
	@Autowired
	WeiXinOpenIdUtils weiXinOpenIdUtils;
	@Autowired
	private PatientService patientService;
	@Autowired
	private WeiXinAccessTokenUtils weiXinAccessTokenUtils;

	public JSONObject findById(Long id){
		PatientHealthGuidance guidance = patientHealthGuidanceDao.findOne(id);

		if(guidance != null){
			JSONObject obj = new JSONObject(guidance);
			Doctor doc = doctorDao.findByCode(guidance.getDoctor());
			Patient p = patientDao.findByCode(guidance.getPatient());

			obj.put("doctorName",doc.getName());
			obj.put("photo",doc.getPhoto());
			obj.put("name",doc.getName());
			obj.put("level",doc.getLevel());
			obj.put("patientName",p.getName());
			obj.put("czrq",guidance.getCzrq()!= null ? DateUtil.dateToStr(guidance.getCzrq(),DateUtil.YYYY_MM_DD_HH_MM) :"");
			return obj;
		}else{
			return null;
		}
	}

	/**
	 * 更改健康指导阅读状态
	 * @param id
	 * @return
	 */
	public void modifyStatus(String id,String type) {
		if("1".equals(type)){
//            一键设置居民未读指导
			String sql = "UPDATE wlyy_patient_health_guidance wphg " +
					"SET wphg .read_status = 1  "+
					"WHERE wphg.patient = ?";
			jdbcTemplate.update(sql,id);
		}else {
			String sql = "UPDATE wlyy_patient_health_guidance wphg " +
					"SET wphg .read_status = 1  " +
					"WHERE wphg.id = ?";
			jdbcTemplate.update(sql, id);
		}
	}

	/**
	 * 保存健康指导
	 * @param guidance
	 * @return
	 */
	public PatientHealthGuidance add(PatientHealthGuidance guidance, String accessToken) throws Exception {
		Doctor doctor = doctorDao.findByCode(guidance.getDoctor());
		Patient patient = patientDao.findByCode(guidance.getPatient());
		//家庭医生
		SignFamily signFamily = signFamilyDao.findByjiatingPatient(guidance.getPatient());
		//家庭医生不存在
		if(signFamily == null){
			 signFamily = signFamilyDao.findBySanshiPatient(guidance.getPatient());
			 if(signFamily==null){
			 	throw new RuntimeException("患者未签约！");
			 }
		}


		guidance.setCzrq(new Date());
		guidance.setCreateTime(new Date());
		guidance.setDel("1");
		guidance.setAdminTeamCode(signFamily.getAdminTeamId());
		guidance.setSignType(2);
		//保存签约CODE
		guidance.setSignCode(patientService.getSignCodeByPatient(patient.getCode()));
		guidance = patientHealthGuidanceDao.save(guidance);

		String openId = null;
//		String name = null;
		JSONObject json = new JSONObject();

		//判定openId是否为空空,如果为空,查找他家人的openId
		if(StringUtils.isNotBlank(patient.getOpenid())){
			json.put("first", "健康指导提醒");
			//name = patient.getName();
			openId = patient.getOpenid();
		}
//		else{
//			JSONObject j = weiXinOpenIdUtils.getFamilyOpenId(patient.getCode());
//			Patient member = (Patient)j.get("member");
//			openId = member.getOpenid();
//			//name = member.getName();
//			if (StringUtils.isNotEmpty(openId)) {
//				json.put("first", weiXinOpenIdUtils.getTitleMes(patient, j.getInt("relation"), patient.getName()) + "健康指导提醒");
//			}
//		}
		if (guidance != null ) {
			json.put("toUser", patient.getCode());
			json.put("represented",patient.getCode());//被代理人
			json.put("id", guidance.getId());
			json.put("date", DateUtil.getStringDate());
			json.put("orgName", doctor.getHospitalName());
			json.put("doctorName", doctor.getName());
			json.put("content", "您好！医生给您发来了一份新的健康指导。");
			json.put("remark", "请点击查看");
			if(StringUtils.isNotEmpty(openId)){
				// 推送消息到微信端
				PushMsgTask.getInstance().putWxMsg(accessToken, 4, openId, patient.getName(), json);
			}
			//发送代理人
			JSONArray jsonArray = weiXinOpenIdUtils.getAgentOpenId(patient.getCode(),patient.getOpenid());
			if(jsonArray!=null&&jsonArray.length()>0){
				for (int i = 0;i<jsonArray.length();i++){
					JSONObject j  = jsonArray.getJSONObject(i);
					Patient member = (Patient) j.get("member");
					JSONObject data = json;
					data.remove("toUser");
					data.put("toUser",member.getCode());
					//String first = (String) json.get("first");
					data.remove("first");
					data.put("first", weiXinOpenIdUtils.getTitleMes(patient, j.getInt("relation"), patient.getName()) + "健康指导提醒");
					PushMsgTask.getInstance().putWxMsg(weiXinAccessTokenUtils.getAccessToken(), 4, member.getOpenid(), patient.getName(), data);
				}
			}

		}
		return guidance;
	}

	/**
	 * 查询医生为患者添加的健康指导
	 * @param doctor 医生标识
	 * @param patient 患者标识
	 * @param id
	 * @param pagesize 分页大小
	 * @return
	 */
	public JSONArray findPatientGuidanceByDoctor(String doctor, String patient, String beginStr, String endStr, long id, int pagesize) {
		Date begin = DateUtil.strToDateLong(beginStr);
		Date end = DateUtil.strToDateLong(endStr);
		JSONArray array = new JSONArray();
		Page<Object> page = null;
		PageRequest pageRequest = new PageRequest(0, pagesize);
		if (id > 0) {
			if (StringUtils.isNotEmpty(patient)) {
				if (begin != null && end != null) {
					page = patientHealthGuidanceDao.findByDoctor(doctor, patient, begin, end, id, pageRequest);
				} else {
					page = patientHealthGuidanceDao.findByDoctor(doctor, patient, id, pageRequest);
				}
			} else {
				if (begin != null && end != null) {
					page = patientHealthGuidanceDao.findByDoctor(doctor, begin, end, id, pageRequest);
				} else {
					page = patientHealthGuidanceDao.findByDoctor(doctor, id, pageRequest);
				}
			}
		} else {
			if (StringUtils.isNotEmpty(patient)) {
				if (begin != null && end != null) {
					page = patientHealthGuidanceDao.findByDoctor(doctor, patient, begin, end, pageRequest);
				} else {
					page = patientHealthGuidanceDao.findByDoctor(doctor, patient, pageRequest);
				}
			} else {
				if (begin != null && end != null) {
					page = patientHealthGuidanceDao.findByDoctor(doctor, begin, end, pageRequest);
				} else {
					page = patientHealthGuidanceDao.findByDoctor(doctor, pageRequest);
				}
			}
		}
		if (page != null) {
			for (Object obj : page) {
				Object[] temp = (Object[]) obj;
				if (temp == null || temp.length != 5) {
					continue;
				}
				JSONObject json = new JSONObject();
				json.put("name", temp[0]);
				json.put("photo", temp[1]);
				json.put("id", temp[2]);
				json.put("content", temp[3]);
				json.put("czrq", DateUtil.dateToStrLong((Date) temp[4]));
				array.put(json);
			}
		}
		return array;
	}

	/**
	 * 健康指导查询
	 *
	 * @param patient
	 * @param teamCode
	 * @param page
	 * @param pageSize
	 * @return
	 */
	public JSONArray findByPatientAndGuidanceAndTeam(String patient,long teamCode,int page,int pageSize){
		Sort sort = new Sort(Sort.Direction.DESC,"createTime");
		PageRequest pageRequest = new PageRequest(0, pageSize, sort);
		Page<Object> result = patientHealthGuidanceDao.findByPatientAndTeamCode(patient,teamCode,pageRequest);
		JSONArray array = new JSONArray();
		if (result != null) {
			for (Object obj : result) {
				Object[] temp = (Object[]) obj;
				JSONObject json = new JSONObject();
				json.put("doctorCode", temp[6]);
				json.put("doctorName", temp[0]);
				json.put("doctorPhoto", temp[1]);
				json.put("id", temp[2]);
				json.put("content", temp[3]);
				json.put("createTime", DateUtil.dateToStrLong((Date) temp[4]));
				json.put("adminTeamCode", temp[7]);
				array.put(json);
			}
		}
		return array;
	}

	/**
	 * 查询患者的健康指导
	 * @param patient 患者标识
	 * @param id
	 * @param pagesize 分页大小
	 * @return
	 */
	public JSONArray findGuidanceByPatient(String patient, long id, int pagesize) {

		JSONArray array = new JSONArray();
		// 分页信息
		PageRequest pageRequest = new PageRequest(0, pagesize);
		Page<Object> page = null;
		if (id > 0) {
			page = patientHealthGuidanceDao.findByPatient(patient, id, pageRequest);
		} else {
			page = patientHealthGuidanceDao.findByPatient(patient, pageRequest);
		}
		if (page != null) {
			for (Object obj : page) {
				Object[] temp = (Object[]) obj;
				if (temp == null || temp.length != 7) {
					continue;
				}
//				控制返回内容50字以内
				String content = temp[3].toString();
				String contain = "";
				if(content.length()>50){
					contain = content.substring(0,50);
				}else {
					contain = content.substring(0,content.length()-1);
				}
				JSONObject json = new JSONObject();
				json.put("name", temp[0]);
				json.put("photo", temp[1]);
				json.put("id", temp[2]);
				json.put("content", contain);
				json.put("createTime", DateUtil.dateToStrLong((Date) temp[4]));
				json.put("level", temp[5]);
				json.put("readStatus", temp[6]);
				array.put(json);
			}
		}
		return array;
	}

	public Integer findGuidanceByPatient(String patientCode, String doctor) {
		return patientHealthGuidanceDao.findbydoctorAndPatient(doctor,patientCode);
	}
}
