package com.nbclass.activity.service.impl;

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

import javax.annotation.Resource;
import javax.transaction.Transactional;

import com.nbclass.activity.mapper.WXMapper;
import com.nbclass.activity.model.*;
import com.nbclass.activity.service.WxService;
import com.nbclass.system.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.nbclass.activity.mapper.ContentMapper;
import com.nbclass.activity.mapper.DataDictMapper;
import com.nbclass.activity.model.enums.ContentType;
import com.nbclass.activity.service.ContentService;
import com.nbclass.activity.service.ElasticSearchService;
import com.nbclass.exception.ParameterException;
import com.nbclass.util.CommonUtils;

/**
 *
 * @author Leon
 * @datetime 2020年5月28日 下午4:42:45
 */
@Service
public class ContentServiceImpl implements ContentService {

	@Resource
	private ContentMapper mapper;

	@Resource
	private DataDictMapper dataDictMapper;

	@Resource
	private ElasticSearchService esService;

	@Resource
	private DataDictMapper dataDictMapper2;

	@Resource
	private WXMapper wxMapper;


	private void baseSaveVerify(Content entity) {
		/*if(StringUtils.isBlank(entity.getType())) {
			throw new ParameterException("案例类型不能为空");
		}*/
		if(StringUtils.isBlank(entity.getTitle())) {
			throw new ParameterException("标题不能为空");
		}
		/*if(entity.getFromid() == null || entity.getFromid() < 1) {
			throw new ParameterException("案例来源不能为空");
		}*/
		if(StringUtils.isBlank(entity.getDesct())) {
			throw new ParameterException("描述不能为空");
		}
		if(StringUtils.isBlank(entity.getListicon())) {
			throw new ParameterException("封面图不能为空");
		}

		// 链接形式的案例
		if(ContentType.h5.key().equals(entity.getType()) || ContentType.video.key().equals(entity.getType())) {
			if(StringUtils.isBlank(entity.getUrl())) {
				throw new ParameterException("URL不能为空");
			}
		}

		// 富文本编辑的案例
		// 0527开发群确认的，记录关键词“都是富文本”
		if(ContentType.design.key().equals(entity.getType())
				|| ContentType.ppqa.key().equals(entity.getType())
				|| ContentType.ggqa.key().equals(entity.getType())
				|| ContentType.ldhd.key().equals(entity.getType())
				|| ContentType.others.key().equals(entity.getType())) {
			if(StringUtils.isBlank(entity.getContent())) {
				throw new ParameterException("内容不能为空");
			}
		}

		if(StringUtils.isBlank(entity.getAttachment()))entity.setAttachment(null); // 空字符串导致MySQL存储json类型异常
	}

//	// 修改案例标签和图集
//	private void updateLabelAndImages(Content o){
//		long cid = o.getId();
//		List<ContentTags> newTagList = new ArrayList<ContentTags>();
//		if(StringUtils.isNotBlank(o.getTags())){
//			ArrayList<String> postTagList = CommonUtils.str2List(o.getTags());
//			// 查询出 dictid
//			DataDict dataDict = new DataDict();
//			dataDict.setDatakey("tag_"+o.getType());
//			dataDict = dataDictMapper.selectOne(dataDict);
//
//
//			List<DataDictItem> taglist = dataDictMapper.getItemsByNames("tag_"+o.getType(), postTagList);
//			HashMap<String, DataDictItem> tagMap = new HashMap<String, DataDictItem>();
//			for (DataDictItem dataDictItem : taglist) {
//				tagMap.put(dataDictItem.getName(), dataDictItem);
//			}
//			for (String tag : postTagList) {
//				if(StringUtils.isBlank(tag))continue;
//				DataDictItem ddItem = null;
//				if(tagMap.containsKey(tag)) {
//					ddItem = tagMap.get(tag);
//				}else {
//					// 字典表里没有则新增标签
//					ddItem = new DataDictItem();
//					ddItem.setDictid(dataDict.getId());
//					ddItem.setName(tag);
//					ddItem.setValue(tag);
//					dataDictMapper.insertDataDictItem(ddItem);
//				}
//				ContentTags label = new ContentTags();
//				label.setCid(cid);
//				label.setTid(ddItem.getId());
//				newTagList.add(label);
//			}
//		}
//		mapper.deleteTags(cid);
//		if(newTagList.size() > 0)mapper.insertContentTags(newTagList);
//
//
//		List<ContentImages> imgList = new ArrayList<ContentImages>();
//		String images = o.getImages();
//		if(StringUtils.isNotBlank(images)){
//			JSONArray array = JSONArray.parseArray(images);
//			for(int i=0, j=array.size();i<j;i++){
//				JSONObject obj = array.getJSONObject(i);
//				ContentImages contentImages = new ContentImages();
//				contentImages.setCid(cid);
//				contentImages.setSort(obj.getIntValue("sort"));
//				contentImages.setImgurl(obj.getString("imgurl"));
//				contentImages.setOri_name(obj.getString("filename"));
//				imgList.add(contentImages);
//			}
//		}
//		mapper.deleteImages(cid);
//		if(imgList.size() > 0){
//			mapper.insertContentImages(imgList);
//		}
//	}

	// 修改案例标签和图集
	private void updateLabelAndImages(Content o){
		long cid = o.getId();
		List<ContentTags> newTagList = new ArrayList<ContentTags>();
		if(StringUtils.isNotBlank(o.getTags())){
			ArrayList<String> postTagList = CommonUtils.str2List(o.getTags());
			// 查询自定义标签的dictid
			Long dictId =  dataDictMapper2.getDataDictIDLabels();

			//根据标签名称查询标签信息
			List<DataDictItem> tagList = dataDictMapper2.getDataDictTemName(postTagList);
			HashMap<String, DataDictItem> tagMap = new HashMap<String, DataDictItem>();
			for (DataDictItem dataDictItem : tagList) {
				tagMap.put(dataDictItem.getName(), dataDictItem);
			}
			for (String tag : postTagList) {
				if(StringUtils.isBlank(tag))continue;
				DataDictItem ddItem = null;
				if(tagMap.containsKey(tag)) {
					ddItem = tagMap.get(tag);
				}else {
					// 字典表里没有则新增标签
					ddItem = new DataDictItem();
					ddItem.setDictid(dictId);
					ddItem.setName(tag);
					ddItem.setValue(tag);
					dataDictMapper.insertDataDictItem(ddItem);
				}
				ContentTags label = new ContentTags();
				label.setCid(cid);
				label.setTid(ddItem.getId());
				newTagList.add(label);
			}
		}
		mapper.deleteTags(cid);
		if(o.getTagLists() != null){
			String[] tagList1 = o.getTagLists();
			for (String s : tagList1) {
				ContentTags contentTags = new ContentTags();
				contentTags.setCid(cid);
				contentTags.setTid(Long.parseLong(s));
				newTagList.add(contentTags);
			}
		}
		if(newTagList.size() > 0)mapper.insertContentTags(newTagList);


		List<ContentImages> imgList = new ArrayList<ContentImages>();
		String images = o.getImages();
		if(StringUtils.isNotBlank(images)){
			JSONArray array = JSONArray.parseArray(images);
			for(int i=0, j=array.size();i<j;i++){
				JSONObject obj = array.getJSONObject(i);
				ContentImages contentImages = new ContentImages();
				contentImages.setCid(cid);
				contentImages.setSort(obj.getIntValue("sort"));
				contentImages.setImgurl(obj.getString("imgurl"));
				contentImages.setOri_name(obj.getString("filename"));
				imgList.add(contentImages);
			}
		}
		mapper.deleteImages(cid);
		if(imgList.size() > 0){
			mapper.insertContentImages(imgList);
		}
	}

	@Transactional
	@Override
	public void add(Content entity) {
		baseSaveVerify(entity);
		entity.setType(null);
		mapper.insertSelective(entity);
		updateLabelAndImages(entity);
		entity.setVisibility(2);

		// 提交到ElasticSearch
		entity = findById(entity.getId());
		esService.merge(entity);
	}

	@Transactional
	@Override
	public void update(Content entity) {
		baseSaveVerify(entity);
		entity.setType(null);
		mapper.updateByPrimaryKeySelective(entity);
		updateLabelAndImages(entity);

		// 提交到ElasticSearch
		entity = findById(entity.getId());
		esService.merge(entity);
	}

	@Override
	public void delete(List<Long> ids) {
		if(ids == null || ids.isEmpty()){
			throw new ParameterException("id不能为空");
		}
		// 从数据库中删除
		mapper.deleteByIds(ids);
		// 从ES中删除
		esService.deleteDocByIds(ids);
	}

	@Override
	public Content findById(Long id) {
		if(id == null || id < 1){
			throw new ParameterException("id不能为空");
		}
		Content entity = mapper.findById(id);
		if(entity!=null&&entity.getId()!=null&&entity.getId()>0) {
			if(entity.getImgList()!=null)entity.setImages(JSON.toJSONString(entity.getImgList()));
			if(entity.getTagList()!=null)entity.setTags(JSON.toJSONString(entity.getTagList()));
		}
		return entity;
	}

	@Override
	public List<Content> getList(Content entity) {
		return mapper.getList(entity);
	}

	@Override
	public List<Content> getListByFront(Content entity) {
		return mapper.getListByFront(entity);
	}

	@Override
	public int updateContentNum(String type, Long id) {
		if(StringUtils.isBlank(type)){
			throw new ParameterException("类型不能为空");
		}
		if(id == null || id < 1){
			throw new ParameterException("id不能为空");
		}
		mapper.updateContentNum(type, id);
		Content entity = findById(id);

		// 提交到ElasticSearch
		esService.merge(entity);

		Integer result = 0;
		if("view".equals(type)){
			result = entity.getViewno();
		}else if("like".equals(type)){
			result = entity.getPraiseno();
		}
		if(result == null)result=1;
		return result;
	}

	@Override
	public long syncEsData(Content entity, boolean isReBuild) {
		/*if(StringUtils.isBlank(entity.getType())) {
			throw new ParameterException("案例类型不能为空");
		}*/
		if(isReBuild) {
			// 如果重建索引，则先把所有记录删除，这个也可用于删除脏数据。
			esService.deleteDocByQuery(entity);
		}
		PageHelper.startPage(1, 1000);
        List<Content> dataList = getListByFront(entity);
		PageInfo<Content> pages = new PageInfo<>(dataList);
        for (Content content : dataList) {
        	// 提交到ElasticSearch
    		esService.merge(content);
		}
        return pages.getTotal();
	}

	@Override
	public PageInfo<Content> getCaseTitle(Integer page,Integer pageSize) {
		PageHelper.startPage(page,pageSize);
		List<Content> list = mapper.getCaseTitle();
		return new PageInfo<>(list);
	}

	@Override
	public void addContentTags(ContentTags contentTags) {
		mapper.addContentTags(contentTags);
	}

	@Override
	public List<DataDictItem> getOtherLabels() {
		List<DataDictItem> list = mapper.getOtherLabels();
		return list;
	}

	@Override
	public void deleteContentTags(List<Long> idList) {
		mapper.deleteContentTags(idList);
	}

	@Override
	public void updateLabelFeedback(Long contentId) {
		mapper.updateLabelFeedback(contentId);
	}

	@Override
	public List<Content> getList2(Content entity) {
		return mapper.getList2(entity);
	}

	@Override
	public void updateComments(Long contentId) {
		mapper.updateComments(contentId);
	}

	@Override
	public void saveScore(Long userId, Long contentId, Double score) {
		mapper.saveScore(userId,contentId,score);
	}

	@Override
	public int getScore(Long userId, Long contentId) {
		return mapper.getScore(userId,contentId);
	}

	@Override
	public Content getEditContent(Long contentId) {
		return mapper.getEditContent(contentId);
	}

	@Override
	@Transactional
	public void saveApplication(Application application) {
		//添加审核申请单
		mapper.saveApplication(application);
		//添加审核人信息
		Check check = new Check();
		check.setApplicationId(application.getId());
		List<Check> checks = application.getChecks();
		if(checks == null ) throw new ParameterException("审核人不能为空!");
		for (Check check1 : checks) {
			check.setCheckId(check1.getCheckId());
			mapper.saveCheck(check);
		}
		//更新案例状态(审核可能是下架重新申请的)
		mapper.updateContentRelease(application.getContentId(),1,2);
		//更新es的状态
		Content entity=mapper.findById(application.getContentId());
		entity.setVisibility(2);
		esService.merge(entity);
	}

	@Override
	public int getApplicationCount(Long contentId) {
		return mapper.getApplicationCount(contentId);
	}

	@Override
	@Transactional
	public void deleteApplication(Long applicationId) {
		//查询案例id
		Long contentId = mapper.getContentId(applicationId);
		//删除案例审核申请
		mapper.deleteApplication(applicationId);
		//删除审核人信息
		mapper.deleteCheck(applicationId);
		//更新es的状态
		Content entity=mapper.findById(contentId);
		entity.setVisibility(2);
		esService.merge(entity);
	}

	@Override
	@Transactional
	public void updateApplicationStatus(Long contentId,Long applicationId) {
		//更新审核申请单状态
		mapper.updateApplicationStatus(applicationId);
		//更新审核人状态
		mapper.updateCheckStatus(applicationId);
		//更新案例状态(上架后重新申请)
		mapper.updateContentRelease(contentId,1,2);
	}

	@Override
	public List<Content> getContentApplication(Content entity) {
		return mapper.getContentApplication(entity);
	}

	@Override
	@Transactional
	public void updateApplication(Check check, Long userId) {
		//更新审核表状态
		check.setCheckId(userId);
		mapper.updateCheck(check);
		Application application = new Application();
		application.setId(check.getApplicationId());
		//更新申请单状态
		if(check.getStatus() == 2){
			//审核通过
			application.setStatus(2);
			//查询案例id
			Long contentId = mapper.getContentId(check.getApplicationId());
			//更新案例状态
			mapper.updateContentRelease(contentId,2,1);
			//更新es的状态
			Content entity=mapper.findById(contentId);
			entity.setVisibility(1);
			esService.merge(entity);
		}else {
			//审核驳回
			application.setStatus(3);
		}
		mapper.updateApplication(application);

	}

	@Override
	public WxUser getQyWxUser(String username) {
		return wxMapper.getQyWxUser(username);
	}

	@Override
	public List<Check> getUserLeader(String department) {
		return wxMapper.getUserLeader(department);
	}

	@Override
	@Transactional
	public void deleteRelease(Long contentId) {
		//根据案例id查询申请单信息
		Application application = mapper.getApplication(contentId);
		//删除申请单信息
		mapper.deleteApplication(application.getId());
		//删除审核表信息
		mapper.deleteCheck(application.getId());
		//案例表状态修改为已下线
		mapper.updateContentRelease(contentId,4,2);
		//更新es的状态
		Content entity=mapper.findById(contentId);
		entity.setVisibility(2);
		esService.merge(entity);
	}

	@Override
	public List<Census> getCensus(Integer type) {
		return mapper.getCensus(type);
	}


}
