/*******************************************************************************
 * Copyright (c) 2005, 2014 springside.github.io
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *******************************************************************************/
package com.yihu.wlyy.service.common.account;

import com.yihu.wlyy.entity.doctor.profile.Doctor;
import com.yihu.wlyy.entity.doctor.team.sign.DoctorPatient;
import com.yihu.wlyy.entity.patient.Patient;
import com.yihu.wlyy.entity.patient.SignFamily;
import com.yihu.wlyy.entity.security.Token;
import com.yihu.wlyy.repository.doctor.DoctorDao;
import com.yihu.wlyy.repository.doctor.DoctorPatientDao;
import com.yihu.wlyy.repository.patient.PatientDao;
import com.yihu.wlyy.repository.patient.SignFamilyDao;
import com.yihu.wlyy.util.EncodesUtil;
import com.yihu.wlyy.util.IdcardInfoExtractor;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.utils.Clock;

import java.util.Date;

/**
 * 患者基本信息类.
 * 
 * @author George
 */
@Component
@Transactional(rollbackFor = Exception.class)
public class PatientService extends TokenService {

	@Autowired
	private SignFamilyDao signFamilyDao;
	@Autowired
	private PatientDao patientDao;
	@Autowired
	private DoctorDao doctorDao;
	@Autowired
	private DoctorPatientDao doctorPatientDao;

	private Clock clock = Clock.DEFAULT;

	public void setClock(Clock clock) {
		this.clock = clock;
	}

	public Patient findByCode(String code) {
		return patientDao.findByCode(code);
	}

	public Patient findByIdcard(String idcard) {
		return patientDao.findByIdcard(idcard);
	}

	public Patient findBySsc(String ssc) {
		return patientDao.findBySsc(ssc);
	}

	public Patient findByMobile(String mobile) {
		return patientDao.findByMobile(mobile);
	}

	public Patient findByOpenid(String openid) {
		return patientDao.findByOpenid(openid);
	}

	public int countByOpenid(String openid) {
		return patientDao.countByOpenid(openid);
	}

	/**
	 * 修改患者密码
	 * @param patient
	 */
	public void updatePatientPwd(Patient patient) {
		EncodesUtil.entryptPassword(patient);
		patientDao.save(patient);
	}

	public void updatePatientInfo(Patient patient) {
		patientDao.save(patient);
	}

	/**
	 * 修改患者openid
	 * @param patient
	 */
	public void updatePatient(Patient patient) {
		if (StringUtils.isNotEmpty(patient.getOpenid())) {
			patientDao.clearOpenid(patient.getCode(), patient.getOpenid());
		}
		patientDao.save(patient);
		if (StringUtils.isNotEmpty(patient.getOpenid())) {
			signFamilyDao.updateOpenidByPatient(patient.getOpenid(), patient.getCode());
		}
	}

	public void deletePatient(Patient patient) {
		patientDao.delete(patient);
	}

	public void deletePatients(Iterable<Patient> patients) {
		patientDao.delete(patients);
	}

	/**
	 * 患者註冊
	 * @param patient
	 * @return
	 * @throws Exception
	 */
	public JSONObject register(Patient patient, String imei, int platform) throws Exception {
		IdcardInfoExtractor ie = new IdcardInfoExtractor(patient.getIdcard());
		patient.setBirthday(ie.getBirthday());
		patient.setSex(ie.getGender());
		patient.setCode(getCode());
		patient.setStatus(1);
		patient.setCzrq(clock.getCurrentDate());
		patient.setDisease(0);
		patient.setDiseaseCondition(0);
		patient.setRecordAmount(0);
		patient.setPoints(0);
		Patient temp = patientDao.save(patient);
		if (temp != null) {
			// 更新openid
			updatePatient(temp);
			// 生成登录tokey
			Token token = newToken(temp.getCode(), imei, platform);
			if (token != null) {
				// 生成登录信息成功
				JSONObject json = new JSONObject();
				json.put("id", temp.getId());
				json.put("uid", temp.getCode());
				json.put("token", token.getToken());
				json.put("name", temp.getName());
				json.put("photo", temp.getPhoto());
				return json;
			}
		}
		return null;
	}

	/**
	 * 建立三师团队与患者的关系
	 * @param sf
	 * @param patient
	 * @param doctorCode
	 * @param doctorType
	 */
	private void bindDoctorPatient(SignFamily sf, Patient patient, String doctorCode, int doctorType) {
		DoctorPatient dp = doctorPatientDao.findByPatientDoctorTeamType(patient.getCode(), doctorCode, doctorType);
		if (dp == null) {
			Doctor doctor = doctorDao.findByCode(doctorCode);
			dp = new DoctorPatient();
			dp.setBirthday(patient.getBirthday());
			dp.setCzrq(new Date());
			dp.setDoctor(doctor.getCode());
			dp.setDoctorName(doctor.getName());
			// 健康管理师
			dp.setDoctorType(doctorType);
			dp.setPatient(patient.getCode());
			dp.setPatientName(patient.getName());
			dp.setSex(patient.getSex());
			if (sf != null) {
				// 三师和家庭都存在
				dp.setSignType("11");
			} else {
				// 只有家庭签约
				dp.setSignType("01");
			}
			dp.setStatus(1);
			// 设置为三师团队
			dp.setTeamType(1);
			// 保存到数据库
			doctorPatientDao.save(dp);
		}
	}

	/**
	 * 微信端患者註冊
	 * @param patient
	 * @return
	 * @throws Exception
	 */
	public JSONObject register(Patient patient) throws Exception {
		patient.setCode(getCode());
		patient.setCzrq(clock.getCurrentDate());
		EncodesUtil.entryptPassword(patient);
		Patient temp = patientDao.save(patient);
		if (temp != null) {
			JSONObject json = new JSONObject();
			json.put("id", temp.getId());
			json.put("uid", temp.getCode());
			json.put("name", "");
			json.put("openid", temp.getOpenid());
			return json;
		}
		return null;
	}

}
