package com.gxwebsoft.ai.controller;

import com.gxwebsoft.ai.entity.AiHistory;
import com.gxwebsoft.ai.param.AiHistoryParam;
import com.gxwebsoft.ai.service.AiHistoryService;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.common.core.web.BatchParam;
import com.gxwebsoft.common.system.entity.User;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

import lombok.extern.slf4j.Slf4j;

/**
 * AI审计历史记录表控制器
 * @author yc
 */
@Tag(name = "AI审计历史记录表管理")
@RestController
@RequestMapping("/api/ai/history")
@Slf4j
public class AiHistoryController extends BaseController {
    @Resource
    private AiHistoryService aiHistoryService;

    //@PreAuthorize("hasAuthority('ai:aiHistory:list')")
    @Operation(summary = "分页查询AI审计历史记录表")
    @GetMapping("/page")
    public ApiResult<PageResult<AiHistory>> page(AiHistoryParam param) {
        // 使用关联查询
        return success(aiHistoryService.pageRel(param));
    }

    //@PreAuthorize("hasAuthority('ai:aiHistory:list')")
    @Operation(summary = "查询全部AI审计历史记录表")
    @GetMapping()
    public ApiResult<List<AiHistory>> list(AiHistoryParam param) {
        // 使用关联查询
        return success(aiHistoryService.listRel(param));
    }

    //@PreAuthorize("hasAuthority('ai:aiHistory:list')")
    @Operation(summary = "根据id查询AI审计历史记录表")
    @GetMapping("/{id}")
    public ApiResult<AiHistory> get(@PathVariable("id") Long id) {
        // 使用关联查询
        return success(aiHistoryService.getByIdRel(id));
    }

    //@PreAuthorize("hasAuthority('ai:aiHistory:save')")
    @Operation(summary = "添加AI审计历史记录表")
    @PostMapping()
    public ApiResult<?> save(@RequestBody AiHistory aiHistory) {
        // 记录当前登录用户id
        User loginUser = getLoginUser();
        if (loginUser != null) {
            aiHistory.setUserId(loginUser.getUserId());
            aiHistory.setUsername(loginUser.getUsername());
        }
        if (aiHistoryService.save(aiHistory)) {
            return success("添加成功");
        }
        return fail("添加失败");
    }

    //@PreAuthorize("hasAuthority('ai:aiHistory:update')")
    @Operation(summary = "修改AI审计历史记录表")
    @PutMapping()
    public ApiResult<?> update(@RequestBody AiHistory aiHistory) {
        if (aiHistoryService.updateById(aiHistory)) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    //@PreAuthorize("hasAuthority('ai:aiHistory:remove')")
    @Operation(summary = "删除AI审计历史记录表")
    @DeleteMapping("/{id}")
    public ApiResult<?> remove(@PathVariable("id") Long id) {
        if (aiHistoryService.removeById(id)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

    //@PreAuthorize("hasAuthority('ai:aiHistory:save')")
    @Operation(summary = "批量添加AI审计历史记录表")
    @PostMapping("/batch")
    public ApiResult<?> saveBatch(@RequestBody List<AiHistory> list) {
        User loginUser = getLoginUser();
        if (loginUser != null) {
            for (AiHistory history : list) {
                history.setUserId(loginUser.getUserId());
                history.setUsername(loginUser.getUsername());
            }
        }
        if (aiHistoryService.saveBatch(list)) {
            return success("添加成功");
        }
        return fail("添加失败");
    }

    //@PreAuthorize("hasAuthority('ai:aiHistory:update')")
    @Operation(summary = "批量修改AI审计历史记录表")
    @PutMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody BatchParam<AiHistory> batchParam) {
        if (batchParam.update(aiHistoryService, "id")) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    //@PreAuthorize("hasAuthority('ai:aiHistory:remove')")
    @Operation(summary = "批量删除 AI审计历史记录表")
    @DeleteMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody List<Long> ids) {
        if (aiHistoryService.removeByIds(ids)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

    /**
     * 根据接口名称和项目 ID 查询最新的历史记录
     */
    @Operation(summary = "查询最新的历史记录")
    @GetMapping("/latest")
    public ApiResult<AiHistory> getLatestHistory(
            @RequestParam String interfaceName,
            @RequestParam Long projectId) {
        try {
            log.info("===== 查询最新历史记录 =====");
            log.info("interfaceName: {}", interfaceName);
            log.info("projectId: {}", projectId);
            
            AiHistory latestHistory = aiHistoryService.getLatestHistory(interfaceName, projectId);
            
            if (latestHistory != null) {
                log.info("查询到历史记录 - id: {}, interfaceName: {}", latestHistory.getId(), latestHistory.getInterfaceName());
            } else {
                log.warn("未查询到历史记录 - interfaceName: {}, projectId: {}", interfaceName, projectId);
            }
            
            return success(latestHistory);
        } catch (Exception e) {
            log.error("查询最新历史记录异常", e);
            return fail("查询最新历史记录异常：" + e.getMessage(), null);
        }
    }
}