package com.ltgk.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ltgk.common.constant.CacheConstants;
import com.ltgk.common.core.redis.RedisCache;
import com.ltgk.system.domain.DeptLinkArea;
import com.ltgk.system.mapper.DeptLinkAreaMapper;
import com.ltgk.system.service.DeptLinkAreaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @Author: wan kun
 * @Description: TODO
 * @Date: 2024/12/18 15:40
 * @Version: 1.0
 */
@Service
public class DeptLinkAreaServiceImpl extends ServiceImpl<DeptLinkAreaMapper, DeptLinkArea> implements DeptLinkAreaService {
    @Autowired
    private RedisCache redisCache;

    @Override
    public List<String> getDeptLinkArea(Long deptId) {
        if (ObjectUtils.isNull(deptId)) return null;
        // 获取缓存
        if (redisCache.hasKey(CacheConstants.SYS_DEPT_KEY + deptId)) {
            return redisCache.getCacheObject(CacheConstants.SYS_DEPT_KEY + deptId);
        }
        LambdaQueryWrapper<DeptLinkArea> lqw = new LambdaQueryWrapper<>();
        lqw.eq(DeptLinkArea::getDeptId, deptId);
        List<DeptLinkArea> list = this.list(lqw);
        List<String> areaList = list.stream().map(DeptLinkArea::getAreaCode).collect(Collectors.toList());
        if (ObjectUtils.isNotEmpty(areaList)) {
            redisCache.setCacheObject(CacheConstants.SYS_DEPT_KEY + deptId, areaList, 60, TimeUnit.MINUTES);
        }
        return areaList;
    }

    @Override
    public String getAreaCodes(Long deptId) {
        if (ObjectUtils.isNull(deptId)) return null;
        // 获取缓存
        if (redisCache.hasKey(CacheConstants.SYS_DEPT_KEY + deptId)) {
            List<String> areaList = redisCache.getCacheObject(CacheConstants.SYS_DEPT_KEY + deptId);
            if (ObjectUtils.isNotEmpty(areaList)) {
                return String.join(",", areaList);
            }
        }
        LambdaQueryWrapper<DeptLinkArea> lqw = new LambdaQueryWrapper<>();
        lqw.eq(DeptLinkArea::getDeptId, deptId);
        List<DeptLinkArea> list = this.list(lqw);
        List<String> areaList = list.stream().map(DeptLinkArea::getAreaCode).collect(Collectors.toList());
        if (ObjectUtils.isNotEmpty(areaList)) {
            redisCache.setCacheObject(CacheConstants.SYS_DEPT_KEY + deptId, areaList, 60, TimeUnit.MINUTES);
            return String.join(",", areaList);
        }
        return null;

    }
}
