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

import com.yihu.wlyy.entity.doctor.profile.Doctor;
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.common.account.DoctorService;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.StringUtils;
import org.htmlparser.Parser;
import org.htmlparser.util.ParserException;
import org.htmlparser.visitors.TextExtractingVisitor;
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.education.HealthEduArticlePatient;
import com.yihu.wlyy.service.app.health.HealthEduArticleService;
import com.yihu.wlyy.util.DateUtil;
import com.yihu.wlyy.web.BaseController;

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

/**
 * 患者端：健康教育控制类
 * @author George
 *
 */
@Controller
@RequestMapping(value = "/patient/health/edu", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "患者端-健康教育")
public class HealthEduArticleController extends BaseController {

	@Autowired
	private HealthEduArticlePatientService healthEduArticlePatientService;

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

	/**
	 * 查询文章列表
	 * @param pagesize 分页大小
	 * @return 列表
	 */
	@RequestMapping(value = "list")
	@ResponseBody
	public String list(@RequestParam("id")long id, @RequestParam("pagesize") int pagesize) {
		try {
			Page<HealthEduArticlePatient> list = healthEduArticlePatientService.findByPatient(getUID(), id, pagesize);
			JSONArray jsonArray = new JSONArray();
			Map<String,Doctor> docMap = new HashMap<>();
			if (list != null) {
				for (HealthEduArticlePatient article : list) {
					JSONObject json = new JSONObject();
					json.put("id", article.getId());
					// 文章标识
					json.put("article", article.getArticle());
					// 医生姓名
					json.put("doctorName", article.getDoctorName());
					// 文章标题
					json.put("title", article.getTitle());
					// 文章查看URL
					json.put("url", article.getUrl());
					// 文章简介
					json.put("content", parsrHtml(article.getContent()));
					// 是否已读：0已读，1未读
					json.put("read", article.getRead());
					// 添加日期
					json.put("czrq", DateUtil.dateToStrLong(article.getCzrq()));

					if(docMap.get(article.getDoctor())==null){
						Doctor doctor = doctorService.findDoctorByCode(article.getDoctor());
						docMap.put(article.getDoctor(),doctor);
						json.put("photo",doctor.getPhoto());
					}else{
						json.put("photo",docMap.get(article.getDoctor()).getPhoto());
					}
					//int collectionAmount =  healthEduArticleOpHistoryService.countCollectionAmount(article.getArticle());
					//int readAmount = healthEduArticleOpHistoryService.countReadAmount(article.getArticle());
					//int repeatAmount = healthEduArticleOpHistoryService.countRepeatAmount(article.getArticle());
					////阅读量
					//json.put("readAmount", readAmount);
					////收藏量
					//json.put("collectionAmount", collectionAmount);
					////转发量
					//json.put("repeatAmount", repeatAmount);
					jsonArray.put(json);
				}
			}
			return write(200, "查询成功", "list", jsonArray);
		} catch (Exception ex) {
			error(ex);
			return invalidUserException(ex, -1, "查询失败!");
		}
	}
	/**
	 * 查询文章列表
	 * @param article 数据文章唯一标示article
	 * @return 列表
	 */
	@RequestMapping(value = "article")
	@ResponseBody
	public String article(@RequestParam(value = "article",required = true) String article) {
		try {
			//获取单条文章记录
			List<HealthEduArticlePatient> healthEduArticlePatients = healthEduArticlePatientService.findByArticleAndPatient(article,getUID());
			if(healthEduArticlePatients==null||healthEduArticlePatients.size()==0){
				return error(-2,"对不起，该消息不是您的消息，您无法查看哦~");
			}
			int isRead  = healthEduArticleOpHistoryService.countByUserStatus(getUID(),HealthEduArticleOpHistory.READ_STATUS);
			//插入文章读取状态第一次阅读记录浏览数量//暂时更新每次都算一次浏览量
			HealthEduArticlePatient healthEduArticlePatient = healthEduArticlePatients.get(0);
			healthEduArticleOpHistoryService.saveByStatus(HealthEduArticleOpHistory.READ_STATUS,healthEduArticlePatient.getArticle(),healthEduArticlePatient.getTitle(),getUID());
			if(isRead==0){
				//将文章更新为已读
				healthEduArticlePatientService.updateRead(getUID(), healthEduArticlePatient.getArticle());
			}
			JSONObject json = new JSONObject();
			json.put("id", healthEduArticlePatient.getId());
			// 文章标识
			json.put("article", healthEduArticlePatient.getArticle());
			// 医生姓名
			json.put("doctorName", healthEduArticlePatient.getDoctorName());
			// 文章标题
			json.put("title", healthEduArticlePatient.getTitle());
			// 文章内容
			json.put("content", healthEduArticlePatient.getContent());

			json.put("url", healthEduArticlePatient.getUrl());
			// 添加日期
			json.put("czrq", DateUtil.dateToStrLong(healthEduArticlePatient.getCzrq()));
			int readAmount = healthEduArticleOpHistoryService.countReadAmount(healthEduArticlePatient.getArticle());
			json.put("readAmount",readAmount);
			return write(200, "查询成功", "data", json);
		} catch (Exception ex) {
			error(ex);
			return invalidUserException(ex, -1, "查询失败!");
		}
	}
	/**
	 * 更新文章为已读
	 * @param article 文章标识
	 * @return
	 */
	@RequestMapping(value = "read")
	@ResponseBody
	public String read(@RequestParam("article") String article) {
		try {
			healthEduArticlePatientService.updateRead(getUID(), article);
			return success("操作成功!");
		} catch (Exception ex) {
			error(ex);
			return invalidUserException(ex, -1, "操作失败!");
		}
	}

	private String parsrHtml(String html) throws ParserException {
		Parser parser = null;
		html = ("<span>"+html+"<span>");
		try{
			parser = new Parser(html);
		}catch (ParserException e){
			return html;//纯文本内容会转换失败，直接返回文本内容
		}
		TextExtractingVisitor visitor = new TextExtractingVisitor();
		parser.visitAllNodesWith(visitor);
		return StringUtils.isNotBlank(visitor.getExtractedText())?visitor.getExtractedText():"内容为图集，请点击查看";
	}
}
