package com.ruoyi.ai.service.impl;

import com.ruoyi.ai.service.IByteDeptApiKeyService;
import com.ruoyi.ai.service.IAiUserService;
import com.ruoyi.common.core.domain.entity.AiUser;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class ByteDeptApiKeyServiceImpl implements IByteDeptApiKeyService {

    private static final String NO_PERM_MSG = "用户没有权限，请联系管理员分配部门";
    private static final int CACHE_HOURS = 1;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private IAiUserService aiUserService;

    @Autowired
    private ISysDeptService sysDeptService;

    @Override
    public String resolveVolcApiKey(Long aiUserId) {
        if (aiUserId == null) {
            throw new ServiceException(NO_PERM_MSG);
        }
        String cacheKey = aiUserId + "_byte_api_key";
        String cached = redisCache.getCacheObject(cacheKey);
        if (StringUtils.isNotEmpty(cached)) {
            return cached;
        }
        AiUser aiUser = aiUserService.selectAiUserById(aiUserId);
        if (aiUser == null || aiUser.getDeptId() == null) {
            throw new ServiceException(NO_PERM_MSG);
        }
        SysDept userDept = sysDeptService.selectDeptById(aiUser.getDeptId());
        if (userDept == null) {
            throw new ServiceException(NO_PERM_MSG);
        }
        Long secondLevelDeptId = resolveSecondLevelDeptId(userDept);
        SysDept keyDept = sysDeptService.selectDeptById(secondLevelDeptId);
        if (keyDept == null || StringUtils.isEmpty(keyDept.getByteApiKey())) {
            throw new ServiceException(NO_PERM_MSG);
        }
        String apiKey = keyDept.getByteApiKey().trim();
        redisCache.setCacheObject(cacheKey, apiKey, CACHE_HOURS, TimeUnit.HOURS);
        return apiKey;
    }

    /**
     * 二级部门：祖级路径中，紧接在「一级」（ancestors 第二段）之下的部门节点；
     * 深度不足时退回用户当前部门。
     */
    private Long resolveSecondLevelDeptId(SysDept userDept) {
        String ancestors = userDept.getAncestors();
        if (StringUtils.isEmpty(ancestors)) {
            return userDept.getDeptId();
        }
        String[] parts = ancestors.split(",");
        if (parts.length >= 3) {
            try {
                return Long.parseLong(parts[2].trim());
            } catch (NumberFormatException ignored) {
                return userDept.getDeptId();
            }
        }
        if (parts.length == 2) {
            try {
                return Long.parseLong(parts[1].trim());
            } catch (NumberFormatException ignored) {
                return userDept.getDeptId();
            }
        }
        return userDept.getDeptId();
    }
}
