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

import com.yihu.wlyy.aop.ObserverRequired;
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.logs.BusinessLogs;
import com.yihu.wlyy.service.app.consult.ConsultService;
import com.yihu.wlyy.service.app.health.PatientHealthGuidanceService;
import com.yihu.wlyy.service.common.account.DoctorService;
import com.yihu.wlyy.service.common.account.PatientService;
import com.yihu.wlyy.service.template.DoctorGuidanceTempService;
import com.yihu.wlyy.util.CommonUtil;
import com.yihu.wlyy.web.WeixinBaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 医生端：健康指导控制类
 * @author George
 *
 */
@Controller
@RequestMapping(value = "/doctor/health/guidance", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "健康指导")
public class DoctorHealthGuidanceController extends WeixinBaseController {

	@Autowired
	private PatientHealthGuidanceService patientHealthGuidanceService;

	@Autowired
	private DoctorService doctorService;

	@Autowired
	private PatientService patientService;

	@Autowired
	private ConsultService consultService;
//======================
	@Autowired
	DoctorGuidanceTempService doctorGuidanceTempService;
//	=======================
	/**
	 * 获取某个健康指导
	 *
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/id")
	@ResponseBody
	public String getHealthGuidance(@RequestParam String id){
		Long idl = Long.parseLong(id);
		try{
			if(idl == null || idl < 1){
				return error(-1,"参数错误");
			}

			JSONObject guidance = patientHealthGuidanceService.findById(idl);
			return write(200,"查询成功","data",guidance);
		}catch (Exception e){
			return error(-1,"查询失败");
		}
	}

	/*/**
	 * 添加患者健康指导
	 * @param patient 患者标识
	 * @param content 指导内容
	 * @return
	 */
	/*@RequestMapping(value = "add")
	@ResponseBody
	public String add(String patient, String content, @RequestParam(required = false) String images, @RequestParam(required = false) String voice) {
		try {
			PatientHealthGuidance guidance = new PatientHealthGuidance();
			guidance.setContent(content);
			guidance.setDoctor(getUID());
			guidance.setPatient(patient);
			Doctor doctor = doctorService.findDoctorByCode(getUID());
			if (StringUtils.isNotEmpty(images)) {
				images = CommonUtil.copyTempImage(images);
			}
			guidance.setImages(images);

			if (StringUtils.isNotEmpty(voice)) {
				images = CommonUtil.copyTempVoice(voice);
			}
			guidance.setVoice(voice);

			// 保存
			if (patientHealthGuidanceService.add(guidance, getAccessToken()) != null) {
				Patient p = patientService.findByCode(patient);
				consultService.sendMucMessageBySingnType(getUID(),doctor.getName(),patient,content,"1",p.getName());
				BusinessLogs.info(BusinessLogs.BusinessType.guidance, patient, new JSONObject(guidance));
				return success("保存成功！");
			} else {
				return error(-1, "保存失败！");
			}
		} catch (Exception e) {
			error(e);
			return error(-1, "保存失败！");
		}
	}*/
	//  ====================修改代码========================

	/**
	 * 添加患者健康指导（modelCode不为空判断为使用模板）
	 * @param patient 患者标识
	 * @param content 指导内容
	 * @param modelCode 指导模板编码
	 * @param images   指导图片
	 * @param voice   指导语音
	 * @return
	 */
	@RequestMapping(value = "add")
	@ResponseBody
	@ObserverRequired
	public String add(@RequestParam String patient,
					  @RequestParam String content,
					  @RequestParam(required = false) String modelCode,
					  @RequestParam(required = false) String images,
					  @RequestParam(required = false) String voice) {

		String imageUrls = "";
		String imageRow = "";

		if(StringUtils.isBlank(modelCode)) {
//			不使用模板指导，旧版手工指导
			try {
				PatientHealthGuidance guidance = new PatientHealthGuidance();
				guidance.setContent(content);
				guidance.setDoctor(getUID());
				guidance.setPatient(patient);
//				找到当前医生
				Doctor doctor = doctorService.findDoctorByCode(getUID());
				if (images==null||"".equals(images)) {
					images=null;
				}else {
					String[] imgs = images.split(",");
					for (String image : imgs) {
						if (image.contains("http://")) {
							imageUrls += image + ",";
						} else {
							try {
								imageRow += CommonUtil.copyTempImage(image)+",";
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
					}

					images = imageUrls + imageRow;
					images =  images.substring(0,images.length()-1);
				}
				/*if (StringUtils.isNotEmpty(images)) {
					images = CommonUtil.copyTempImage(images);
				}*/
				guidance.setImages(images);

				// 保存到居民端健康指导
				if (patientHealthGuidanceService.add(guidance, getAccessToken()) != null) {
					Patient p = patientService.findByCode(patient);
					String imcotent  = "{\"title\":\"健康指导\",\"type\":2,\"id\":\"" + guidance.getId() + "\",\"img\":\"" + guidance.getImages() + "\",\"content\":\""+CommonUtil.getSubString(guidance.getContent(),0,30)+"\"}";
					consultService.sendMucMessageBySingnType(getUID(), doctor.getName(), patient, imcotent, "4", p.getName());
					BusinessLogs.info(BusinessLogs.BusinessType.guidance, getUID(), patient, new JSONObject(guidance));
					return success("保存成功！");
				} else {
					return error(-1, "保存失败！");
				}
			} catch (Exception e) {
				error(e);
				return error(-1, "保存失败！");
			}
		}else{
			try{
				PatientHealthGuidance guidance = new PatientHealthGuidance();
				guidance.setContent(content);
				guidance.setDoctor(getUID());
				guidance.setPatient(patient);
				Doctor doctor = doctorService.findDoctorByCode(getUID());
				if (images==null||"".equals(images)) {
					images = null;
				}else {
					String[] imgs = images.split(",");
					for (String image : imgs) {
						if (image.contains("http://")) {
							imageUrls += image + ",";
						} else {
							try {
								imageRow += CommonUtil.copyTempImage(image)+",";
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
					}

					images = imageUrls + imageRow;
					images =  images.substring(0,images.length()-1);
				}
				guidance.setImages(images);

				// 保存
				if (patientHealthGuidanceService.add(guidance, getAccessToken()) != null) {
					String sendImgs = "";
					if(StringUtils.isNotBlank(images)){
						sendImgs = images;
					}
					Patient p = patientService.findByCode(patient);
					String imcotent  = "{\"title\":\"健康指导\",\"type\":2,\"id\":\"" + guidance.getId() + "\",\"img\":\"" + sendImgs + "\",\"content\":\""+CommonUtil.getSubString(guidance.getContent(),0,30)+"\"}";
					consultService.sendMucMessageBySingnType(getUID(), doctor.getName(), patient, imcotent, "4", p.getName());
					BusinessLogs.info(BusinessLogs.BusinessType.guidance, getUID(), patient, new JSONObject(guidance));
					//发送成功记录模板发送次数
					doctorGuidanceTempService.countSend(modelCode);
					return success("保存成功！");
				} else {
					return error(-1, "保存失败！");
				}
			}catch (Exception e){
				error(e);
				return error(-1, "保存失败！");
			}
		}
	}
	//  ============================================

	/**
	 * 查询患者的健康指导
	 * @param patient 患者标识
	 * @param begin   开始时间
	 * @param end     结束时间
	 * @param id	  指导编码
	 * @param pagesize 展示页数
	 * @return
	 */
	@RequestMapping(value = "list")
	@ResponseBody
	public String list(@RequestParam(required = false) String patient,
					   @RequestParam(required = false) String begin,
					   @RequestParam(required = false) String end,
					   @RequestParam String id,
					   @RequestParam String pagesize) {
		try {
			Long idl = Long.parseLong(id);
			int  page = Integer.parseInt(pagesize);
			if (StringUtils.isNotEmpty(begin)) {
				begin = begin + " 00:00:00";
			}
			if (StringUtils.isNotEmpty(end)) {
				end = end + " 23:59:59";
			}
			JSONArray array = patientHealthGuidanceService.findPatientGuidanceByDoctor(getUID(), patient, begin, end, idl, page);
			return write(200, "查询成功！", "list", array);
		} catch (Exception e) {
			error(e);
			return error(-1, "查询失败！");
		}
	}


	/**
	 * 查询患者的健康指导
	 *
	 * @param patient
	 * @param teamCode
	 * @param page
	 * @param pagesize
	 * @return
	 */
	@RequestMapping(value = "list_by_team", method = {RequestMethod.GET, RequestMethod.POST})
	@ResponseBody
	@ApiOperation(value = "查询居民健康指导记录")
	public String list(@RequestParam @ApiParam(value = "居民code") String patient,
					   @RequestParam @ApiParam(value = "团队Code") Long teamCode,
					   @RequestParam @ApiParam(value = "第几页") int page,
					   @RequestParam @ApiParam(value = "页大小") int pagesize) {
		try {
			if (StringUtils.isEmpty(patient)) {
				return error(-1, "请输入需查询的居民");
			}
			if (teamCode == null || teamCode < 1) {
				return error(-1, "请输入需查询的居民的团队");
			}
			page = page > 0 ? page - 1 : 0;
			JSONArray result = patientHealthGuidanceService.findByPatientAndGuidanceAndTeam(patient,teamCode,page,pagesize);
			return write(200, "查询成功！", "data", result);
		} catch (Exception e) {
			error(e);
			return error(-1, "查询失败！");
		}
	}

}
