package org.springblade.flow.permission.service;

import java.util.ArrayList;
import java.util.List;

import org.springblade.flow.permission.entity.PositionEntity;
import org.springblade.flow.permission.mapper.PositionMapper;
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-26 16:35:54
 */
@Service
public class PositionService extends ServiceImpl<PositionMapper, PositionEntity> {
	@Autowired
	private CacheKeyUtil cacheKeyUtil;

	@Autowired
	private RedisUtil redisUtil;

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

	public List<PositionEntity> getPositionName(List<String> idList) {
		List<PositionEntity> list = new ArrayList<>();
		if (idList.size() > 0) {
			QueryWrapper<PositionEntity> queryWrapper = new QueryWrapper<>();
			queryWrapper.lambda().in(PositionEntity::getId, idList);
			list = this.list(queryWrapper);
		}
		return list;
	}

	public List<PositionEntity> getPositionName(String... ids) {
		if (ids != null && ids.length > 0) {
			List<String> idList = CollUtil.newArrayList(ids);
			return getPositionName(idList);
		}
		return null;
	}

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

	public List<PositionEntity> getPosRedisList() {
		if (redisUtil.exists(cacheKeyUtil.getPositionList())) {
			return JsonUtil.getJsonToList(redisUtil.getString(cacheKeyUtil.getPositionList()).toString(),
					PositionEntity.class);
		}
		QueryWrapper<PositionEntity> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda().eq(PositionEntity::getEnabledMark, 1);

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