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

import java.util.*;

import com.yihu.wlyy.entity.device.Device;
import com.yihu.wlyy.entity.doctor.profile.Doctor;
import com.yihu.wlyy.entity.doctor.team.admin.AdminTeamMember;
import com.yihu.wlyy.entity.doctor.team.sign.DoctorTeam;
import com.yihu.wlyy.entity.doctor.team.sign.DoctorTeamMember;
import com.yihu.wlyy.entity.patient.Patient;
import com.yihu.wlyy.entity.patient.SignFamily;
import com.yihu.wlyy.repository.deviece.DeviceDao;
import com.yihu.wlyy.repository.doctor.DoctorAdminTeamMemberDao;
import com.yihu.wlyy.repository.doctor.DoctorDao;
import com.yihu.wlyy.repository.doctor.DoctorTeamDao;
import com.yihu.wlyy.repository.doctor.DoctorTeamMemberDao;
import com.yihu.wlyy.repository.patient.PatientDao;
import com.yihu.wlyy.util.DateUtil;
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 org.springside.modules.utils.Clock;

import com.yihu.wlyy.entity.device.PatientDevice;
import com.yihu.wlyy.repository.patient.PatientDeviceDao;
import com.yihu.wlyy.service.BaseService;

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

	private Clock clock = Clock.DEFAULT;

	@Autowired
	private DoctorDao doctorDao;

	@Autowired
	private PatientDeviceDao patientDeviceDao;

	@Autowired
	private DeviceDao deviceDao;

	@Autowired
	private PatientDao patientDao;

	@Autowired
	private DoctorAdminTeamMemberDao doctorAdminTeamMemberDao;


	/**
	 * 保存患者设备
	 */
	public boolean saveDevice(PatientDevice patientDevice) throws Exception {
		//判断sn码是否被使用
		String sn = patientDevice.getDeviceSn();
		String type =  patientDevice.getCategoryCode();
		Long deviceId =  patientDevice.getDeviceId();
		String userType = patientDevice.getUserType();
		if(userType == null)
		{
			userType = "-1";
			patientDevice.setUserType("-1");
		}

		boolean needVerify = true;
		//修改操作
		if(patientDevice.getId()!=null)
		{
			PatientDevice deviceOld =  patientDeviceDao.findOne(patientDevice.getId());
			if(deviceOld!=null)
			{
				if(deviceOld.getDeviceSn().equals(sn))
				{
					needVerify = false;
				}
			}
			else{
				throw new Exception("不存在该条记录！");
			}
		}

		//校验sn码是否被使用
		if(needVerify) {
			PatientDevice device = patientDeviceDao.findByDeviceIdAndDeviceSnAndUserType(deviceId, sn, userType);
			if (device != null && !device.getId().equals(patientDevice.getId())) {
				throw new Exception("sn码" + sn + "已被使用！");
			}
		}
		patientDevice.setCzrq(clock.getCurrentDate());
		//当前用户的身份证
		Patient patient = patientDao.findByCode(patientDevice.getUser());
		patientDevice.setUserIdcard(patient.getIdcard());
		patientDeviceDao.save(patientDevice);

		return true;
	}

	/**
	 * 删除患者设备
	 */
	public void deleteDevice(String id) {
		patientDeviceDao.delete(Long.valueOf(id));
	}

	/**
	 * 患者设备列表接口（分页）
	 */
	public Page<PatientDevice> findByPatient(String patientCode, long id, int pageSize) {
		if (id < 0) {
			id = 0;
		}
		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("user", Operator.EQ, patientCode));
		if(id > 0){
			filters.put("id", new SearchFilter("id", Operator.LT, id));
		}

		Specification<PatientDevice> spec = DynamicSpecifications.bySearchFilter(filters.values(), PatientDevice.class);

		return patientDeviceDao.findAll(spec, pageRequest);
	}

	/**
	 * 患者设备列表接口--医生端
	 */
	public List<Map<String,Object>> findByDoctor(String patientCode,String doctorCode, int page, int pagesize) {
		List<Map<String,Object>> re = new ArrayList<>();
		if (page <= 0) {
			page = 1;
		}
		if (pagesize <= 0) {
			pagesize = 10;
		}

		boolean bo = false;
		//判断该医生是否属于患者的签约行政团队
		List<AdminTeamMember> adminTeamMembers = doctorAdminTeamMemberDao.findByAdminTeam(patientCode,doctorCode);
		if(adminTeamMembers!=null && adminTeamMembers.size()>0)
		{
			bo = true;
		}

		PageRequest pageRequest = new PageRequest(page-1, pagesize);

		List<PatientDevice> list = new ArrayList<>();
		if(bo) //签约医生查看所有设备
		{
			list = patientDeviceDao.findByUser(patientCode,pageRequest);
		}
		else{
			list = patientDeviceDao.findByUserAndDoctor(patientCode, doctorCode,pageRequest);
		}

		if(list!=null)
		{
			//获取设备路径,医生姓名
			List<Device> deviceList = deviceDao.findAll();
			Doctor self = doctorDao.findByCode(doctorCode);
			for(PatientDevice item :list)
			{
				Map<String,Object>  map = new HashMap<>();
				map.put("id",item.getId()) ;
				map.put("deviceId",item.getDeviceId());
				map.put("deviceSn",item.getDeviceSn());
				map.put("user",item.getUser());
				map.put("categoryCode",item.getCategoryCode());
				map.put("userType",item.getUserType());
				map.put("userIdcard",item.getUserIdcard());
				map.put("czrq", DateUtil.dateToStrLong(item.getCzrq()));
				String deviceDoctor = item.getDoctor();
				if(deviceDoctor == null)
				{
					map.put("doctor","");
					map.put("doctorName","");
				}
				else{
					map.put("doctor",deviceDoctor);
					if(deviceDoctor.equals(doctorCode))
					{
						map.put("doctorName",self.getName());
					}
					else{
						Doctor doctor = doctorDao.findByCode(deviceDoctor);
						if(doctor!=null)
						{
							map.put("doctorName",doctor.getName());
						}
						else{
							map.put("doctorName","");
						}
					}
				}


				//获取设备路径
				for(Device de : deviceList)
				{
					if(de.getId().equals(item.getDeviceId()))
					{
						map.put("deviceName",de.getName());
						map.put("devicePhoto",de.getPhoto());
						map.put("deviceBrands",de.getBrands());
						break;
					}
				}
				re.add(map);
			}
		}

		re.sort(new Comparator<Map<String, Object>>() {
			@Override
			public int compare(Map<String, Object> o1, Map<String, Object> o2) {
				if(o1.get("czrq").toString().compareTo(o2.get("czrq").toString()) > 0){
					return -1;
				}
				if(o1.get("czrq").toString().compareTo(o2.get("czrq").toString()) < 0){
					return 1;
				}

				return 0;
			}
		});

		return re;
	}

	/**
	 * 查询患者已拥有的设备
	 * @param patient
	 * @return
	 */
	public Iterator<PatientDevice> findPatientHave(String patient) {
		return patientDeviceDao.findByUser(patient).iterator();
	}

	/**
	 * 获取患者设备信息
	 **/
	public PatientDevice findById(String id) {
		return patientDeviceDao.findOne(Long.valueOf(id));
	}



	/**
	 * 通过sn码获取设备绑定情况
	 **/
	public List<Map<String,String>> getDeviceUser(String user,String deviceSn,String type) throws Exception {
		List<Map<String,String>> re = new ArrayList<>();
		List<PatientDevice> list =patientDeviceDao.findByDeviceSnAndCategoryCode(deviceSn,type);
		if(list!=null)
		{
			for(PatientDevice item:list)
			{
				Map<String,String> map = new HashMap<> ();
				map.put("type",item.getUserType());
				String code = item.getUser();
				if(code.equals(user))
				{
					map.put("others","0");
				}
				else{
					map.put("others","1");
				}

				//获取姓名
				Patient patient = patientDao.findByCode(code);
				if(patient!=null)
				{
					map.put("name",patient.getName());
				}
				else{
					map.put("name",code);
				}

				re.add(map);
			}
		}

		return re;
	}
}
