package com.yihu.jw.base.endpoint.article;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.base.dao.article.KnowledgeArticleDictDao;
import com.yihu.jw.base.dao.article.KnowledgeArticleUserDao;
import com.yihu.jw.base.dao.role.RoleDao;
import com.yihu.jw.base.dao.user.UserDao;
import com.yihu.jw.base.service.article.KnowledgeArticleService;
import com.yihu.jw.base.service.article.KnowledgeArticleUserService;
import com.yihu.jw.base.service.article.KnowledgeCategoryService;
import com.yihu.jw.doctor.dao.BaseDoctorHospitalDao;
import com.yihu.jw.entity.base.doctor.BaseDoctorHospitalDO;
import com.yihu.jw.entity.base.patient.BasePatientBusinessDO;
import com.yihu.jw.entity.base.role.RoleDO;
import com.yihu.jw.entity.base.user.UserDO;
import com.yihu.jw.entity.hospital.article.KnowledgeArticleDO;
import com.yihu.jw.entity.hospital.article.KnowledgeArticleDictDO;
import com.yihu.jw.entity.hospital.article.KnowledgeArticleUserDO;
import com.yihu.jw.entity.hospital.article.KnowledgeCategoryDO;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.ListEnvelop;
import com.yihu.jw.restmodel.web.MixEnvelop;
import com.yihu.jw.restmodel.web.ObjEnvelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.rm.hospital.BaseHospitalRequestMapping;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * 健康文章
 * @author huangwenjie
 */
@RestController
@RequestMapping(value = BaseHospitalRequestMapping.KnowledgeArticle.PREFIX)
@Api(value = "文章管理接口", description = "文章管理接口", tags = {"文章管理接口"})
public class ArticleEndpoint extends EnvelopRestEndpoint {
	
	@Autowired
	private KnowledgeArticleService knowledgeArticleService;
	
	@Autowired
	private KnowledgeCategoryService knowledgeCategoryService;

	@Autowired
	private BaseDoctorHospitalDao doctorHospitalDao;
	@Autowired
	private KnowledgeArticleUserService knowledgeArticleUserService;
	@Autowired
	private KnowledgeArticleUserDao knowledgeArticleUserDao;
	@Autowired
	private KnowledgeArticleDictDao knowledgeArticleDictDao;
	@Autowired
	private UserDao userdao;
	@Autowired
	private RoleDao roleDao;
	
	@GetMapping(value = BaseHospitalRequestMapping.KnowledgeArticle.searchKnowledgePageList)
	@ApiOperation(value = "获取文章列表")
	public Envelop searchKnowledgePageList(
//			@ApiParam(name = "category_first", value = "1级分类编码")
//			@RequestParam(value = "category_first", required = false) String category_first,
//			@ApiParam(name = "category_secend", value = "2级分类编码")
//			@RequestParam(value = "category_second", required = false) String category_second,
//			@ApiParam(name = "keyword", value = "关键字")
//			@RequestParam(value = "keyword", required = false) String keyword,
//			@ApiParam(name = "status", value = "审核状态：0未审核，1已审核")
//			@RequestParam(value = "status", required = false) String status,
//			@ApiParam(name = "start", value = "开始时间")
//			@RequestParam(value = "start", required = false) String start,
//			@ApiParam(name = "end", value = "结束时间")
//			@RequestParam(value = "end", required = false) String end,
			@ApiParam(name = "fields", value = "返回的字段，为空返回全部字段")
			@RequestParam(value = "fields", required = false) String fields,
			@ApiParam(name = "filters", value = "过滤器，为空检索所有条件")
			@RequestParam(value = "filters", required = false) String filters,
			@ApiParam(name = "sorts", value = "排序，规则参见说明文档")
			@RequestParam(value = "sorts", required = false) String sorts,
			@ApiParam(name = "page", value = "第几页，从1开始", required = true, defaultValue = "1")
			@RequestParam(value = "page", required = true,defaultValue = "1")Integer page,
			@ApiParam(name = "pageSize", value = "每页分页大小", required = true, defaultValue = "10")
			@RequestParam(value = "pageSize", required = true,defaultValue = "10")Integer pageSize)throws Exception{

		try {
			String userId=getUID();
			UserDO userDO = userdao.findById(userId);
			boolean queryAll=false;
			if (userDO!=null){
				RoleDO roleDO= roleDao.findOne(userDO.getRoleId());
				if (roleDO!=null){
					if ("admin".equalsIgnoreCase(roleDO.getCode())){
						queryAll=true;
					}
				}
			}
			if (queryAll){
				if(StringUtils.isBlank(filters)){
					filters=filters+"del=1";
				}else{
					filters=filters+";del=1";
				}
			}else {
				if(StringUtils.isBlank(filters)){
					filters=filters+"del=1"+";createUser="+userId+"";
				}else{
					filters=filters+";del=1"+";createUser="+userId+"";
				}
			}
			List<KnowledgeArticleDictDO> list  = knowledgeArticleService.search(fields,filters,sorts,page,pageSize);
			List<KnowledgeArticleDictDO> totals  = knowledgeArticleService.search(fields,filters,sorts);

			JSONObject result = new JSONObject();
			result.put("total",totals.size());
			result.put("detailModelList",list);

			return success(result);
		}catch (Exception e){
			return failedException(e);
		}
	}
	@GetMapping(value = BaseHospitalRequestMapping.KnowledgeArticle.searchKnowledgeList)
	@ApiOperation(value = "获取文章列表")
	public Envelop searchKnowledgeList(
			@ApiParam(name = "first", value = "second")
			@RequestParam(value = "first", required = false) String first,
			@ApiParam(name = "second", value = "second")
			@RequestParam(value = "second", required = false) String second,
			@ApiParam(name = "key", value = "关键字")
			@RequestParam(value = "key", required = false) String key,
			@ApiParam(name = "page", value = "第几页，从1开始", required = true, defaultValue = "1")
			@RequestParam(value = "page", required = true,defaultValue = "1")Integer page,
			@ApiParam(name = "pageSize", value = "每页分页大小", required = true, defaultValue = "10")
			@RequestParam(value = "pageSize", required = true,defaultValue = "10")Integer pageSize)throws Exception{

		try {
			return success(knowledgeArticleService.findArticleList(first,second,key,page,pageSize));
		}catch (Exception e){
			return failedException(e);
		}
	}
	@GetMapping(value = BaseHospitalRequestMapping.KnowledgeArticle.queryById)
	@ApiOperation(value = "根据id查询文章")
	public Envelop queryByCode(
			@ApiParam(name = "id", value = "id", required = true)
			@RequestParam(value = "id", required = true)String id) throws Exception{
		try {
			KnowledgeArticleDictDO articleDO = knowledgeArticleService.retrieve(id);
			return success(articleDO);
		}catch (Exception e){
			return failedException(e);
		}
	}
	
	@PostMapping (value = BaseHospitalRequestMapping.KnowledgeArticle.deleteById)
	@ApiOperation(value = "根据id删除文章")
	public Envelop deleteById(
			@ApiParam(name = "id", value = "id，多个使用英文逗号分隔", required = true)
			@RequestParam(value = "id", required = true)String id)throws Exception {
			try {
				knowledgeArticleService.delArticle(id);
				return success("操作成功");
			}catch (Exception e){
				return failedException(e);
			}
	}
	
	@PostMapping (value = BaseHospitalRequestMapping.KnowledgeArticle.saveArticle)
	@ApiOperation(value = "保存/更新文章")
	public Envelop saveArticle(
			@ApiParam(name = "jsonData", value = "Json数据", required = true)
			@RequestParam String jsonData)throws Exception {

		try {
			knowledgeArticleService.saveArticle(jsonData);
			return success("操作成功");
		}catch (Exception e){
			return failedException(e);
		}
	}
	
	@PostMapping (value = BaseHospitalRequestMapping.KnowledgeArticle.reviewArticle)
	@ApiOperation(value = "审核/退回文章")
	public Envelop saveArticle(
			@ApiParam(name = "articleId", value = "文章ID")
			@RequestParam(value = "articleId", required = true) String articleId,
			@ApiParam(name = "status", value = "0未审核，1已审核，2退回")
			@RequestParam(value = "status", required = true) Integer status,
			@ApiParam(name = "reason", value = "退回理由")
			@RequestParam(value = "reason", required = false) String reason
	)throws Exception {
		try {
			knowledgeArticleService.reviewArticle(articleId,status,reason);
			return success("操作成功");
		}catch (Exception e){
			return failedException(e);
		}
	}
	
	
	@GetMapping(value = BaseHospitalRequestMapping.KnowledgeArticle.searchCategoryList)
	@ApiOperation(value = "获取分类列表")
	public ListEnvelop searchCategoryList(
			@ApiParam(name = "fields", value = "返回的字段，为空返回全部字段")
			@RequestParam(value = "fields", required = false) String fields,
			@ApiParam(name = "filters", value = "过滤器，为空检索所有条件")
			@RequestParam(value = "filters", required = false) String filters,
			@ApiParam(name = "sorts", value = "排序，规则参见说明文档")
			@RequestParam(value = "sorts", required = false) String sorts,
			@ApiParam(name = "page", value = "第几页，从1开始", required = true, defaultValue = "1")
			@RequestParam(value = "page", required = true,defaultValue = "1")Integer page,
			@ApiParam(name = "pageSize", value = "每页分页大小", required = true, defaultValue = "10")
			@RequestParam(value = "pageSize", required = true,defaultValue = "10")Integer pageSize)throws Exception{

		try {
			List<KnowledgeCategoryDO> list  = knowledgeCategoryService.search(fields,filters,sorts,page,pageSize);
			List<KnowledgeCategoryDO> result = new ArrayList<>();
			for(KnowledgeCategoryDO knowledgeCategoryDO:list){
				if(knowledgeCategoryDO.getDel() == 1){
					result.add(knowledgeCategoryDO);
				}
			}
			return success(result);
		}catch (Exception e){
			return failedListEnvelopException(e);
		}
	}
	
	@PostMapping (value = BaseHospitalRequestMapping.KnowledgeArticle.saveCategory)
	@ApiOperation(value = "保存/更新分类")
	public Envelop saveCategory(
			@ApiParam(name = "jsonData", value = "Json数据", required = true)
			@RequestParam String jsonData)throws Exception {

		try {
			knowledgeCategoryService.saveCategory(jsonData);
			return success("操作成功");
		} catch (Exception e){
			return failedException(e);
		}
	}
	
	@PostMapping (value = BaseHospitalRequestMapping.KnowledgeArticle.updateDel)
	@ApiOperation(value = "根据分类code删除分类")
	public Envelop updateDel(
			@ApiParam(name = "id", value = "id", required = true)
			@RequestParam(value = "id", required = true)String id)throws Exception {

		try {
			Boolean flag = knowledgeCategoryService.updateDel(id);
			if (flag) {
				return success("操作成功");
			}else{
				return failed("操作失败");
			}
		}catch (Exception e){
			return failedException(e);
		}
		
	}

	@PostMapping(value = BaseHospitalRequestMapping.KnowledgeArticle.saveArticleDept)
	@ApiOperation(value = "设置文章发送的科室")
	public ObjEnvelop saveArticleDept(@ApiParam(name = "articleId", value = "文章ID")
	                                 @RequestParam(value = "articleId",required = true)String articleId,
	                                 @ApiParam(name = "sdJsons", value = "部门与科室关系json")
	                                 @RequestParam(value = "sdJsons",required = true)String sdJsons)throws Exception {
		try {
			return success(knowledgeArticleService.saveArticleDept(articleId,sdJsons));
		}catch (Exception e){
			return failedObjEnvelopException(e);
		}
	}
	
	@GetMapping(value = BaseHospitalRequestMapping.KnowledgeArticle.findDeptByArticle)
	@ApiOperation(value = "查询文章下的科室")
	public ListEnvelop findDeptByArticle(@ApiParam(name = "articleId", value = "文章ID")
	                                    @RequestParam(value = "articleId",required = true)String articleId)throws Exception {
		try {
			return success(knowledgeArticleService.findDeptByArticle(articleId));

		}catch (Exception e){
			return failedListEnvelopException(e);
		}
	}
	
	@GetMapping(value = BaseHospitalRequestMapping.KnowledgeArticle.findArticleByDept)
	@ApiOperation(value = "查询部门下发放的文章")
	public ListEnvelop findArticleByDept(@ApiParam(name = "dept", value = "科室")
	                                    @RequestParam(value = "dept",required = true)String dept)throws Exception {
		try {
			return success(knowledgeArticleService.findArticleByDept(dept));
		}catch (Exception e){
			return failedListEnvelopException(e);
		}
	}
	
	@PostMapping(value = BaseHospitalRequestMapping.KnowledgeArticle.saveDeptArticle)
	@ApiOperation(value = "设置科室发送的文章")
	public ObjEnvelop saveDeptArticle(@ApiParam(name = "dept", value = "部门code")
	                                 @RequestParam(value = "dept",required = true)String dept,
	                                 @ApiParam(name = "sdJsons", value = "部门与科室关系json")
	                                 @RequestParam(value = "sdJsons",required = false)String sdJsons)throws Exception {

		try {
			return success(knowledgeArticleService.saveDeptArticle(dept,sdJsons));
		}catch (Exception e){
			return failedObjEnvelopException(e);
		}
	}


	@PostMapping(value = BaseHospitalRequestMapping.KnowledgeArticle.sendPatientBusiness)
	@ApiOperation(value = "发送文章/问卷")
	public ListEnvelop sendPatientBusiness(@ApiParam(name = "json", value = "患者业务关联表")
									  @RequestParam(value = "json",required = false)String json)throws Exception {

		try {
			ListEnvelop listEnvelop = new ListEnvelop();
			JSONArray jsonArray = JSONArray.parseArray(json);
			List<BasePatientBusinessDO> patientBusinessDOList = new ArrayList<>();
			for (int i=0;i<jsonArray.size();i++){
				JSONObject jsonObject = jsonArray.getJSONObject(i);
				BasePatientBusinessDO patientBusinessDO = toEntity(jsonObject.toJSONString(),BasePatientBusinessDO.class);
				patientBusinessDOList.add(patientBusinessDO);
			}
			listEnvelop.setDetailModelList(knowledgeArticleService.sendBusinessToPatient(patientBusinessDOList));
			return  listEnvelop;
		}catch (Exception e){
			return failedListEnvelopException(e);
		}
	}

	@PostMapping(value = BaseHospitalRequestMapping.KnowledgeArticle.setArticleUsed)
	@ApiOperation(value = "发布文章")
	public ObjEnvelop setArticleUsed(@ApiParam(name = "id", value = "文章id")
									  @RequestParam(value = "id",required = true)String id,
									  @ApiParam(name = "status", value = "1发布0未发布")
									  @RequestParam(value = "status",required = false)Integer status)throws Exception {
		try {
			return success(knowledgeArticleService.releaseArticle(id,status));
		}catch (Exception e){
			return failedObjEnvelopException(e);
		}
}

	@PostMapping(value = BaseHospitalRequestMapping.KnowledgeArticle.findArticleByCategoryAndName)
	@ApiOperation(value = "查询文章")
	public MixEnvelop findArticleByCategoryAndName(@ApiParam(name = "categoryFirst", value = "一级分类code")
										   @RequestParam(value = "categoryFirst",required = false)String categoryFirst,
												   @ApiParam(name = "categorySecond", value = "二级分类code")
										   @RequestParam(value = "categorySecond",required = false)String categorySecond,
												   @ApiParam(name = "keyWords", value = "关键词")
										   @RequestParam(value = "keyWords",required = false)String keyWords,
												   @ApiParam(name = "page", value = "当前页")
										   @RequestParam(value = "page",required = false)Integer page,
												   @ApiParam(name = "pageSize", value = "分页大小）")
										   @RequestParam(value = "pageSize",required = false)Integer pageSize)throws Exception {

		MixEnvelop mixEnvelop=knowledgeArticleService.findArticleByCategoryAndName(categoryFirst,categorySecond,keyWords,page,pageSize);
		return mixEnvelop;
	}
	@GetMapping(value = BaseHospitalRequestMapping.KnowledgeArticle.getArticleGroup)
	@ApiOperation(value = "查询分类")
	public MixEnvelop getGroup(){
		try {
			MixEnvelop envelop = knowledgeCategoryService.findAllGroup();
			return envelop;
		}catch (Exception e){
			return failedMixEnvelopException(e);
		}

	}


	@PostMapping(value = BaseHospitalRequestMapping.KnowledgeArticle.findPatientFavorite)
	@ApiOperation(value = "查询收藏文章")
	public Envelop findPatientFavorite(@ApiParam(name = "patient", value = "病人id")
												   @RequestParam(value = "patient",required = false)String patient,
												   @ApiParam(name = "page", value = "当前页")
												   @RequestParam(value = "page",required = false)Integer page,
												   @ApiParam(name = "pageSize", value = "分页大小）")
												   @RequestParam(value = "pageSize",required = false)Integer pageSize)throws Exception {

		try {
			return success(knowledgeArticleService.findPatientFavorite(patient,page,pageSize));
		}catch (Exception e){
			return failedException(e);
		}
	}
}
