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_DEPT_MSG = "用户未分配部门：请在后台为门户用户设置 ai_user.dept_id（关联 sys_dept.dept_id）";
    private static final String NO_DEPT_ROW_MSG = "用户所属部门不存在或已删除，请核对 ai_user.dept_id";
    private static final String NO_API_KEY_MSG = "部门未配置火山 API Key：请在 sys_dept 为用户所在部门（或其上级二级部门）配置 byte_api_key";
    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_DEPT_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_DEPT_MSG);
        }
        SysDept userDept = sysDeptService.selectDeptById(aiUser.getDeptId());
        if (userDept == null) {
            throw new ServiceException(NO_DEPT_ROW_MSG);
        }
        // 优先使用用户直接归属部门的 Key；多数业务把用户挂在分公司（如 101）并在该节点配 byte_api_key
        String apiKey = trimKey(userDept.getByteApiKey());
        if (StringUtils.isEmpty(apiKey)) {
            Long fallbackDeptId = resolveSecondLevelDeptId(userDept);
            if (!fallbackDeptId.equals(userDept.getDeptId())) {
                SysDept keyDept = sysDeptService.selectDeptById(fallbackDeptId);
                if (keyDept != null) {
                    apiKey = trimKey(keyDept.getByteApiKey());
                }
            }
        }
        if (StringUtils.isEmpty(apiKey)) {
            throw new ServiceException(NO_API_KEY_MSG);
        }
        redisCache.setCacheObject(cacheKey, apiKey, CACHE_HOURS, TimeUnit.HOURS);
        return apiKey;
    }

    private static String trimKey(String raw) {
        return raw == null ? null : raw.trim();
    }

    /**
     * 二级部门：祖级路径中，紧接在「一级」（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();
    }
}
