package com.yihu.wlyy.web.doctor.consult;

import java.util.List;
import java.util.Map;

import com.yihu.wlyy.service.app.health.PatientHealthGuidanceService;
import com.yihu.wlyy.service.app.scheduling.DoctorWorkTimeService;
import com.yihu.wlyy.service.common.account.DoctorService;
import io.swagger.annotations.Api;
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.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.yihu.wlyy.entity.consult.ConsultTeam;
import com.yihu.wlyy.entity.consult.ConsultTeamLog;
import com.yihu.wlyy.entity.doctor.profile.Doctor;
import com.yihu.wlyy.entity.patient.Patient;
import com.yihu.wlyy.service.app.account.DoctorInfoService;
import com.yihu.wlyy.service.app.account.PatientInfoService;
import com.yihu.wlyy.service.app.consult.ConsultTeamService;
import com.yihu.wlyy.task.PushMsgTask;
import com.yihu.wlyy.util.CommonUtil;
import com.yihu.wlyy.util.DateUtil;
import com.yihu.wlyy.web.WeixinBaseController;

/**
 * 医生端：三师咨询控制类
 * @author George
 *
 */
@Controller
@RequestMapping(value = "/doctor/consult")
@Api(description = "三师咨询")
public class DoctorConsultController extends WeixinBaseController {

	@Autowired
	private ConsultTeamService consultTeamService;
	@Autowired
	private PatientInfoService patientService;
	@Autowired
	private DoctorInfoService doctorInfoService;
	@Autowired
	private PatientHealthGuidanceService patientHealthGuidanceService;
	@Autowired
	private DoctorService doctorService;
	@Autowired
	private DoctorWorkTimeService doctorWorkTimeService;

	/**
	 * 三师咨询列表查询
	 * @param type 咨询类型：0、全部，1、咨询我的，2、公共的， 3、参与过的，4、已结束的  5 名医咨询 全部  6 名医咨询 进行中 7 名医咨询 已结束 8名医咨询 待处理 9咨询我的三师 + 家庭 + 名医
	 * @param id
	 * @param pagesize 每页显示数，默认为10
	 * @return
	 */
	@RequestMapping(value = "list")
	@ResponseBody
	public String list(int type, int id, int pagesize, @RequestParam(required = false) String patient, @RequestParam(required = false) String title) {
		try {
			Page<ConsultTeam> list = consultTeamService.findByDoctor(getUID(), type, id, pagesize,title);
			JSONArray jsonArray = new JSONArray();
			for (ConsultTeam consult : list) {
				if (consult == null) {
					continue;
				}

				if (StringUtils.isNotBlank(patient) && !StringUtils.equals(patient, consult.getPatient())) {
					continue;
				}

				JSONObject json = new JSONObject();
				json.put("id", consult.getId());
				// 设置咨询标识
				json.put("consult", consult.getConsult());
				// 设置患者标识
				json.put("patient", consult.getPatient());
				// 设置患者头像
				json.put("photo", consult.getPhoto());
				// 设置咨询标识
				json.put("title", consult.getSymptoms());
				// 设置患者姓名
				json.put("name", consult.getName());
				// 设置患者年龄
				json.put("age", DateUtil.getAgeByBirthday(consult.getBirthday()));
				// 设置评价内容
				json.put("comment", consult.getCommentContent());
				// 设置评价星级
				json.put("star", consult.getCommentStar());
				// 设置咨询类型：1三师咨询，2家庭医生咨询 6名医咨询
				json.put("type", consult.getType());
				// 设置咨询时间
				json.put("time", DateUtil.dateToStr(consult.getCzrq(), DateUtil.YYYY_MM_DD_HH_MM_SS));
				// 咨询状态
				json.put("status", consult.getStatus());
				// 设置性别
				json.put("sex", consult.getSex());
				// 未读消息
				json.put("doctorRead", consult.getDoctorRead());

				jsonArray.put(json);
			}
			return write(200, "查询成功", "list", jsonArray);
		} catch (Exception e) {
			error(e);
			return invalidUserException(e, -1, "查询失败！");
		}
	}

	/**
	 * 名医列表
	 * @return
	 */
	@RequestMapping(value = "famousDoctorList")
	@ResponseBody
	public String famousDoctorList(
			@RequestParam(required = false) String name,
			int page,
			int pagesize) {
		try {
			JSONArray array = new JSONArray();
			Page<Doctor>list = doctorService.famousDoctorList(name, page, pagesize);
			if (list != null) {
				for (Doctor doctor : list) {
					if (doctor == null) {
						continue;
					}

					// 判断名医是否在工作
					JSONObject isWorking = doctorWorkTimeService.isFamousDoctorWorking(doctor.getCode());

					if(isWorking == null || !isWorking.getString("status").equals("1")){
						continue;
					}

					JSONObject json = new JSONObject();
					json.put("id", doctor.getId());
					// 医生标识
					json.put("code", doctor.getCode());
					// 医生性别
					json.put("sex", doctor.getSex());
					// 医生姓名
					json.put("name", doctor.getName());
					// 所在医院名称
					json.put("hospital", doctor.getHospital());
					// 所在医院名称
					json.put("hospital_name", doctor.getHosptialName());
					// 科室名称
					json.put("dept_name", (doctor.getDeptName() == null ||
							StringUtils.isEmpty(doctor.getDeptName().toString())) ? " " : doctor.getDeptName());
					// 职称名称
					json.put("job_name", (doctor.getJobName() == null ||
							StringUtils.isEmpty(doctor.getJobName().toString())) ? " " : doctor.getJobName());
					// 头像
					json.put("photo", doctor.getPhoto());
					// 简介
					json.put("introduce", doctor.getIntroduce());
					// 专长
					json.put("expertise", doctor.getExpertise());
					// 剩余咨询次数
					json.put("num", doctorWorkTimeService.getDoctorConsultTimesRemain(doctor.getCode()));
					array.put(json);
				}
			}
			return write(200, "获取医院医生列表成功！", "list", array);
		} catch (Exception e) {
			error(e);
			return error(-1, "获取医院医生列表失败！");
		}
	}

	/**
	 * 获取咨询全科医生签约量
	 *
	 * @param consults
	 * @return
	 */
	@RequestMapping(value = "/consult_sign")
	@ResponseBody
	public String consultSign(String consults){
		try{
            List<Map<String,Object>>  list = consultTeamService.getConsultSign(consults.split(","));
			return write(200,"查询成功","data",new JSONArray(list));
		}catch (Exception e){
			e.printStackTrace();
			return error(-1,"查询失败");
		}
	}

	/**
	 * 三师咨询转接接口
	 * @param consult 图咨询标识
	 * @param doctor 转接对象标识 健康管理师转全科是 1个    全科转专科是多个  传多个doctor逗号分隔
	 * @param type 转接对象类型，1三师团队，2指定医生，3工作组团队  
	 * @return
	 */
	@RequestMapping(value = "transfer")
	@ResponseBody
	public String transfer(
			String consult, 
			String doctor, 
			@RequestParam(required = false)int type) {
		try {
			consultTeamService.transfers(getUID(), doctor, consult);
			return success("转接成功");
		} catch (Exception e) {
			error(e);
			return error(-1, "转接失败！");
		}
	}

	/**
	 * 结束三师咨询接口
	 * @param consult 三师咨询标识
	 * @return
	 */
	@RequestMapping(value = "finish")
	@ResponseBody
	public String finish(String consult) {
		try {
			int flag = consultTeamService.finish(consult);
			if (flag > 0) {
				return success("咨询已关闭");
			} else {
				return error(-1, "关闭失败！");
			}
		} catch (Exception e) {
			error(e);
			return invalidUserException(e, -1, "关闭失败！");
		}
	}

	/**
	 * 设置消息已读
	 *
	 * @param consult
	 * @return
	 */
	@RequestMapping(value = "/readed")
	@ResponseBody
	public String readMessage(String consult){
		try{
			int result = consultTeamService.readMessage(consult);
			return write(200,"设置成功!");
		}catch (Exception e){
			e.printStackTrace();
			return error(-1,"设置失败");
		}
	}

	/**
	 * 医生咨询咨询日志查询
	 * @param consult 咨询标识
	 * @param patient 患者标识
	 * @param pagesize 每页显示数，默认为10
	 * @return
	 */
	@RequestMapping(value = "record")
	@ResponseBody
	public String record(String consult, String patient, long id, int pagesize) {
		try {
			Patient patientTemp = null;
			if (id <= 0) {
				// 只有第一页才会查询患者信息
				patientTemp = patientService.findByCode(patient);
				// 更新医生未读数量为0
				consultTeamService.clearDoctorRead(consult);
			}
			// 查询日志列表
			JSONArray jsonArray = new JSONArray();
			Page<ConsultTeamLog> list = consultTeamService.findLogByConsult(consult, id, pagesize);
			if (list != null) {
				for (ConsultTeamLog log : list) {
					if (consult == null) {
						continue;
					}
					JSONObject json = new JSONObject();
					json.put("id", log.getId());
					// 设置回复内容
					json.put("content", log.getContent());
					// 设置回复医生姓名
					json.put("doctorName", log.getDoctorName());
					// 设置回复人头像
					json.put("photo", log.getPhoto());
					// 设置日志类型
					json.put("type", log.getType());
					// 设置记录类型
					json.put("chatType", log.getChatType());
					// 设置咨询或回复时间
					json.put("time", DateUtil.dateToStr(log.getCzrq(), DateUtil.YYYY_MM_DD_HH_MM_SS));
					jsonArray.put(json);
				}
			}
			// 设置返回结果
			JSONObject values = new JSONObject();
			if (patientTemp != null) {
				JSONObject patientJson = new JSONObject();
				// 设置患者标识
				patientJson.put("patient", patientTemp.getCode());
				// 设置姓名
				patientJson.put("name", patientTemp.getName());
				// 设置头像
				patientJson.put("photo", patientTemp.getPhoto());
				values.put("patient", patientJson);
			}
			values.put("list", jsonArray);
			// 返回结果
			return write(200, "查询成功", "data", values);
		} catch (Exception e) {
			error(e);
			return invalidUserException(e, -1, "查询失败！");
		}
	}

	/**
	 * 医生回复网络咨询
	 * @param patient 患者标识
	 * @param consult 咨询标识
	 * @param content 回复内容
	 * @param type	回复类型，1文字，2图片，3语音
	 * @return
	 */
	@RequestMapping(value = "reply")
	@ResponseBody
	public String reply(String patient, String consult, String content, int type) {
		try {
			// 查询医生基本信息
			Doctor doctor = doctorInfoService.findDoctorByCode(getUID());
			if (doctor == null) {
				return error(-1, "回复失败！");
			} else {
				ConsultTeamLog log = new ConsultTeamLog();
				// 设置咨询标识
				log.setConsult(consult);
				// 拷贝图片
				if (StringUtils.isNotEmpty(content)) {
					if (type == 3) {
						// 语音
						content = CommonUtil.copyTempVoice(content);
					} else if (type == 2) {
						// 图片
						content = CommonUtil.copyTempImage(content);
					}
				}
				// 设置回复内容
				log.setContent(content);
				log.setDel("1");
				// 设置回复医生标识
				log.setDoctor(doctor.getCode());
				// 设置医生姓名
				log.setDoctorName(doctor.getName());
				// 设置医生头像
				log.setPhoto(doctor.getPhoto());
				// 设置咨询类型为医生回复
				log.setType(1);
				// 设置记录类型
				log.setChatType(type);
				// 保存医生回复内容
				log = consultTeamService.reply(log, patient, getUID(), log.getType());
				if (log == null) {
					return error(-1, "回复失败！");
				} else {
					// 推送消息给患者
					// PushMsgTask.getInstance().put(patient, MessageType.MESSAGE_TYPE_PATIENT_CONSULT_TEAM_REPLY.P_CT_01.name(), MessageType.MESSAGE_TYPE_PATIENT_CONSULT_TEAM_REPLY.三师咨询.name(), MessageType.MESSAGE_TYPE_PATIENT_CONSULT_TEAM_REPLY.医生回复了您.name(), consult);
					// 推送消息给微信端
					ConsultTeam ct = consultTeamService.findByCode(consult);
					Patient p = patientService.findByCode(patient);
					if (ct != null && p != null && StringUtils.isNotEmpty(p.getOpenid())) {
						JSONObject json = new JSONObject();
						json.put("first", "问诊回复提醒");
						json.put("consultcontent", ct.getSymptoms());
						String replycontent = content.length() > 15 ? content.substring(0, 15) + "..." : content;
						if (type == 2) {
							replycontent = "[图片]";
						} else if (type == 3) {
							replycontent = "[语音]";
						}
						json.put("consult", consult);
						json.put("replycontent", replycontent);
						json.put("doctorName", doctor.getName());
						json.put("remark", "医生已为您提供问诊方案");
						PushMsgTask.getInstance().putWxMsg(getAccessToken(), 3, p.getOpenid(), p.getName(), json);
					}
					if (type == 2) {
						return write(200, "回复成功！", "data", content);
					}
					return success("回复成功！");
				}
			}
		} catch (Exception e) {
			error(e);
			return invalidUserException(e, -1, "回复失败！");
		}
	}

	/**
	 * 查询医生的总咨询次数和今日咨询次数
	 * @param doctorCode
	 * @return
	 */
	@RequestMapping(value = "getConsultCount")
	@ResponseBody
	public String getAllCount(@RequestParam(required = true) String doctorCode) {
		try {
			JSONObject json = new JSONObject();
			Map<String,Long> counts=consultTeamService.getAllCount(doctorCode);
			
			json.put("all", counts.get("all"));
			json.put("today", counts.get("today"));
			return json.toString();
		} catch (Exception e) {
			error(e);
			return error(-1, "回复失败！");
		}
	}

	/**
	 * 查询患者的服务数目
	 * @return
     */
	@RequestMapping(value = "getPatientServicNum")
	@ResponseBody
	public String getPatientServicNum(String patientCode) {
		try {
			JSONObject json = new JSONObject();
			//统计咨询数目
			Integer allSize1=consultTeamService.findByDoctorSize(patientCode,getUID());
			//查询健康指导
			Integer allSize2=patientHealthGuidanceService.findGuidanceByPatient(patientCode,getUID());
			json.put("consult", allSize1);
			json.put("guide", allSize2);
			//json.put("today", counts.get("today"));
			return json.toString();
		} catch (Exception e) {
			error(e);
			return error(-1, "回复失败！");
		}
	}

	/**
	 * 根据医生code和和患者code判断是否有存在进行中的咨询
	 * @param patientCode 多个患者 逗号分隔
	 * @param doctor
	 * @return 只返回存在咨询的患者的code
     */
	@RequestMapping(value = "getConsultByPatientAndDoctor")
	@ResponseBody
	public String getConsultByPatientAndDoctor(String patientCode,String doctor) {
		try {
			JSONArray json = new JSONArray();
			String []patients=patientCode.split(",");
			for(int i=0 ;i<patients.length;i++){
				ConsultTeam consultTeam= consultTeamService.getConsultByPatientAndDoctor(patients[i],doctor);
				if(consultTeam!=null){
					json.put(patients[i]);
				}
			}
			return json.toString();
		} catch (Exception e) {
			error(e);
			return error(-1, "回复失败！");
		}
	}

}
