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

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

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.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.wlyy.entity.doctor.profile.Doctor;
import com.yihu.wlyy.entity.follow.FollowUpItemRecordAnswer;
import com.yihu.wlyy.entity.follow.FollowUpPlanStage;
import com.yihu.wlyy.entity.follow.FollowUpPlanStageItem;
import com.yihu.wlyy.entity.follow.FollowUpPlanStageItemQuestion;
import com.yihu.wlyy.entity.follow.FollowUpPlanStageItemQuestionOption;
import com.yihu.wlyy.entity.follow.FollowUpSummary;
import com.yihu.wlyy.service.app.followup.FollowUpExecutionService;
import com.yihu.wlyy.service.common.account.DoctorService;
import com.yihu.wlyy.util.DateUtil;
import com.yihu.wlyy.web.BaseController;

/**
 * 医生端：随访干预
 * 
 * @author George
 *
 */
@Controller
@RequestMapping(value = "/doctor/followup")
@Api(description = "医生端-随访干预")
public class DoctorFollowUpController extends BaseController {

	@Autowired
	private FollowUpExecutionService executionService;
	@Autowired
	private DoctorService doctorService;

	/**
	 * 随访计划执行情况
	 * 
	 * @param planId String 计划标识
	 * @return
	 */
	@RequestMapping(value = "/plandetails")
	@ResponseBody
	public String getPlanDetails(String plan) {
		try {
			return write(200, "查询成功！", "data", executionService.getPlanDetails(plan));
		} catch (Exception e) {
			error(e);
			return error(-1, "查询失败！");
		}

	}

	/**
	 * 随访计划调查情况
	 * 
	 * @param item String 随访项标识
	 * @return
	 */
	@RequestMapping(value = "/investigation")
	@ResponseBody
	public String getItemInvestigation(String item) {
		try {
			return write(200, "查询成功！", "list", executionService.getItemInvestigation(item));
		} catch (Exception e) {
			error(e);
			return error(-1, "查询失败！");
		}
	}

	/**
	 * 随访项调查明细
	 * 
	 * @param item String 随访项标识
	 * @return
	 */
	@RequestMapping(value = "/inverstigationdetails")
	@ResponseBody
	public String getItemInverstigationDetails(String item) {
		try {
			return write(200, "查询成功！", "data", executionService.getItemInverstigationDetails(item));
		} catch (Exception e) {
			error(e);
			return error(-1, "查询失败！");
		}
	}

	/**
	 * 随访纪录作答详细
	 * 
	 * @param item String 随访项标识
	 * @param record String 随访项纪录标识
	 * @return
	 */
	@RequestMapping(value = "/itemanswersdetails")
	@ResponseBody
	public String getItemRecordAnswerDetails(String item, String record) {
		try {
			return write(200, "查询成功！", "data", executionService.getItemRecordAnswerDetails(item, record));
		} catch (Exception e) {
			error(e);
			return error(-1, "查询失败！");
		}
	}

	/**
	 * 随访项详细
	 * 
	 * @param item String 随访项标识
	 * @return
	 */
	@RequestMapping(value = "/itemdetails")
	@ResponseBody
	public String getItemDetails(String item) {
		try {
			return write(200, "查询成功！", "data", executionService.getItemDetails(item));
		} catch (Exception e) {
			error(e);
			return error(-1, "查询失败！");
		}
	}

	/**
	 * 随访项总结提交
	 * 
	 * @param summary String 随访总结JSON
	 * @return
	 */
	@RequestMapping(value = "/summarysubmit")
	@ResponseBody
	public String saveSummary(int type, int status, String summary) {
		String errMsg = "";

		try {
			ObjectMapper mapper = new ObjectMapper();
			FollowUpSummary summaryEntity = mapper.readValue(summary, FollowUpSummary.class);
			Doctor doctor = doctorService.findDoctorByCode(getUID());

			switch (type) {
			case 1:
				if (summaryEntity.getPlan().isEmpty()) {
					errMsg = "计划标识不能为空";
				}
				break;
			case 2:
				if (summaryEntity.getPlan().isEmpty()) {
					errMsg = "阶段标识不能为空";
				}
				break;
			case 3:
				if (summaryEntity.getPlan().isEmpty()) {
					errMsg = "随访项标识不能为空";
				}
				break;
			case 4:
				if (summaryEntity.getPlan().isEmpty()) {
					errMsg = "随访纪录标识不能为空";
				}
				break;
			default:
				break;
			}

			summaryEntity.setId((long) 0);
			summaryEntity.setCzrq(new Date());
			summaryEntity.setType(type);
			summaryEntity.setDoctor(doctor.getCode());
			summaryEntity.setDoctorName(doctor.getName());

			executionService.saveSummary(type, status, summaryEntity);

			return success("提交总结成功");
		} catch (Exception e) {
			error(e);
			return error(-1, "提交总结失败" + (errMsg.length() > 0 ? ("，" + errMsg) : "") + "！");
		}
	}

	/**
	 * 医生代答随访
	 * 
	 * @param answers 随访答案JSON
	 * @return
	 */
	@RequestMapping(value = "/doctoranswer")
	@ResponseBody
	public String saveRecordAnswers(String answers) {
		try {
			ObjectMapper mapper = new ObjectMapper();
			FollowUpItemRecordAnswer[] answerArray = mapper.readValue(answers, FollowUpItemRecordAnswer[].class);
			Doctor doctor = doctorService.findDoctorByCode(getUID());

			for (FollowUpItemRecordAnswer answer : answerArray) {
				answer.setCzrq(new Date());
				answer.setDoctor(doctor.getCode());
				answer.setDoctorName(doctor.getName());
			}

			executionService.saveRecordAnswers(Arrays.asList(answerArray));

			return success("提交成功！");
		} catch (Exception e) {
			error(e);
			return error(-1, "提交失败 ！");
		}
	}

	/**
	 * 随访频率变更
	 * 
	 * @param item String 随访项标识
	 * @param frequency String 频率信息
	 * @return
	 */
	@RequestMapping(value = "/itemfrequencychange")
	@ResponseBody
	public String changeItemFrequency(String item, String frequency) {
		try {
			JSONObject fJsonObject = new JSONObject(frequency);
			executionService.changeItemFrequency(item, fJsonObject);
			return success("提交成功！");
		} catch (Exception e) {
			error(e);
			return error(-1, "提交失败 ！");
		}
	}

	/**
	 * 随访计划编辑
	 * 
	 * @param stages
	 * @return
	 */
	@RequestMapping(value = "/planedit")
	@ResponseBody
	public String editPlan(String stages) {
		try {
			JSONArray stageArray = new JSONArray(stages);
			// 随访阶段列表
			List<FollowUpPlanStage> stageList = new ArrayList<FollowUpPlanStage>();
			// 随访项列表
			List<FollowUpPlanStageItem> stageItemList = new ArrayList<FollowUpPlanStageItem>();
			// 随访问题列表
			List<FollowUpPlanStageItemQuestion> questionList = new ArrayList<FollowUpPlanStageItemQuestion>();
			// 随访问题选项列表
			List<FollowUpPlanStageItemQuestionOption> optionList = new ArrayList<FollowUpPlanStageItemQuestionOption>();
			// 查询医生信息
			Doctor doctor = doctorService.findDoctorByCode(getUID());

			if (stageArray != null && stageArray.length() > 0) {
				for (int j = 0; j < stageArray.length(); j++) {
					JSONObject tempStage = stageArray.getJSONObject(j);
					// 新的随访阶段
					FollowUpPlanStage stage = new FollowUpPlanStage();
					// 设置阶段标识
					stage.setCode(tempStage.getString("code"));
					stage.setCzrq(new Date());
					// 设置医生标识
					stage.setDoctor(doctor.getCode());
					// 设置医生姓名
					stage.setDoctorName(doctor.getName());
					// 设置阶段结束日期
					stage.setEndDate(DateUtil.strToDateShort(tempStage.getString("endDate")));
					// 设置随访计划标识
					stage.setPlan(tempStage.getString("plan"));
					// 设置阶段序号
					stage.setSeq(tempStage.getInt("seq"));
					// 设置状态
					if (j == 0) {
						// 默认开始第一阶段
						stage.setStatus(1);
					} else {
						// 其他阶段未开始
						stage.setStatus(0);
					}
					// 设置阶段目标
					stage.setTarget(tempStage.getString("target"));
					// 设置类型：1定时，2不定时
					stage.setType(tempStage.getInt("type"));

					if (tempStage.getString("code").isEmpty()) {
						// 设置阶段标识
						stage.setCode(executionService.getCode());
						// 添加到阶段列表
						stageList.add(stage);
					}

					// ====================================随访项======================================
					JSONArray stageItemArray = tempStage.getJSONArray("items");
					if (stageItemArray != null && stageItemArray.length() > 0) {
						for (int k = 0; k < stageItemArray.length(); k++) {
							JSONObject tempItem = stageItemArray.getJSONObject(k);
							// 新的随访项
							FollowUpPlanStageItem item = new FollowUpPlanStageItem();
							// 设置随访项标识
							item.setCode(executionService.getCode());
							item.setCzrq(new Date());
							// 设置随访计划标识
							item.setPlan(tempStage.getString("plan"));
							// 设置推送类型：1按时间，2按次数
							item.setPushType(tempItem.getInt("pushType"));
							// 设置推送周期
							item.setPushCycle(tempItem.getInt("pushCycle"));
							// 设置推送开始时间
							item.setPushBegin(DateUtil.strToDateShort(tempItem.getString("pushBegin")));
							// 设置推送周期单位：1天，2周，3月
							item.setPushCycleUnit(tempItem.getInt("pushCycleUnit"));
							if (item.getPushType() == 1) {
								// 设置推送结束日期
								item.setPushEnd(DateUtil.strToDateShort(tempItem.getString("pushEnd")));
							} else if (item.getPushType() == 2) {
								// 设置推送次数
								item.setPushTimes(tempItem.getInt("pushTimes"));
							}
							// 设置阶段标识
							item.setStage(stage.getCode());
							// 设置执行状态：-1暂停，0未开始，1进行中，2已结束
							if (item.getCzrq().before(item.getPushBegin())) {
								// 推送时间未到，未开始
								item.setStatus(0);
							} else {
								// 已到推送时间，正在进行
								item.setStatus(1);
							}
							// 设置随访项标题
							item.setTitle(tempItem.getString("title"));
							// 设置随访项类型：1问卷，2体测
							item.setType(tempItem.getInt("type"));
							// 添加随访项列表
							stageItemList.add(item);
							// ==========================================随访问题=========================================
							JSONArray questionArray = tempItem.getJSONArray("questions");
							if (questionArray != null && questionArray.length() > 0) {
								for (int l = 0; l < questionArray.length(); l++) {
									JSONObject tempQuestion = questionArray.getJSONObject(l);
									// 新的随访问题
									FollowUpPlanStageItemQuestion question = new FollowUpPlanStageItemQuestion();
									// 设置问题标识
									question.setCode(executionService.getCode());
									if (item.getType() == 2) {
										// 体测随访，设置体测指标类型：1血糖，2血压，3体重，4腰围
										question.setIndex(tempQuestion.getInt("index"));
									}
									// 设置随访标识
									question.setItem(item.getCode());
									// 设置随访计划标识
									question.setPlan(tempStage.getString("plan"));
									// 设置随访计划阶段标识
									question.setStage(stage.getCode());
									// 设置问题标题
									question.setTitle(tempQuestion.getString("title"));
									// 设置问题类型：1单选，2多选，3问答
									if (item.getType() == 1) {
										// 问卷随访
										question.setType(tempQuestion.getInt("type"));
									} else {
										// 体测随访，只有问答
										question.setType(3);
									}
									// 添加问题列表
									questionList.add(question);
									// ====================================问题选项========================================
									JSONArray optionArray = tempQuestion.getJSONArray("options");
									if (optionArray != null && optionArray.length() > 0) {
										JSONArray tempArray = new JSONArray();
										for (int u = 0; u < optionArray.length(); u++) {
											String des = optionArray.getJSONObject(u).getString("des");
											if (StringUtils.isEmpty(des)) {
												continue;
											}
											// 新的问题选项
											FollowUpPlanStageItemQuestionOption option = new FollowUpPlanStageItemQuestionOption();
											// 设置选项标识
											option.setCode(executionService.getCode());
											// 设置选项描述
											option.setDes(des);
											// 设置随访项标识
											option.setItem(item.getCode());
											// 设置随访计划标识
											option.setPlan(tempStage.getString("plan"));
											// 设置问题标识
											option.setQuestion(question.getCode());
											// 设置阶段标识
											option.setStage(stage.getCode());
											// 添加到选项列表
											optionList.add(option);

											JSONObject tempJson = new JSONObject();
											tempJson.put("code", option.getCode());
											tempJson.put("des", option.getDes());
											tempArray.put(tempJson);
										}
									}
								}
							}
						}
					}
				}
			}
			// 保存到数据库
			executionService.editPlan(stageList, stageItemList, questionList, optionList);
			return success("提交成功！");
		} catch (Exception e) {
			error(e);
			return error(-1, "提交失败 ！");
		}
	}

	/**
	 * 总结获取
	 * 
	 * @param type
	 * @param summary
	 * @return
	 */
	@RequestMapping(value = "/summary")
	@ResponseBody
	public String getSummary(int type, String summary) {
		try {
			return write(200, "查询成功！", "data", executionService.getSummary(type, summary));
		} catch (Exception e) {
			error(e);
			return error(-1, "查询失败！");
		}
	}

	/**
	 * 阶段周期编辑
	 *  
	 * @param stage String 阶段标识
	 * @param frequency 周期JSON
	 * @return
	 */
	@RequestMapping(value = "/stageedit")
	@ResponseBody
	public String editStage(String stage, String frequency) {
		try {
			JSONObject fJsonObject = new JSONObject(frequency);
			executionService.editStage(stage, fJsonObject);
			return success("提交成功！");
		} catch (Exception e) {
			error(e);
			return error(-1, "提交失败 ！");
		}
	}

	/**
	 * 
	 * 
	 * @param type
	 * @param status
	 * @param identity
	 * @return
	 */
	@RequestMapping(value = "/statuschange")
	@ResponseBody
	public String setStatus(int type, int status, String identity) {
		try {
			if (type == 1) {
				executionService.setPlanStatus(status, identity);
			} else if (type == 2) {
				executionService.setStageStatus(status, identity);
			} else {
				executionService.setItemStatus(status, identity);
			}

			return success("设置成功！");
		} catch (Exception e) {
			error(e);
			return error(-1, "设置失败 ！");
		}
	}
}
