package com.yushu.system.service.impl;

import com.yushu.common.utils.AesUtils;
import com.yushu.common.utils.SecurityUtils;
import com.yushu.system.domain.AiService;
import com.yushu.system.mapper.AiServiceMapper;
import com.yushu.system.service.IAiServiceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * AI服务Service业务层处理
 * 
 * @author yushu
 * @date 2024-12-12
 */
@Service
public class AiServiceServiceImpl implements IAiServiceService {
    
    @Autowired
    private AiServiceMapper aiServiceMapper;

    @Override
    public AiService selectAiServiceByServiceId(Long serviceId) {
        AiService service = aiServiceMapper.selectAiServiceByServiceId(serviceId);
        if (service != null) {
            // 返回给前端时脱敏显示
            maskSensitiveData(service);
        }
        return service;
    }
    
    /**
     * 获取完整的服务配置（含解密后的API Key，仅内部调用）
     */
    @Override
    public AiService selectFullServiceById(Long serviceId) {
        AiService service = aiServiceMapper.selectAiServiceByServiceId(serviceId);
        if (service != null) {
            // 解密API Key供内部使用
            decryptSensitiveData(service);
        }
        return service;
    }

    @Override
    public AiService selectAiServiceByServiceCode(String serviceCode) {
        AiService service = aiServiceMapper.selectAiServiceByServiceCode(serviceCode);
        if (service != null) {
            maskSensitiveData(service);
        }
        return service;
    }

    @Override
    public List<AiService> selectAiServiceList(AiService aiService) {
        List<AiService> list = aiServiceMapper.selectAiServiceList(aiService);
        // 列表展示时脱敏
        list.forEach(this::maskSensitiveData);
        return list;
    }

    @Override
    public List<AiService> selectEnabledServiceList() {
        List<AiService> list = aiServiceMapper.selectEnabledServiceList();
        list.forEach(this::maskSensitiveData);
        return list;
    }

    @Override
    public int insertAiService(AiService aiService) {
        aiService.setCreateBy(SecurityUtils.getUsername());
        // 加密敏感数据
        encryptSensitiveData(aiService);
        return aiServiceMapper.insertAiService(aiService);
    }

    @Override
    public int updateAiService(AiService aiService) {
        aiService.setUpdateBy(SecurityUtils.getUsername());
        // 如果API Key是脱敏值，不更新
        if (aiService.getApiKey() != null && aiService.getApiKey().contains("****")) {
            aiService.setApiKey(null);
        } else if (aiService.getApiKey() != null) {
            aiService.setApiKey(AesUtils.encrypt(aiService.getApiKey()));
        }
        if (aiService.getApiSecret() != null && aiService.getApiSecret().contains("****")) {
            aiService.setApiSecret(null);
        } else if (aiService.getApiSecret() != null) {
            aiService.setApiSecret(AesUtils.encrypt(aiService.getApiSecret()));
        }
        return aiServiceMapper.updateAiService(aiService);
    }
    
    /**
     * 加密敏感数据
     */
    private void encryptSensitiveData(AiService service) {
        if (service.getApiKey() != null && !service.getApiKey().isEmpty()) {
            service.setApiKey(AesUtils.encrypt(service.getApiKey()));
        }
        if (service.getApiSecret() != null && !service.getApiSecret().isEmpty()) {
            service.setApiSecret(AesUtils.encrypt(service.getApiSecret()));
        }
    }
    
    /**
     * 解密敏感数据（内部调用时使用）
     */
    private void decryptSensitiveData(AiService service) {
        if (service.getApiKey() != null && !service.getApiKey().isEmpty()) {
            service.setApiKey(AesUtils.decrypt(service.getApiKey()));
        }
        if (service.getApiSecret() != null && !service.getApiSecret().isEmpty()) {
            service.setApiSecret(AesUtils.decrypt(service.getApiSecret()));
        }
    }
    
    /**
     * 脱敏敏感数据（返回给前端时使用）
     */
    private void maskSensitiveData(AiService service) {
        if (service.getApiKey() != null && !service.getApiKey().isEmpty()) {
            // 先解密再脱敏
            String decrypted = AesUtils.decrypt(service.getApiKey());
            service.setApiKey(AesUtils.mask(decrypted));
        }
        if (service.getApiSecret() != null && !service.getApiSecret().isEmpty()) {
            String decrypted = AesUtils.decrypt(service.getApiSecret());
            service.setApiSecret(AesUtils.mask(decrypted));
        }
    }

    @Override
    public int deleteAiServiceByServiceId(Long serviceId) {
        return aiServiceMapper.deleteAiServiceByServiceId(serviceId);
    }

    @Override
    public int deleteAiServiceByServiceIds(Long[] serviceIds) {
        return aiServiceMapper.deleteAiServiceByServiceIds(serviceIds);
    }

    @Override
    public AiService selectDefaultService() {
        return aiServiceMapper.selectDefaultService();
    }

    @Override
    @Transactional
    public int setDefaultService(Long serviceId) {
        // 先重置所有默认
        aiServiceMapper.resetDefaultService();
        // 设置新的默认
        AiService service = new AiService();
        service.setServiceId(serviceId);
        service.setIsDefault("1");
        service.setUpdateBy(SecurityUtils.getUsername());
        return aiServiceMapper.updateAiService(service);
    }
}
