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

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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.ResponseBody;

import com.yihu.wlyy.entity.doctor.profile.Doctor;
import com.yihu.wlyy.entity.education.HealthEduArticle;
import com.yihu.wlyy.entity.education.HealthEduArticlePatient;
import com.yihu.wlyy.service.app.health.HealthEduArticleService;
import com.yihu.wlyy.service.common.account.DoctorService;
import com.yihu.wlyy.task.PushMsgTask;
import com.yihu.wlyy.util.DateUtil;
import com.yihu.wlyy.util.MessageType;
import com.yihu.wlyy.web.BaseController;

/**
 * 医生端：健康教育控制类
 * @author George
 *
 */
@Controller
@RequestMapping(value = "/doctor/health/edu")
@Api(description = "健康教育")
public class DoctorHealthEduArticleController extends BaseController {

	@Autowired
	private HealthEduArticleService healthEduArticleService;
	@Autowired
	private DoctorService doctorService;

	/**
	 * 查询
	 * @param pagesize 分页大小
	 * @return 列表
	 */
	@RequestMapping(value = "list")
	@ResponseBody
	public String list(long id, int pagesize) {
		try {
			Page<HealthEduArticle> list = healthEduArticleService.findAll(id, pagesize);
			JSONArray jsonArray = new JSONArray();
			if (list != null) {
				for (HealthEduArticle article : list) {
					JSONObject json = new JSONObject();
					json.put("id", article.getId());
					// 文章标识
					json.put("code", article.getCode());
					// 文章标题
					json.put("title", article.getTitle());
					// 文章查看URL
					json.put("url", article.getUrl());
					// 文章简介
					json.put("content", article.getContent());
					// 添加日期
					json.put("czrq", DateUtil.dateToStrLong(article.getCzrq()));
					jsonArray.put(json);
				}
			}
			return write(200, "查询成功", "list", jsonArray);
		} catch (Exception ex) {
			error(ex);
			return invalidUserException(ex, -1, "查询失败!");
		}
	}

	/**
	 * 发送文章给患者
	 * @param article 文章标识，多个以逗号分隔
	 * @param patient 患者标识，多个以逗号分隔
	 * @return
	 */
	@RequestMapping(value = "send")
	@ResponseBody
	public String send(String article, String patient) {
		try {
			List<HealthEduArticlePatient> list = new ArrayList<HealthEduArticlePatient>();
			if (StringUtils.isEmpty(article)) {
				return error(-1, "请至少选择一篇文章！");
			}
			if (StringUtils.isEmpty(patient)) {
				return error(-1, "请至少选择一个患者！");
			}
			String[] articles = article.split(",");
			String[] patients = patient.split(",");
			if (articles.length == 0) {
				return error(-1, "请至少选择一篇文章！");
			}
			if (patients.length == 0) {
				return error(-1, "请至少选择一个患者！");
			}
			Map<String, HealthEduArticle> maps = new HashMap<String, HealthEduArticle>();
			// 查询医生信息
			Doctor doctor = doctorService.findDoctorByCode(getUID());
			JSONArray messages = new JSONArray();
			for (String p : patients) {
				for (String a : articles) {
					// 查询文章信息
					HealthEduArticle temp = maps.get(a);
					if (temp == null) {
						temp = healthEduArticleService.findArticleByCode(a);
						// 添加到缓存
						maps.put(a, temp);
					}
					HealthEduArticlePatient heap = new HealthEduArticlePatient();
					// 设置文章标识
					heap.setArticle(a);
					// 设置文章简介
					heap.setContent(temp.getContent());
					// 设置文章标题
					heap.setTitle(temp.getTitle());
					// 设置文章查看URL
					heap.setUrl(temp.getUrl());
					// 设置发送时间
					heap.setCzrq(new Date());
					// 设置医生标识
					heap.setDoctor(doctor.getCode());
					// 设置医生姓名
					heap.setDoctorName(doctor.getName());
					// 设置患者标识
					heap.setPatient(p);
					// 设置为示读
					heap.setRead(1);
					list.add(heap);
				}
				
				JSONObject message = new JSONObject();
				message.put("receiver", p);
				message.put("type", MessageType.MESSAGE_TYPE_PATIENT_HEALTH_EDU.P_HE_01.name());
				message.put("title", MessageType.MESSAGE_TYPE_PATIENT_HEALTH_EDU.健康教育.name());
				message.put("msg", MessageType.MESSAGE_TYPE_PATIENT_HEALTH_EDU.您有新的健康教育.name());
				messages.put(message);
			}
			// 保存到数据库
			int row = healthEduArticleService.send(list);
			if (row <= 0) {
				return error(-1, "发送失败！");
			} else {
				// 推送消息给患者
				PushMsgTask.getInstance().put(messages);
				return success("发送成功！");
			}
		} catch (Exception e) {
			error(e);
			return error(-1, "发送失败！");
		}
	}

}
