package com.hotent.portal.persistence.manager.impl;

import java.io.File;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.hotent.base.model.CommonResult;
import com.hotent.base.query.*;
import com.hotent.base.util.*;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hotent.base.conf.SaaSConfig;
import com.hotent.base.exception.BaseException;
import com.hotent.base.manager.impl.BaseManagerImpl;
import com.hotent.portal.model.PortalNewsNotice;
import com.hotent.portal.model.PortalNewsTree;
import com.hotent.portal.persistence.dao.PortalNewsNoticeDao;
import com.hotent.portal.persistence.dao.PortalNewsTreeDao;
import com.hotent.portal.persistence.manager.PortalNewsNoticeManager;
import com.hotent.portal.persistence.manager.PortalNewsTreeManager;
import com.hotent.sys.persistence.manager.SysAuthUserManager;
import com.hotent.sys.persistence.model.SysAuthUser;
import com.hotent.uc.api.impl.util.ContextUtil;
import com.hotent.uc.api.model.IUser;

/**
 *  服务实现类
 *
 * @company 广州宏天软件股份有限公司
 * @author 赵祥云
 * @since 2020-07-03
 */
@Service
public class PortalNewsNoticeManagerImpl extends BaseManagerImpl<PortalNewsNoticeDao, PortalNewsNotice> implements PortalNewsNoticeManager {

	@Resource
	PortalNewsNoticeDao portalNewsNoticeDao;

	@Resource
	PortalNewsTreeManager portalNewsTreeManager;
	@Resource
	PortalNewsTreeDao portalNewsTreeDao;
	@Resource
	SysAuthUserManager sysAuthUserManager;

	@Override
	public List<PortalNewsNotice> getNews(String classifyId, String page, String pageSize) {
		QueryWrapper<PortalNewsNotice> queryWrapper = new QueryWrapper<>();
		LocalDateTime now = LocalDateTime.now();
		if (!classifyId.equals("all")){
			List<String> treeIds = new ArrayList<String>();
			QueryWrapper<PortalNewsTree> treeWrapper = new QueryWrapper<>();
			treeWrapper.like(true, "PATH_", classifyId+".");
			List<PortalNewsTree> treeList = portalNewsTreeDao.selectList(treeWrapper);
			for (PortalNewsTree portalNewsTree : treeList) {
				treeIds.add(portalNewsTree.getId());
			}
			if(!treeIds.isEmpty()){
				queryWrapper.in("CLASSIFY_ID_", treeIds);
			}
		}
		queryWrapper.le("PUBLISH_TIME_", now);
		queryWrapper.orderByAsc("SN_").orderByDesc("CREATE_TIME_");
//		queryWrapper.gt("END_TIME_", now);
		//List<PortalNewsNotice> selectList = baseMapper.selectList(queryWrapper);
		List<PortalNewsNotice> selectList = new ArrayList<PortalNewsNotice>();
		if(StringUtil.isNotEmpty(page) && StringUtil.isNotEmpty(pageSize)) {
			PageBean bean = new PageBean(Integer.valueOf(page), Integer.valueOf(pageSize));
			IPage pageInfo = baseMapper.selectPage(convert2IPage(bean), queryWrapper);
			selectList = pageInfo.getRecords();
		} else {
			selectList = baseMapper.selectList(queryWrapper);
		}
		IUser currentUser = null;
		try {
			currentUser = ContextUtil.getCurrentUser();
		}catch (Exception e){}
		Map<String,Boolean> authMap = null;
		//应用数据权限
		if(BeanUtils.isNotEmpty(selectList) && BeanUtils.isNotEmpty(currentUser) && !currentUser.isAdmin()) {
			List<String> list = new ArrayList<String>();
			for (PortalNewsNotice notice : selectList) {
				list.add(notice.getId());
			}
			List<String> authList = sysAuthUserManager.getAuthorizeIdsByUserAndList(SysAuthUser.BPMDEFUSER_OBJ_TYPE.NEWS_NOTICE, list);
			if(BeanUtils.isNotEmpty(authList)) {
				authMap = new HashMap<String, Boolean>();
				for (String id : authList) {
					authMap.put(id, true);
				}
			}
		} else if(BeanUtils.isNotEmpty(selectList) && BeanUtils.isEmpty(currentUser)) {
			List<String> list = new ArrayList<String>();
			for (PortalNewsNotice notice : selectList) {
				list.add(notice.getId());
			}
			List<String> authList = sysAuthUserManager.getAuthorizeIdsInIds(list, SysAuthUser.BPMDEFUSER_OBJ_TYPE.NEWS_NOTICE);
			if(BeanUtils.isNotEmpty(authList)) {
				authMap = new HashMap<String, Boolean>();
				for (int i = 0; i < list.size(); i++) {
					String id = list.get(i);
					if (!authList.contains(list.get(i))) {
						authMap.put(id, true);
					}
				}
			}
		}
		List<PortalNewsNotice> respNotice = new ArrayList<>();
		for (PortalNewsNotice notice : selectList) {
			if (notice.getEndTime()!=null && notice.getEndTime().isBefore(now)){
				// 已过期，不予展示
			}else if(authMap == null || authMap.containsKey(notice.getId())){
				respNotice.add(notice);
			}
		}
		return respNotice;
	}


	@Override
	public void deleteByClassifyId(String classifyId) {
		portalNewsNoticeDao.deleteByClassifyId(classifyId);
	}

	@Override
	public void deleteNewsByParentId(String parentId) {
		portalNewsNoticeDao.deleteNewsByParentId(parentId);
	}

	@Override
	public String export(List<String> ids) throws Exception{
		if (BeanUtils.isEmpty(ids)) {
			throw new BaseException("传入的id集合为空");
		}
		List<PortalNewsNotice> portalNewsNotices = baseMapper.selectBatchIds(ids);
		if (BeanUtils.isEmpty(portalNewsNotices)) {
			throw new BaseException("根据id集合查找，未查到任何记录");
		}
		return JsonUtil.toJson(portalNewsNotices);
	}

	@Override
	public CommonResult<String> importCheck(String uzPath, String classifyId) throws Exception{

		String fileStr = FileUtil.readFile(uzPath + File.separator + "newsNotice.json");
		SaaSConfig saaSConfig = AppUtil.getBean(SaaSConfig.class);
		boolean enable = saaSConfig.isEnable();
		List list = JsonUtil.toBean(fileStr, List.class);
		PortalNewsTree portalNewsTree = portalNewsTreeManager.get(classifyId);
		if (BeanUtils.isEmpty(portalNewsTree)) {
			throw new BaseException("请先选择要导入的分类");
		}

		List<String> titles = Lists.newArrayList();
		for (Object o : list) {
			PortalNewsNotice portalNewsNotice = JsonUtil.toBean(JsonUtil.toJson(o), PortalNewsNotice.class);
			titles.add(portalNewsNotice.getTitle());
		}

		LambdaQueryWrapper<PortalNewsNotice> query = Wrappers.<PortalNewsNotice>lambdaQuery().eq(PortalNewsNotice::getClassifyId, classifyId).in(PortalNewsNotice::getTitle, titles);
		List<PortalNewsNotice> portalNewsNoticeList = this.getBaseMapper().selectList(query);
		if(BeanUtils.isNotEmpty(portalNewsNoticeList)){
			return new CommonResult<String>(false, "导入失败，导入的数据中有数据已经存在，是否进行覆盖？");
		}
		//2、没有重复数据，直接导入
		this.importFile(uzPath,classifyId);
		return new CommonResult<String>(true, "导入成功");
	}

	@Override
	public void importFile(String uzPath, String classifyId) {
		try {
			String fileStr = FileUtil.readFile(uzPath + File.separator + "newsNotice.json");
			SaaSConfig saaSConfig = AppUtil.getBean(SaaSConfig.class);
			boolean enable = saaSConfig.isEnable();
			List list = JsonUtil.toBean(fileStr, List.class);
			PortalNewsTree portalNewsTree = portalNewsTreeManager.get(classifyId);
			if (BeanUtils.isEmpty(portalNewsTree)) {
				throw new BaseException("请先选择要导入的分类");
			}
			String treeType;
			if(portalNewsTree.getPath().startsWith("100")){
				treeType = "1";
			}else if(portalNewsTree.getPath().startsWith("200")){
				treeType = "2";
			}else{
				throw new BaseException("所属分类未知");
			}

			Map<String, PortalNewsNotice> portalNewsNoticeByTitleMap = this.getPortalNewsNoticeByTitleMap(classifyId, list);

			for (Object o : list) {
				PortalNewsNotice portalNewsNotice = JsonUtil.toBean(JsonUtil.toJson(o), PortalNewsNotice.class);
				if(treeType.equals(portalNewsNotice.getType().toString())){
					throw new BaseException("所属类型不匹配，无法导入");
				}

				portalNewsNotice.setClassifyPath(portalNewsTree.getPath());
				portalNewsNotice.setClassifyId(classifyId);
				portalNewsNotice.setClassifyName(portalNewsTree.getName());
				QueryFilter<PortalNewsNotice> filter = QueryFilter.build();
				filter.addFilter("CLASSIFY_ID_", portalNewsTree.getId(), QueryOP.EQUAL, FieldRelation.AND);
				filter.addFilter("ID_", portalNewsNotice.getId(), QueryOP.EQUAL, FieldRelation.AND);
				//如果当前分类下已存在，则更新
				PageList<PortalNewsNotice> old = this.query(filter);
				if (BeanUtils.isEmpty(old.getRows()) || old.getRows().isEmpty()) {
					//根据ID查询不存在，再根据title查询
					if(portalNewsNoticeByTitleMap.containsKey(portalNewsNotice.getTitle())){
						PortalNewsNotice oldNotice = portalNewsNoticeByTitleMap.get(portalNewsNotice.getTitle());
						portalNewsNotice.setId(oldNotice.getId());
						portalNewsNotice.setCreateTime(oldNotice.getCreateTime());
						this.updateById(portalNewsNotice);
					}else{
						portalNewsNotice.setId(UniqueIdUtil.getSuid());
						if(enable){
							//启用租户模式下
							portalNewsNotice.setTenantId(null);
						}
						this.create(portalNewsNotice);
					}
				}else{
					this.updateById(portalNewsNotice);
				}
			}

		}catch (Exception e){
			throw new BaseException(e.getMessage());
		}
	}

	private Map<String,PortalNewsNotice> getPortalNewsNoticeByTitleMap(String classifyId,List<Object> list) throws Exception{
		List<String> titles = Lists.newArrayList();
		for (Object o : list) {
			PortalNewsNotice portalNewsNotice = JsonUtil.toBean(JsonUtil.toJson(o), PortalNewsNotice.class);
			titles.add(portalNewsNotice.getTitle());
		}
		LambdaQueryWrapper<PortalNewsNotice> query = Wrappers.<PortalNewsNotice>lambdaQuery().eq(PortalNewsNotice::getClassifyId, classifyId).in(PortalNewsNotice::getTitle, titles);
		List<PortalNewsNotice> portalNewsNotices = this.getBaseMapper().selectList(query);
		if(BeanUtils.isNotEmpty(portalNewsNotices)){
			Map<String, PortalNewsNotice> map = portalNewsNotices.stream().collect(Collectors.toMap(PortalNewsNotice::getTitle, m -> m, (key1, key2) -> key2));
			return map;
		}
		return Maps.newHashMap();
	}
}
