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

import java.util.*;

import com.yihu.wlyy.entity.education.HealthEduArticleOpHistory;
import com.yihu.wlyy.service.app.health.HealthEduArticleOpHistoryService;
import com.yihu.wlyy.service.app.health.HealthEduArticlePatientService;
import com.yihu.wlyy.service.app.label.SignPatientLabelInfoService;
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 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", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "健康教育")
public class DoctorHealthEduArticleController extends BaseController {

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

	@Autowired
	private SignPatientLabelInfoService signPatientLabelInfoService;

	@Autowired
	private HealthEduArticlePatientService healthEduArticlePatientService;
	/**
	 * 查询
	 * @param pagesize 分页大小
	 * @return 列表
	 */
	@RequestMapping(value = "list")
	@ResponseBody
	public String list(@RequestParam(value = "page",required = true)int page, @RequestParam(value = "pagesize",required = true)int pagesize,@RequestParam(value = "filter",required = false)String filter) {
		try {
			Page<HealthEduArticle> list = healthEduArticleService.findAll(page, pagesize,filter);
			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()));
					int collectionAmount =  healthEduArticleOpHistoryService.countCollectionAmount(article.getCode());
					int readAmount = healthEduArticleOpHistoryService.countReadAmount(article.getCode());
					int repeatAmount = healthEduArticleOpHistoryService.countRepeatAmount(article.getCode());
					//阅读量
					json.put("readAmount", readAmount);
					//收藏量
					json.put("collectionAmount", collectionAmount);
					//转发量
					json.put("repeatAmount", repeatAmount);
					//是否收藏
					json.put("collection",1);

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

	/**
	 * 查询文章列表
	 * @param code 数据文章唯一标示code
	 * @return 列表
	 */
	@RequestMapping(value = "article")
	@ResponseBody
	public String article(@RequestParam(value = "code",required = true) String code) {
		try {
			//获取单条文章记录
			HealthEduArticle healthEduArticle = healthEduArticleService.findArticleByCode(code);
			int isRead  = healthEduArticleOpHistoryService.countByUserStatus(getUID(), HealthEduArticleOpHistory.READ_STATUS);
			//插入文章读取状态第一次阅读记录浏览数量
			if(isRead==0){
				//更新浏览量
				healthEduArticleOpHistoryService.saveByStatus(HealthEduArticleOpHistory.READ_STATUS,healthEduArticle.getCode(),healthEduArticle.getTitle(),getUID());
			}
			JSONObject json = new JSONObject();
			json.put("id", healthEduArticle.getId());
			// 文章标识
			json.put("code", healthEduArticle.getCode());
			// 文章标题
			json.put("title", healthEduArticle.getTitle());
			// 文章内容
			json.put("content", healthEduArticle.getContent());
			// 添加日期
			json.put("czrq", DateUtil.dateToStrLong(healthEduArticle.getCzrq()));
			int readAmount = healthEduArticleOpHistoryService.countReadAmount(code);
			json.put("readAmount",readAmount);
			json.put("collection",1);
			return write(200, "查询成功", "data", json);
		} catch (Exception ex) {
			error(ex);
			return invalidUserException(ex, -1, "查询失败!");
		}
	}


	/**
	 * 发送文章给患者
	 * @param code 文章标识，多个以逗号分隔
	 * @param patient 患者标识，多个以逗号分隔
	 * @param  group 所选群组，多个用逗号分隔
	 * @return
	 */
	@RequestMapping(value = "send")
	@ResponseBody
	public String send(@RequestParam(value = "code")String code,
					   @RequestParam(value = "patient",required = false)String patient,
					   @RequestParam(value = "group",required = false,defaultValue = "")String group,
					   @RequestParam(value = "labelType",required = false)String labelType,
					   @RequestParam(value = "labelCode",required = false)String labelCode,
					   @RequestParam(value = "teamCode",required = false)long teamCode) {
		try {
			List<HealthEduArticlePatient> list = new ArrayList<HealthEduArticlePatient>();
			if (StringUtils.isEmpty(code)) {
				return error(-1, "请至少选择一篇文章！");
			}
			if (StringUtils.isEmpty(patient)&&StringUtils.isEmpty(group)) {
				return error(-1, "请至少选择一个患者！");
			}
			String[] articles = code.split(",");
			String[] patients = patient.split(",");
			String[] groups = group.split(",");
			if (articles.length == 0) {
				return error(-1, "请至少选择一篇文章！");
			}
			if (patients.length == 0&&groups.length==0) {
				return error(-1, "请至少选择一个患者！");
			}
			Map<String, HealthEduArticle> maps = new HashMap<String, HealthEduArticle>();
			Set<String> patientSet = new HashSet<>();
			if(StringUtils.isNotBlank(group)&&groups.length>0){
				//递归患者数据
				getPatientByGroup(labelCode,labelType,teamCode,patientSet,1,100);
			}
			//去重操作
			for (String p : patients) {
				patientSet.add(p);
			}
			// 查询医生信息
			Doctor doctor = doctorService.findDoctorByCode(getUID());
			JSONArray messages = new JSONArray();
			for (String p : patientSet) {
				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, "发送失败！");
		}
	}
	private void getPatientByGroup(String labelCode, String labelType, Long teamCode,Set<String> patientSet,int page,int pagesize) throws Exception{
		JSONArray result = signPatientLabelInfoService.getPatientByLabel(getUID(), labelCode, labelType, teamCode, page, pagesize);
		for(Object o : result){
			JSONObject json  = (JSONObject)o;
			String patient  = (String)json.get("code");
			patientSet.add(patient);
		}
		if(result.length()==100){
			getPatientByGroup( labelCode,labelType,teamCode,patientSet,page+1,pagesize);
		}
	}

}
