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

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.base.dao.article.KnowledgeArticleDictDao;
import com.yihu.jw.base.dao.article.KnowledgeCategoryDao;
import com.yihu.jw.entity.hospital.article.KnowledgeArticleDO;
import com.yihu.jw.entity.hospital.article.KnowledgeArticleDictDO;
import com.yihu.jw.entity.hospital.article.KnowledgeCategoryDO;
import com.yihu.jw.restmodel.web.MixEnvelop;
import com.yihu.jw.utils.hibernate.HibenateUtils;
import com.yihu.mysql.query.BaseJpaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.net.URLDecoder;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 健康文章分类
 * @author huangwenjie
 */
@Service
public class KnowledgeCategoryService extends BaseJpaService<KnowledgeCategoryDO, KnowledgeCategoryDao> {
	@Autowired
	private KnowledgeCategoryDao knowledgeCategoryDao;
	@Autowired
	private KnowledgeArticleDictDao articleDao;
	
	@Autowired
	private ObjectMapper objectMapper;
	@Autowired
	private HibenateUtils hibenateUtils;
	public KnowledgeCategoryDO saveCategory(String jsonData) throws Exception {
		jsonData = URLDecoder.decode(jsonData,"utf-8");
		KnowledgeCategoryDO knowledgeCategoryDO = objectMapper.readValue(jsonData, KnowledgeCategoryDO.class);
		if (null == knowledgeCategoryDO.getPid()) {
			knowledgeCategoryDO.setPid("0");
		}
		if (null == knowledgeCategoryDO.getId()) {
			// 新增
			knowledgeCategoryDO.setCreateTime(new Date());
			knowledgeCategoryDO.setDel(1);
		} else {
			KnowledgeCategoryDO one = knowledgeCategoryDao.findOne(knowledgeCategoryDO.getId());
			knowledgeCategoryDO.setId(one.getId());
			knowledgeCategoryDO.setDel(one.getDel());
			knowledgeCategoryDO.setUpdateTime(new Date());
		}
		return knowledgeCategoryDao.save(knowledgeCategoryDO);
	}
	
	@Transactional
	public Boolean updateDel(String code) {
		List<KnowledgeArticleDictDO> byCategory = articleDao.findByCategory(code);
		if (null != byCategory && byCategory.size() > 0) {
			return false;
		}
		knowledgeCategoryDao.updateDel(code);
		return true;
	}
	public MixEnvelop findAllGroup(){
		String sqlPid = "select id as \"id\",name as \"name\",pid as \"pid\" from wlyy_knowledge_category  where pid = '0' and del = 1";
		List<Map<String,Object>> list = hibenateUtils.createSQLQuery(sqlPid);
		String child = "select id as \"id\",name as \"name\",pid as \"pid\" from wlyy_knowledge_category  where del = 1";
		if (list.size()>0){
			for (Map<String,Object> map:list){
				String pid = map.get("id").toString();
				child+=" and pid = '"+pid+"'";
				List<Map<String,Object>> childList = hibenateUtils.createSQLQuery(child);
				map.put("childList",childList);
			}
		}
		MixEnvelop envelop = new MixEnvelop();
		envelop.setDetailModelList(list);
		return envelop;
	}
}
