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

import com.yihu.wlyy.entity.dict.Medicines;
import com.yihu.wlyy.entity.education.Sports;
import com.yihu.wlyy.entity.education.SportsType;
import com.yihu.wlyy.entity.patient.PatientHealthRecordDiet;
import com.yihu.wlyy.entity.patient.PatientHealthRecordMedication;
import com.yihu.wlyy.entity.patient.PatientHealthRecordSports;
import com.yihu.wlyy.service.app.health.PatientHealthRecordService;
import com.yihu.wlyy.service.app.medicines.MedicinesService;
import com.yihu.wlyy.service.app.sports.SportsService;
import com.yihu.wlyy.util.CommonUtil;
import com.yihu.wlyy.util.DateUtil;
import com.yihu.wlyy.web.WeixinBaseController;
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.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;

import java.util.Date;
import java.util.List;

/**
 * 健康记录控制类
 * @author George
 *
 */
@Controller
@RequestMapping(value = "/patient/health_record", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "患者端-健康记录")
public class PatientHealthRecordController extends WeixinBaseController {

	@Autowired
	private SportsService sportsService;

	@Autowired
	private MedicinesService medicinesService;

	@Autowired
	private PatientHealthRecordService patientHealthRecordService;

	/**
	 * 保健记录更改接口（包括手动记录的修改和所有的删除）
	 *
	 * @param id
	 * @param type   饮食1，运动2，用药3
	 * @param value1 记录时间
	 * @param value2 饮食内容CONTETN  时长 用药
	 * @param value3 上传图片 强度
	 * @param value4 运动项目
	 * @return
	 */
	@RequestMapping(value = "/modifyHealthCare", method = RequestMethod.POST)
	@ResponseBody
	public String modifyHealthCare(@RequestParam long id,
								   @RequestParam int type,
								   @RequestParam(required = false) String value1,
								   @RequestParam(required = false) String value2,
								   @RequestParam(required = false) String value3,
								   @RequestParam(required = false) String value4) {
		try {
			patientHealthRecordService.modifyHealthCare(id, type, value1, value2, value3, value4);
			return write(200, "更改成功！");
		} catch (Exception e) {
			error(e);
			return invalidUserException(e, -1, "更改失败！");
		}
	}



	/**
	 * 运动强度查询接口
	 * @return
	 */
	@RequestMapping(value = "sports_type")
	@ResponseBody
	public String sportsType() {
		try {
			JSONArray array = new JSONArray();
			List<SportsType> list = sportsService.finsAllSportsType();
			if (list != null) {
				for (SportsType temp : list) {
					if (temp == null) {
						continue;
					}
					JSONObject json = new JSONObject();
					json.put("code", temp.getCode());
					json.put("name", temp.getName());
					array.put(json);
				}
			}
			return write(200, "查询成功", "list", array);
		} catch (Exception e) {
			error(e);
			return error(-1, "查询失败");
		}
	}

	/**
	 * 运动类型查询接口
	 * @return
	 */
	@RequestMapping(value = "sports")
	@ResponseBody
	public String sports() {
		try {
			JSONArray array = new JSONArray();
			List<Sports> list = sportsService.finsAllSports();
			if (list != null) {
				for (Sports temp : list) {
					if (temp == null) {
						continue;
					}
					JSONObject json = new JSONObject();
					json.put("code", temp.getCode());
					json.put("name", temp.getName());
					array.put(json);
				}
			}
			return write(200, "查询成功", "list", array);
		} catch (Exception e) {
			error(e);
			return error(-1, "查询失败");
		}
	}

	/**
	 * 查询药品列表
	 * @return
	 */
	@RequestMapping(value = "medicines")
	@ResponseBody
	public String medicines() {
		try {
			JSONArray array = new JSONArray();
			List<Medicines> list = medicinesService.findAllMedicines(1);
			if (list != null) {
				for (Medicines temp : list) {
					if (temp == null) {
						continue;
					}
					JSONObject json = new JSONObject();
					json.put("code", temp.getCode());
					json.put("name", temp.getName());
					array.put(json);
				}
			}
			return write(200, "查询成功", "list", array);
		} catch (Exception e) {
			error(e);
			return error(-1, "查询失败");
		}
	}

	/**
	 * 添加运动记录
	 * @param record_date 记录时间
	 * @param sportsTime 运动时长（分）
	 * @param sportsType 运动强度标识
	 * @param sports 运动类型标识
	 * @return
	 */
	@RequestMapping(value = "add_sports")
	@ResponseBody
	public String addSports(String record_date, double sportsTime, String sportsType, String sports) {
		try {
			PatientHealthRecordSports record = new PatientHealthRecordSports();
			record.setDel("1");
			record.setCzrq(new Date());
			record.setPatient(getRepUID());
//			record.setPatient(getUID());
			record.setRecordDate(DateUtil.strToDateShort(record_date));
			record.setSortDate(DateUtil.strToDateAppendNowTime(record_date, DateUtil.YYYY_MM_DD_HH_MM_SS));
			record.setSportsTime(sportsTime);
			if (patientHealthRecordService.addSports(record, sportsType, sports) != null) {
				return success("保存成功");
			} else {
				return error(-1, "保存失败");
			}
		} catch (Exception e) {
			error(e);
			return error(-1, "保存失败");
		}
	}

	/**
	 * 添加用药记录
	 * @param record_date 记录时间
	 * @param medicines 药品标识
	 * @param medicines_name 药品名称
	 * @return
	 */
	@RequestMapping(value = "add_medication")
	@ResponseBody
	public String addMedication(String record_date, String medicines, String medicines_name) {
		try {
			PatientHealthRecordMedication record = new PatientHealthRecordMedication();
			record.setDel("1");
			record.setCzrq(new Date());
			record.setPatient(getRepUID());
//			record.setPatient(getUID());
			record.setRecordDate(DateUtil.strToDateShort(record_date));
			record.setSortDate(DateUtil.strToDateAppendNowTime(record_date, DateUtil.YYYY_MM_DD_HH_MM_SS));
			record.setMedicines(medicines);
			record.setMedicinesName(medicines_name);
			if (patientHealthRecordService.addMedication(record) != null) {
				return success("保存成功");
			} else {
				return error(-1, "保存失败");
			}
		} catch (Exception e) {
			error(e);
			return error(-1, "保存失败");
		}
	}

	/**
	 * 添加饮食记录接口
	 * @param record_date 记录时间
	 * @param content 饮食内容
	 * @param images 图片HTTP地址，多图以逗号分隔
	 * @return
	 */
	@RequestMapping(value = "add_diet")
	@ResponseBody
	public String add(String record_date, String content, @RequestParam(required = false) String images) {
		try {
			PatientHealthRecordDiet record = new PatientHealthRecordDiet();
			record.setDel("1");
			record.setCzrq(new Date());
			record.setPatient(getRepUID());
//			record.setPatient(getUID());
			record.setRecordDate(DateUtil.strToDateShort(record_date));
			record.setSortDate(DateUtil.strToDateAppendNowTime(record_date, DateUtil.YYYY_MM_DD_HH_MM_SS));
			record.setContent(content);
			// 从微信服务器获取图片
			if (StringUtils.isEmpty(images)) {
				images = fetchWxImages();
			}
			if (StringUtils.isNotEmpty(images)) {
				images = CommonUtil.copyTempImage(images);
			}
			record.setImages(images);
			if (patientHealthRecordService.addDiet(record) != null) {
				return success("保存成功");
			} else {
				return error(-1, "保存失败");
			}
		} catch (Exception e) {
			error(e);
			return error(-1, "保存失败");
		}
	}

	/**
	 * 最近填写的运动、用药、饮食内容
	 * @return
	 */
	@RequestMapping(value = "recent")
	@ResponseBody
	public String recent() {
		try {
//			JSONObject json = patientHealthRecordService.findRecentByPatient(getUID());
			JSONObject json = patientHealthRecordService.findRecentByPatient(getRepUID());
			if (json != null) {
				return write(200, "查询成功", "data", json);
			} else {
				return error(-1, "查询失败");
			}
		} catch (Exception e) {
			error(e);
			return error(-1, "查询失败");
		}
	}

	/**
	 * 运动记录查询接口
	 * @param pagesize 分页大小
	 * @return
	 */
	@RequestMapping(value = "list_sports")
	@ResponseBody
	public String sports(String start,String end,int page, int pagesize) {
		try {
			Page<PatientHealthRecordSports> data = patientHealthRecordService.findSportsByPatientPage(getRepUID(), start,end,page, pagesize);
//			Page<PatientHealthRecordSports> data = patientHealthRecordService.findSportsByPatientPage(getUID(), start,end,page, pagesize);
			if (data != null) {
				JSONArray array = new JSONArray();
				for (PatientHealthRecordSports record : data) {
					if (record == null) {
						continue;
					}
					JSONObject json = new JSONObject();
					json.put("id", record.getId());
					// 设置记录标识
					json.put("code", record.getCode());
					// 设置记录日期
					json.put("record_date", DateUtil.dateToStrShort(record.getRecordDate()));
					json.put("sortDate", DateUtil.dateToStrLong(record.getSortDate()));
					// 设置运动时长（分钟）
					json.put("sports_time", record.getSportsTime());
					// 设置运动强度
					json.put("sports_type", record.getSportsTypeName());
					// 设置运动类型
					json.put("sports", record.getSportsName());
					array.put(json);
				}
				return write(200, "查询成功", "list", array);
			} else {
				return error(-1, "查询失败");
			}
		} catch (Exception e) {
			error(e);
			return error(-1, "查询失败");
		}
	}

	/**
	 * 用药记录查询接口
	 * @param pagesize 分页大小
	 * @return
	 */
	@RequestMapping(value = "list_medication")
	@ResponseBody
	public String medication(String start,String end,int page, int pagesize) {
		try {
			Page<PatientHealthRecordMedication> data = patientHealthRecordService.findMedicalByPatientPage(getRepUID(), start, end, page, pagesize);
//			Page<PatientHealthRecordMedication> data = patientHealthRecordService.findMedicalByPatientPage(getUID(), start, end, page, pagesize);
			if (data != null) {
				JSONArray array = new JSONArray();
				for (PatientHealthRecordMedication record : data) {
					if (record == null) {
						continue;
					}
					JSONObject json = new JSONObject();
					json.put("id", record.getId());
					// 设置记录标识
					json.put("code", record.getCode());
					// 设置记录日期
					json.put("record_date", DateUtil.dateToStrShort(record.getRecordDate()));
					json.put("sortDate", DateUtil.dateToStrLong(record.getSortDate()));
					// 药品名称
					json.put("medicines", record.getMedicinesName());
					array.put(json);
				}
				return write(200, "查询成功", "list", array);
			} else {
				return error(-1, "查询失败");
			}
		} catch (Exception e) {
			error(e);
			return error(-1, "查询失败");
		}
	}

	/**
	 * 饮食记录查询接口
	 * @param pagesize 分页大小
	 * @return
	 */
	@RequestMapping(value = "list_diet")
	@ResponseBody
	public String diet(String start,String end,int page,int pagesize) {
		try {
			Page<PatientHealthRecordDiet> data = patientHealthRecordService.findDietByPatientPage(getRepUID(),start,end,page, pagesize);
//			Page<PatientHealthRecordDiet> data = patientHealthRecordService.findDietByPatientPage(getUID(),start,end,page, pagesize);
			if (data != null) {
				JSONArray array = new JSONArray();
				for (PatientHealthRecordDiet record : data) {
					if (record == null) {
						continue;
					}
					JSONObject json = new JSONObject();
					json.put("id", record.getId());
					// 设置记录标识
					json.put("code", record.getCode());
					// 设置记录日期
					json.put("record_date", DateUtil.dateToStrShort(record.getRecordDate()));
					json.put("sortDate", DateUtil.dateToStrLong(record.getSortDate()));
					// 设置饮食内容
					json.put("content", record.getContent());
					// 设置图片URL,多图以逗号分隔
					json.put("images", record.getImages());
					array.put(json);
				}
				return write(200, "查询成功", "list", array);
			} else {
				return error(-1, "查询失败");
			}
		} catch (Exception e) {
			error(e);
			return error(-1, "查询失败");
		}
	}

}
