package com.yushu.web.controller.system;

import com.yushu.common.annotation.Log;
import com.yushu.common.core.controller.BaseController;
import com.yushu.common.core.domain.AjaxResult;
import com.yushu.common.core.page.TableDataInfo;
import com.yushu.common.enums.BusinessType;
import com.yushu.system.domain.AiService;
import com.yushu.system.service.IAiServiceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * AI服务管理Controller
 * 
 * 简化设计：一个服务 = 一个可用的AI
 * 新增AI只需要在这里添加一条配置
 * 
 * @author yushu
 * @date 2024-12-12
 */
@RestController
@RequestMapping("/system/ai/service")
public class AiServiceController extends BaseController {
    
    @Autowired
    private IAiServiceService aiServiceService;

    /**
     * 查询AI服务列表
     */
    @PreAuthorize("@ss.hasPermi('ai:service:list')")
    @GetMapping("/list")
    public TableDataInfo list(AiService aiService) {
        startPage();
        List<AiService> list = aiServiceService.selectAiServiceList(aiService);
        return getDataTable(list);
    }

    /**
     * 查询已启用的AI服务列表（下拉框使用）
     */
    @GetMapping("/enabled")
    public AjaxResult enabledList() {
        List<AiService> list = aiServiceService.selectEnabledServiceList();
        // 隐藏敏感信息
        list.forEach(s -> {
            s.setApiKey(null);
            s.setApiSecret(null);
        });
        return success(list);
    }

    /**
     * 获取AI服务详细信息（API Key已脱敏）
     */
    @PreAuthorize("@ss.hasPermi('ai:service:query')")
    @GetMapping("/{serviceId}")
    public AjaxResult getInfo(@PathVariable Long serviceId) {
        // Service层已处理脱敏
        return success(aiServiceService.selectAiServiceByServiceId(serviceId));
    }

    /**
     * 查看完整API Key（敏感操作，需要管理员权限）
     */
    @PreAuthorize("@ss.hasPermi('ai:service:viewkey')")
    @Log(title = "AI服务", businessType = BusinessType.OTHER)
    @GetMapping("/viewkey/{serviceId}")
    public AjaxResult viewApiKey(@PathVariable Long serviceId) {
        AiService service = aiServiceService.selectFullServiceById(serviceId);
        if (service == null) {
            return error("服务不存在");
        }
        // 只返回API Key相关信息
        AiService result = new AiService();
        result.setServiceId(service.getServiceId());
        result.setServiceName(service.getServiceName());
        result.setApiKey(service.getApiKey());
        result.setApiSecret(service.getApiSecret());
        return success(result);
    }

    /**
     * 新增AI服务
     */
    @PreAuthorize("@ss.hasPermi('ai:service:add')")
    @Log(title = "AI服务", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody AiService aiService) {
        // 检查服务代码是否已存在
        if (aiServiceService.selectAiServiceByServiceCode(aiService.getServiceCode()) != null) {
            return error("服务代码'" + aiService.getServiceCode() + "'已存在");
        }
        return toAjax(aiServiceService.insertAiService(aiService));
    }

    /**
     * 修改AI服务
     */
    @PreAuthorize("@ss.hasPermi('ai:service:edit')")
    @Log(title = "AI服务", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody AiService aiService) {
        // 如果API Key是脱敏的，不更新
        if (aiService.getApiKey() != null && aiService.getApiKey().contains("****")) {
            aiService.setApiKey(null);
        }
        return toAjax(aiServiceService.updateAiService(aiService));
    }

    /**
     * 删除AI服务
     */
    @PreAuthorize("@ss.hasPermi('ai:service:remove')")
    @Log(title = "AI服务", businessType = BusinessType.DELETE)
    @DeleteMapping("/{serviceIds}")
    public AjaxResult remove(@PathVariable Long[] serviceIds) {
        return toAjax(aiServiceService.deleteAiServiceByServiceIds(serviceIds));
    }

    /**
     * 设置默认服务
     */
    @PreAuthorize("@ss.hasPermi('ai:service:edit')")
    @Log(title = "AI服务", businessType = BusinessType.UPDATE)
    @PutMapping("/default/{serviceId}")
    public AjaxResult setDefault(@PathVariable Long serviceId) {
        return toAjax(aiServiceService.setDefaultService(serviceId));
    }

    /**
     * 获取默认服务
     */
    @GetMapping("/default")
    public AjaxResult getDefault() {
        AiService service = aiServiceService.selectDefaultService();
        if (service != null) {
            service.setApiKey(null);
            service.setApiSecret(null);
        }
        return success(service);
    }

    /**
     * 测试AI服务连接
     */
    @PreAuthorize("@ss.hasPermi('ai:service:query')")
    @PostMapping("/test/{serviceId}")
    public AjaxResult testConnection(@PathVariable Long serviceId) {
        AiService service = aiServiceService.selectAiServiceByServiceId(serviceId);
        if (service == null) {
            return error("服务不存在");
        }
        if (service.getApiKey() == null || service.getApiKey().isEmpty()) {
            return error("请先配置API密钥");
        }
        // TODO: 实际发送测试请求
        return success("连接测试成功");
    }
}
