package org.springblade.flow.permission.service;

import java.util.List;

import org.springblade.flow.permission.entity.OrganizeEntity;
import org.springblade.flow.permission.entity.UserEntity;
import org.springblade.flow.permission.mapper.OrganizeMapper;
import org.springblade.flow.util.CacheKeyUtil;
import org.springblade.flow.util.JsonUtil;
import org.springblade.flow.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import cn.hutool.core.collection.CollUtil;

/**
 *  服务类
 *
 * @author william
 * @date   2022-07-14 10:57:52
 */
@Service
public class OrganizeService extends ServiceImpl<OrganizeMapper, OrganizeEntity> {

	@Autowired
	private CacheKeyUtil cacheKeyUtil;

	@Autowired
	private RedisUtil redisUtil;

	@Autowired
	private User4FlowService userService;

	public List<OrganizeEntity> getList() {
		QueryWrapper<OrganizeEntity> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda().orderByAsc(OrganizeEntity::getSortCode);
		List<OrganizeEntity> list = this.list(queryWrapper);
		return list;
	}

	public OrganizeEntity getInfo(String id) {
		QueryWrapper<OrganizeEntity> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda().eq(OrganizeEntity::getId, id);
		return this.getOne(queryWrapper);
	}

	public List<OrganizeEntity> getOrgRedisList() {
		if (redisUtil.exists(cacheKeyUtil.getOrganizeList())) {
			return JsonUtil.getJsonToList(redisUtil.getString(cacheKeyUtil.getOrganizeList()).toString(),
					OrganizeEntity.class);
		}
		QueryWrapper<OrganizeEntity> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda().eq(OrganizeEntity::getIsDeleted, 0);

		List<OrganizeEntity> list = this.list(queryWrapper);
		if (list.size() > 0) {
			redisUtil.insert(cacheKeyUtil.getOrganizeList(), JsonUtil.getObjectToString(list), 300);
		}
		return list;
	}

	/**
	 * 是否有子部门
	 * 
	 * @return
	 */
	public boolean hasChild(String id) {
		QueryWrapper<OrganizeEntity> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda().eq(OrganizeEntity::getParentId, id);
		List<OrganizeEntity> list = this.list(queryWrapper);
		return CollUtil.isNotEmpty(list);
	}

	/**
	 * 是否有员工
	 * 
	 * @return
	 */
	public boolean hasUser(String id) {
		QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda().eq(UserEntity::getOrganizeId, id);
		List<UserEntity> list = userService.list(queryWrapper);
		return CollUtil.isNotEmpty(list);
	}
}