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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.base.dao.article.KnowledgeArticleDictDao;
import com.yihu.jw.base.dao.article.KnowledgeArticleDeptDao;
import com.yihu.jw.base.dao.article.KnowledgeArticleMenuDao;
import com.yihu.jw.base.dao.article.KnowledgeArticleUserDao;
import com.yihu.jw.base.dao.menu.BaseMenuDictDao;
import com.yihu.jw.base.dao.user.UserDao;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.doctor.dao.BaseDoctorHospitalDao;
import com.yihu.jw.entity.base.doctor.BaseDoctorDO;
import com.yihu.jw.entity.base.doctor.BaseDoctorHospitalDO;
import com.yihu.jw.entity.base.menu.BaseMenuDictDO;
import com.yihu.jw.entity.base.patient.BasePatientBusinessDO;
import com.yihu.jw.entity.base.user.UserDO;
import com.yihu.jw.entity.hospital.article.KnowledgeArticleDO;
import com.yihu.jw.entity.hospital.article.KnowledgeArticleDeptDO;
import com.yihu.jw.entity.hospital.article.KnowledgeArticleDictDO;
import com.yihu.jw.entity.hospital.article.KnowledgeArticleUserDO;
import com.yihu.jw.entity.hospital.consult.WlyyHospitalSysDictDO;
import com.yihu.jw.entity.hospital.survey.WlyySurveyTemplateDO;
import com.yihu.jw.entity.hospital.survey.WlyySurveyUserDO;

import com.yihu.jw.hospital.dict.WlyyHospitalSysDictDao;
import com.yihu.jw.hospital.survey.dao.SurveyTemplateDao;
import com.yihu.jw.hospital.survey.dao.SurveyUserDao;
import com.yihu.jw.patient.dao.BasePatientBusinessDao;
import com.yihu.jw.restmodel.web.MixEnvelop;
import com.yihu.jw.utils.EntityUtils;
import com.yihu.jw.utils.hibernate.HibenateUtils;
import com.yihu.mysql.query.BaseJpaService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 健康文章业务层代码
 * @author huangwenjie
 * @date 2019/9/10 13:54
 */
@Service
public class KnowledgeArticleService extends BaseJpaService<KnowledgeArticleDictDO, KnowledgeArticleDictDao> {
	
	@Autowired
	private KnowledgeArticleDictDao knowledgeArticleDictDao;
	@Autowired
	private BaseMenuDictDao baseMenuDictDao;
	
	@Autowired
	private KnowledgeArticleDeptDao knowledgeArticleDeptDao;
	@Autowired
	private WlyyHospitalSysDictDao hospitalSysDictDao;
	@Autowired
	private BasePatientBusinessDao patientBusinessDao;
	@Autowired
	private KnowledgeArticleUserDao knowledgeArticleUserDao;
	@Autowired
	private BaseDoctorHospitalDao doctorHospitalDao;
	@Autowired
	private BaseDoctorDao doctorDao;
	@Autowired
	private SurveyUserDao surveyUserDao;
	@Autowired
	private SurveyTemplateDao surveyTemplateDao;
	@Autowired
    private HibenateUtils hibenateUtils;
	@Autowired
	private UserDao userDao;
	//查询文章列表
	public List<Map<String,Object>> findArticleList(String first,String second ,String key,Integer page ,Integer pageSize){
		String sql ="select b.id as \"id\", " +
				" b.title as \"title\"," +
				" b.intro as \"intro\"," +
				" b.category_first as \"categoryFirst\"," +
				" b.category_first_name as \"categoryFirstName\"," +
				" b.category_second as \"category_second\"," +
				" b.category_second_name as \"categorySecondName\"," +
				" b.create_user as \"createUser\"," +
				" b.status as \"status\"," +
				" b.used as \"used\"," +
				" b.create_user_name as \"createUserName\"," +
				" b.create_time as \"createTime\"," +
				" b.check_time as \"checkTime\"," +
				" b.release_status as \"releaseStatus\"," +
				" t.menu_id as \"menuId\"," +
				" t.parent_id as \"parentId\"," +
				" t.menu_name as \"menuName\"  " +
				" from wlyy_knowledge_article_menu t left join wlyy_knowledge_article b" +
				" on t.article_id=b.id left join base_menu_dict c " +
				" on c.id= t.menu_id where t.del=1";
		if (StringUtils.isNotBlank(first)){
			sql+=" and t.category_first ='"+first+"'";
		}
		if (StringUtils.isNotBlank(second)){
			sql+=" and t.category_second ='"+second+"'";
		}
		if (StringUtils.isNotBlank(key)){
			sql+=" and (t.title like '%"+first+"&' or t.intro like '%"+key+"%' or t.content like '%"+key+"%')";
		}
		List<Map<String,Object>> list = hibenateUtils.createSQLQuery(sql,page,pageSize);
		for (Map<String,Object> map:list){
			if (!"0".equalsIgnoreCase(map.get("parentId").toString())){
				BaseMenuDictDO baseMenuDictDO = baseMenuDictDao.findOne(map.get("parentId").toString());
				if (baseMenuDictDO!=null){
					map.put("parentName",baseMenuDictDO.getName());
				}
			}else {
				map.put("parentName",map.get("menuName").toString());
			}
		}
		return list;
	}
	
	/**
	 * 删除，支持批量
	 * @param id
	 */
	public boolean delArticle1(String id){
		String[] split = id.split(",|，");
		String ids = StringUtils.join(split, ",");
		String sql = "update wlyy_knowledge_article a set a.del = 0 where a.id in(" + ids + ")";
		String sqlUser = "update wlyy_knowledge_article_user a set a.del = 0 where a.relation_code in(" + ids + ")";
		String sqlBussiness = "update base_patient_business a set a.del = 0 where a.relation_code in(" + ids + ")";
		int update = jdbcTemplate.update(sql);
		int updateUser = jdbcTemplate.update(sqlUser);
		int updateBussiness  = jdbcTemplate.update(sqlBussiness);
		if (update > 0||updateUser>0||updateBussiness>0) {
			return true;
		}
		return false;
	}
	public boolean delArticle(String id){
		KnowledgeArticleDictDO knowledgeArticleDictDO = knowledgeArticleDictDao.findByIdAndDel(id);
		if (knowledgeArticleDictDO!=null){
			knowledgeArticleDictDO.setDel(0);
			knowledgeArticleDictDao.save(knowledgeArticleDictDO);
			return true;
		}
		return false;
	}
	/**
	 * 更新/保存健康文章
	 * @param jsonData
	 * @return
	 * @throws Exception
	 */
	public KnowledgeArticleDictDO saveArticle(String jsonData) throws  Exception {
		KnowledgeArticleDictDO knowledgeArticleDO = EntityUtils.jsonToEntity(jsonData, KnowledgeArticleDictDO.class);
		WlyyHospitalSysDictDO wlyyHospitalSysDictDO = hospitalSysDictDao.findById("articleNeedCheck");
		Boolean articleNeedCheck= true;
		if (wlyyHospitalSysDictDO!=null){
			if (!wlyyHospitalSysDictDO.getDictValue().equalsIgnoreCase("1")){
				articleNeedCheck=false;
			}
		}
		if (!StringUtils.isNotBlank(knowledgeArticleDO.getId()) ) {
			// 新增
			knowledgeArticleDO.setId(UUID.randomUUID().toString().replace("-", ""));
			knowledgeArticleDO.setCreateTime(new Date());
			knowledgeArticleDO.setStatus(0);
			knowledgeArticleDO.setReleaseStatus(0);
			knowledgeArticleDO.setDel(1);
			UserDO userDO = userDao.findById(knowledgeArticleDO.getCreateUser());
			if (userDO!=null){
				knowledgeArticleDO.setCreateUserName(userDO.getName());
			}
			if (!articleNeedCheck){
				knowledgeArticleDO.setStatus(1);
				knowledgeArticleDO.setReleaseStatus(1);
			}
			knowledgeArticleDO = knowledgeArticleDictDao.save(knowledgeArticleDO);
			return knowledgeArticleDO;
		} else {
			KnowledgeArticleDictDO one = knowledgeArticleDictDao.findOne(knowledgeArticleDO.getId());
			one.setTitle(knowledgeArticleDO.getTitle());
			one.setContent(knowledgeArticleDO.getContent());
			one.setImage(knowledgeArticleDO.getImage());
			one.setIntro(knowledgeArticleDO.getIntro());
			one.setUpdateTime(new Date());
			one.setCategoryFirst(knowledgeArticleDO.getCategoryFirst());
			one.setCategoryFirstName(knowledgeArticleDO.getCategoryFirstName());
			one.setCategorySecond(knowledgeArticleDO.getCategorySecond());
			one.setCategorySecondName(knowledgeArticleDO.getCategorySecondName());
			one.setReleaseTime(knowledgeArticleDO.getReleaseTime());
			one.setStatus(0);
			if (!articleNeedCheck){
				one.setStatus(1);
				one.setReleaseStatus(1);
			}
			knowledgeArticleDictDao.save(one);
			return  one;
		}
	}
	
	//审核/退回文章
	public KnowledgeArticleDictDO reviewArticle(String articleId,Integer status,String reason) throws Exception{

		KnowledgeArticleDictDO knowledgeArticleDO = knowledgeArticleDictDao.findOne(articleId);
		if (null == knowledgeArticleDO) {
			throw new Exception("该文章不存在");
		} else {
			knowledgeArticleDO.setStatus(status);
			knowledgeArticleDO.setCheckTime(new Date());
			if(StringUtils.isNotBlank(reason)){
				knowledgeArticleDO.setCancelReason(reason);
			}
			knowledgeArticleDictDao.save(knowledgeArticleDO);
			return  knowledgeArticleDO;
		}
	}
	
	/**
	 * 保存文章科室关系
	 * @param articleId
	 * @param sdJsons
	 * @return
	 * @throws Exception
	 */
	public Boolean saveArticleDept(String articleId,String sdJsons)throws Exception{
		
		//删除之前关系
		List<KnowledgeArticleDeptDO> list = knowledgeArticleDeptDao.findByArticleId(articleId);
		if(list!=null&&list.size()>0){
			knowledgeArticleDeptDao.delete(list);
		}
		
		if(org.apache.commons.lang3.StringUtils.isNotBlank(sdJsons)){
			List<KnowledgeArticleDeptDO> _list = EntityUtils.jsonToList(sdJsons,KnowledgeArticleDeptDO.class);
			if(_list!=null&&_list.size()>0){
				knowledgeArticleDeptDao.save(_list);
			}
		}
		return true;
	}
	
	/**
	 * 查询文章下科室
	 * @param articleId
	 * @return
	 */
	public List<Map<String,Object>> findDeptByArticle(String articleId)throws Exception{
		String sql ="SELECT " +
				" d.article_id AS articleId," +
				" d.dept, " +
				" d.dept_name AS deptName " +
				" FROM " +
				" wlyy_knowledge_article t " +
				" JOIN wlyy_knowledge_article_dept d ON t.id = d.article_id " +
				" WHERE " +
				" t.id = '"+articleId+"'";
		List<Map<String,Object>> list = jdbcTemplate.queryForList(sql);
		return list;
	}
	
	/**
	 * 查询部门下的文章
	 * @param dept
	 * @return
	 */
	public List<Map<String,Object>> findArticleByDept(String dept)throws Exception{
		String sql = "SELECT " +
				" t.id as \"id\", " +
				" t.title as \"title\", " +
				" t.create_time AS \"create_time\" ," +
				" t.image AS \"image\" " +
				" FROM " +
				" wlyy_knowledge_article t " +
				" JOIN wlyy_knowledge_article_dept d ON t.id = d.article_id " +
				" WHERE " +
				" d.dept = '"+dept+"'";
		List<Map<String,Object>> list = jdbcTemplate.queryForList(sql);
		return list;
	}
	
	/**
	 * 设置部门发送文章
	 * @param dept
	 * @param sdJsons
	 * @return
	 */
	public Boolean saveDeptArticle(String dept, String sdJsons) throws Exception{
		
		//删除之前关系
		List<KnowledgeArticleDeptDO> dels = knowledgeArticleDeptDao.findByDept(dept);
		if(dels!=null&&dels.size()>0){
			knowledgeArticleDeptDao.delete(dels);
		}
		
		if(org.apache.commons.lang3.StringUtils.isNotBlank(sdJsons)){
			List<KnowledgeArticleDeptDO> list = EntityUtils.jsonToList(sdJsons,KnowledgeArticleDeptDO.class);
			if(list!=null&&list.size()>0){
				knowledgeArticleDeptDao.save(list);
			}
		}
		return true;
	}
	public KnowledgeArticleDictDO releaseArticle(String articleId,Integer releaseStatus ){
		KnowledgeArticleDictDO knowledgeArticleDictDO = knowledgeArticleDictDao.findByIdAndDel(articleId);
		if (null!=knowledgeArticleDictDO){
			knowledgeArticleDictDO.setReleaseStatus(releaseStatus);
			knowledgeArticleDictDao.save(knowledgeArticleDictDO);
		}
		return knowledgeArticleDictDO;
	}
	/**
	 *	患者接收问卷/文章
	 * @param businessDOS
	 * @return
	 */
	public List<BasePatientBusinessDO> sendBusinessToPatient(List<BasePatientBusinessDO> businessDOS) throws Exception {
		if (businessDOS!=null&&businessDOS.size()!=0){
			for (BasePatientBusinessDO patientBusinessDO:businessDOS){
				BasePatientBusinessDO basePatientBusinessDO = patientBusinessDao.findByPatientAndRelationCodeAndDel(patientBusinessDO.getPatient(),patientBusinessDO.getRelationCode());
				if (basePatientBusinessDO != null) {
					throw new Exception("已发送过!");
				}
				patientBusinessDO.setCreateTime(new Date());
				patientBusinessDO.setUpdateTime(new Date());
				patientBusinessDO.setCreateUser(patientBusinessDO.getDoctor());
				patientBusinessDO.setUpdateUser(patientBusinessDO.getDoctor());
				patientBusinessDO.setCreateUserName(patientBusinessDO.getDoctorName());
				patientBusinessDO.setUpdateUserName(patientBusinessDO.getUpdateUserName());
				patientBusinessDO.setCollection(0);
				patientBusinessDO.setDel(1);
				patientBusinessDO = patientBusinessDao.save(patientBusinessDO);
					if (patientBusinessDO.getRelationType()==1){
						KnowledgeArticleDictDO knowledgeArticleDO = knowledgeArticleDictDao.findByIdAndDel(patientBusinessDO.getRelationCode());
					System.out.println("content:"+JSON.toJSONString(knowledgeArticleDO));
					JSONObject object = new JSONObject();
					object.put("id",knowledgeArticleDO.getId());
					object.put("title",knowledgeArticleDO.getTitle());
					object.put("content",knowledgeArticleDO.getIntro());
					object.put("img",knowledgeArticleDO.getImage());
				}else {
					WlyySurveyUserDO wlyySurveyUserDO = new WlyySurveyUserDO();
					String doctor = patientBusinessDO.getDoctor();
					BaseDoctorDO doctorDO = doctorDao.findById(doctor);
					wlyySurveyUserDO.setDept(doctorDO.getVisitDept());
					wlyySurveyUserDO.setDeptName(doctorDO.getVisitDeptName());
					wlyySurveyUserDO.setDoctor(doctor);
					wlyySurveyUserDO.setDoctorName(doctorDO.getName());
					wlyySurveyUserDO.setStatus(0);
					wlyySurveyUserDO.setPatient(patientBusinessDO.getPatient());
					wlyySurveyUserDO.setPatientName(patientBusinessDO.getPatientName());
					wlyySurveyUserDO.setSurveyTempCode(patientBusinessDO.getRelationCode());
					wlyySurveyUserDO.setSurveyTempTitle(patientBusinessDO.getRelationName());
					wlyySurveyUserDO.setCreateTime(new Date());
					wlyySurveyUserDO.setEndTime(new Date());
					wlyySurveyUserDO = surveyUserDao.save(wlyySurveyUserDO);
					JSONObject object = new JSONObject();
					WlyySurveyTemplateDO wlyySurveyTemplateDO = surveyTemplateDao.findOne(wlyySurveyUserDO.getSurveyTempCode());
					if (null!=wlyySurveyTemplateDO){
						object.put("title",wlyySurveyTemplateDO.getTitle());
						object.put("content",wlyySurveyTemplateDO.getTemplateComment());
						object.put("id",wlyySurveyTemplateDO.getId());
					}
				}

			}
		}
		return businessDOS;
	}


	/**
	 * 设置为1常用或者0不常用
	 * @param id
	 * @param used
	 * @return
	 */
	public KnowledgeArticleDictDO setUsed(String id,Integer used,String doctor){
		KnowledgeArticleDictDO knowledgeArticleDO = knowledgeArticleDictDao.findByIdAndDel(id);
		BaseDoctorDO doctorDO = doctorDao.findById(doctor);
		KnowledgeArticleUserDO knowledgeArticleUserDO =knowledgeArticleUserDao.findByrelationCodeAndUserAndDel(id,doctor);
		if (knowledgeArticleUserDO==null){
			knowledgeArticleUserDO = new KnowledgeArticleUserDO();
			knowledgeArticleUserDO.setRelationCode(id);
			knowledgeArticleUserDO.setRelationName(knowledgeArticleDO.getTitle());
			knowledgeArticleUserDO.setRelationType(1);
			knowledgeArticleUserDO.setDel(1);
			knowledgeArticleUserDO.setUser(doctor);
			if (doctorDO!=null){
				knowledgeArticleUserDO.setUserName(doctorDO.getName());
				knowledgeArticleUserDO.setCreateUserName(doctorDO.getName());
			}
			knowledgeArticleUserDO.setCreateTime(new Date());
			knowledgeArticleUserDO.setUpdateTime(new Date());
			knowledgeArticleUserDO.setCreateUser(doctor);
			knowledgeArticleUserDO.setUpdateUser(doctor);
			knowledgeArticleUserDO.setUsed(used);
			knowledgeArticleUserDO = knowledgeArticleUserDao.save(knowledgeArticleUserDO);
		}
        if (knowledgeArticleDO!=null){
            if (knowledgeArticleDO.getUsed()!=null){
            	if (used==1){
					knowledgeArticleUserDO.setUsed(1);
					knowledgeArticleDO.setUsed(knowledgeArticleDO.getUsed()+1);
				}else if (used==0){
            		knowledgeArticleUserDO.setUsed(0);
            		knowledgeArticleDO.setUsed(knowledgeArticleDO.getUsed()-1);
				}
			}else {
				if (used==1){
					knowledgeArticleDO.setUsed(1);
				}else if (used==0){
					knowledgeArticleDO.setUsed(0);
				}
			}
        }
		knowledgeArticleUserDO.setRelationName(knowledgeArticleDO.getTitle());
        knowledgeArticleUserDao.save(knowledgeArticleUserDO);
		return knowledgeArticleDictDao.save(knowledgeArticleDO);
	}


	public KnowledgeArticleDictDO selectById(String id){
		return knowledgeArticleDictDao.findByIdAndDel(id);
	}
	//根据分类查询文章
	public MixEnvelop findArticleByCategoryAndName(String categoryFirst, String categorySecond, String keyWords, Integer page, Integer pageSize){
		MixEnvelop objEnvelop = new MixEnvelop();
		String sql = "select t.id as \"id\",t.title as \"title\",t.read_count as \"readCount\"," +
				"t.collection as \"collection\",t.fabulous as \"fabulous\",t.is_share as \"share\"," +
                " t.intro as \"intro\",t.category_first_name as \"categoryFirstName\"," +
                " t.category_second_name as \"categorySecondName\" ," +
                "t.content as \"content\",t.image as \"image\",t.create_user_name as \"createUserName\",c.job_title_name as \"jobTitleName\"," +
                "b.dept_name as \"deptName\",b.org_name as \"hospitalName\"," +
				"t.create_time as \"createTime\" " +
				" from wlyy_knowledge_article t left join wlyy_knowledge_article_dept a " +
                " on a.article_id = t.id left join base_doctor_hospital b on b.doctor_code = t.create_user" +
				" left join base_doctor c on c.id = t.create_user where 1=1 and t.del = 1 and t.status = 1";
		if (StringUtils.isNotBlank(categoryFirst)){
		    sql+=" and t.category_first = '"+categoryFirst+"'";
        }
		if (StringUtils.isNotBlank(categorySecond)){
			sql+=" and t.category_second ='"+categorySecond+"'";
		}
        if (StringUtils.isNotBlank(keyWords)){
            sql+=" and (t.create_user_name like '%"+keyWords+"%' or t.title like '%"+keyWords+"%' or t.content like '%"+keyWords+"%' or a.dept_name like '%"+keyWords+"%' )";
        }
		sql+=" group by t.id ,t.title ,t.intro,t.category_first_name ,t.category_second_name ,c.job_title_name," +
				"t.read_count,t.collection,t.fabulous,t.is_share,t.content ,t.image ,t.create_user_name ,b.dept_name ,b.org_name,t.create_time " +
				" order by t.create_time desc";
        List<Map<String,Object>> result = hibenateUtils.createSQLQuery(sql,page,pageSize);
        List<Map<String,Object>> countList = hibenateUtils.createSQLQuery(sql);
        objEnvelop.setObj(result);
        objEnvelop.setTotalCount(countList.size());
        objEnvelop.setPageSize(pageSize);
        objEnvelop.setCurrPage(page);
        return objEnvelop;
	}

	//查询患者收藏的文章列表
	public JSONObject findPatientFavorite(String patient,Integer page,Integer pageSize){
		String sql = "select t.id as \"id\",t.user_code as \"user\",t.user_name as \"userName\"," +
				"t.relation_code as \"relationCode\"," +
				"t.relation_type as \"relationType\"," +
				"t.relation_name as \"relationName\"," +
				"t.is_read as \"isRead\",t.fabulous as \"fabulous\"," +
				"t.is_share as \"share\"," +
				"t.collection as \"collection\",t.used as \"used\",t.del as \"del\"";
		sql+=" from wlyy_knowledge_article_user t left join wlyy_knowledge_article a" +
				" on t.relation_code = a.id where 1=1 and a.del=1 and a.collection=1 ";
		if (StringUtils.isNotEmpty(patient)){
			sql+=" and t.user_code = '"+patient+"'";
		}
		List<Map<String,Object>> list = hibenateUtils.createSQLQuery(sql,page,pageSize);
		if(list!=null&&list.size()>0){
			for (Map<String,Object> map:list){
				String relationCode = map.get("relationCode").toString();
				String type =  map.get("relationType").toString();
				if ("1".equalsIgnoreCase(type)){
					KnowledgeArticleDictDO knowledgeArticleDO = this.selectById(relationCode);
					if (knowledgeArticleDO!=null){
						List<BaseDoctorHospitalDO> doctorHospitalDOS = doctorHospitalDao.findByDoctorCode(knowledgeArticleDO.getCreateUser());
						if (doctorHospitalDOS!=null&&doctorHospitalDOS.size()!=0){
							knowledgeArticleDO.setDeptName(doctorHospitalDOS.get(0).getDeptName());
							knowledgeArticleDO.setHospitalName(doctorHospitalDOS.get(0).getOrgName());
						}
					}
					map.put("KnowledgeArticleUserDO",knowledgeArticleDO);
				}
			}
		}
		List<Map<String,Object>> listCount = hibenateUtils.createSQLQuery(sql);
		JSONObject result = new JSONObject();
		result.put("total",listCount.size());
		result.put("detailModelList",list);
		return result;
	}
}
