package com.emergency.avenue.admin.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.emergency.avenue.admin.api.entity.SysDeptRelation;
import com.emergency.avenue.common.core.exception.BusinessException;
import com.emergency.avenue.common.core.util.IdGenerator;
import com.emergency.avenue.admin.api.entity.SysTreeDict;
import com.emergency.avenue.admin.api.vo.*;
import com.emergency.avenue.admin.mapper.SysTreeDictMapper;
import com.emergency.avenue.admin.service.SysTreeDictService;
import lombok.AllArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 工单字典表
 * </P>
 *
 * @Author: wenpeng_qing
 * @Date: 2019-05-27 03:59
 * @Version: 1.0.0
 */
@AllArgsConstructor
@Service("sysTreeDictService")
public class SysTreeDictServiceImpl extends ServiceImpl<SysTreeDictMapper, SysTreeDict> implements
		SysTreeDictService {

	/**
	 * 工单字典表简单分页查询
	 *
	 * @param sysTreeDict 工单字典表
	 */
	@Override
	public IPage<SysTreeDict> getOrderDictPage(Page<SysTreeDict> page, SysTreeDict sysTreeDict) {
		return baseMapper.getOrderDictPage(page, sysTreeDict);
	}

	@Override
	public List<TreeNode> getDictTree(Integer type) {
		List<SysTreeDict> dictList = baseMapper.getOrderDictList(type);
		List<TreeNode> treeNodes = new ArrayList<>();
		dictList.stream()
				.forEach(dict -> treeNodes.add(JSON.parseObject(JSON.toJSONString(dict), TreeNode.class)));
		return TreeBuilder.buildByRecursive(treeNodes);
	}

	@Override
	public List<SysTreeDict> getList(Integer type) {
		return baseMapper.getOrderDictList(type);
	}

	/**
	 * 查询字典根据id集合
	 *
	 * @param dictList
	 * @return
	 */
	@Override
	public List<SysTreeDict> selectByDicIds(List<String> dictList) {
		return baseMapper.selectBatchIds(dictList);
	}


	@Override
	public List<SysTreeDict> getTypesList(List<Integer> typeList) {
		if (CollUtil.isNotEmpty(typeList)) {
			return baseMapper.getTypesList(typeList);
		} else {
			return new ArrayList<>();
		}
	}

	@Override
	public int insert(SysTreeDict entity) {
		if (entity.getName().length() > 50) {
			throw new IllegalStateException("名称长度不能超过50位");
		}
		if (Boolean.FALSE.equals(validateRe(entity.getType(), entity.getName(), entity.getCode()))) {
			throw new IllegalStateException("编码重复");
		}
		entity.setId(IdGenerator.nextId());
		handleSysTreeDict(entity);
		return baseMapper.insert(entity);
	}

	void handleSysTreeDict(SysTreeDict sysTreeDict) {
		if (sysTreeDict.getType() == 1) {
			if (CharSequenceUtil.isBlank(sysTreeDict.getCode())) {
				throw new BusinessException("物资类型CODE不能为空");
			}
			SysTreeDict sysTreeDictParent = baseMapper.selectById(sysTreeDict.getParentId());
			if (sysTreeDictParent != null) {
				sysTreeDict.setParentCode(sysTreeDictParent.getParentCode());
				sysTreeDict.setPath(sysTreeDictParent.getPath() + sysTreeDict.getCode() + "/");
			} else {
				sysTreeDict.setPath("/" + sysTreeDict.getCode() + "/");
			}

		}
	}

	Boolean validateRe(Integer type, String name, String code) {
//		List<SysTreeDict> sysTreeDictNameList = baseMapper.getOrderDict(name, type);
//		if (CollectionUtils.isNotEmpty(sysTreeDictNameList)) {
//			return false;
//		}
		List<SysTreeDict> sysTreeDictCodeList = baseMapper.selectList(Wrappers.<SysTreeDict>query().lambda()
				.eq(SysTreeDict::getType, type).eq(SysTreeDict::getCode, code));
		if (CollectionUtils.isNotEmpty(sysTreeDictCodeList)) {
			return false;
		}
		return true;
	}

	@Override
	public List<SysTreeDict> getOrderDictPath(String dictId) {
		List<SysTreeDict> dictList = new ArrayList<>();
		int i = 1;
		if (CharSequenceUtil.isNotBlank(dictId)) {
			SysTreeDict orderDict = baseMapper.selectById(dictId);
			if (orderDict != null) {
				orderDict.setSort(i);
				dictList.add(orderDict);
				if (!orderDict.getParentId().equals("0")) {
					getChild(orderDict.getParentId(), dictList, i + 1);
				}
			}

			dictList.sort(Comparator.comparingLong(SysTreeDict::getSort).reversed());
			return dictList;
		}
		return Collections.emptyList();
	}

	public void getChild(String dictId, List<SysTreeDict> dictList, int i) {
		SysTreeDict sysTreeDict = baseMapper.selectById(dictId);
		if (sysTreeDict != null) {
			sysTreeDict.setSort(i);
			dictList.add(sysTreeDict);
			if (!sysTreeDict.getParentId().equals("0")) {
				getChild(sysTreeDict.getParentId(), dictList, i + 1);
			}
		}
	}
}