package com.gxwebsoft.ai.controller;

import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.ai.service.AiCloudFileService;
import com.gxwebsoft.ai.entity.AiCloudFile;
import com.gxwebsoft.ai.param.AiCloudFileParam;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gxwebsoft.common.core.web.ApiResult;
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.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * AI云文件表控制器
 *
 * @author yc
 */
@Tag(name = "AI云文件表管理")
@RestController
@RequestMapping("/api/ai/file")
public class AiCloudFileController extends BaseController {
	
    @Resource
    private AiCloudFileService aiCloudFileService;

    //@PreAuthorize("hasAuthority('ai:aiCloudFile:list')")
    @Operation(summary = "分页查询AI云文件表")
    @GetMapping("/page")
    public ApiResult<PageResult<AiCloudFile>> page(AiCloudFileParam param) {
        return success(aiCloudFileService.pageRel(param));
    }

    //@PreAuthorize("hasAuthority('ai:aiCloudFile:list')")
    @Operation(summary = "查询全部AI云文件表")
    @GetMapping()
    public ApiResult<List<AiCloudFile>> list(AiCloudFileParam param) {
        return success(aiCloudFileService.listRel(param));
    }

    //@PreAuthorize("hasAuthority('ai:aiCloudFile:list')")
    @Operation(summary = "根据id查询AI云文件表")
    @GetMapping("/{id}")
    public ApiResult<AiCloudFile> get(@PathVariable("id") Integer id) {
        return success(aiCloudFileService.getByIdRel(id));
    }

    //@PreAuthorize("hasAuthority('ai:aiCloudFile:list')")
    @Operation(summary = "根据ids查询AI云文件表")
    @GetMapping("/byIds/{ids}")
    public ApiResult<List<AiCloudFile>> getByIds(@PathVariable("ids") String ids) {
        List<String> idList = cn.hutool.core.util.StrUtil.split(ids, ',');
        List<AiCloudFile> ret = aiCloudFileService.list(new LambdaQueryWrapper<AiCloudFile>().in(AiCloudFile::getId, idList));
        return success(ret);
    }

    //@PreAuthorize("hasAuthority('ai:aiCloudFile:save')")
    @Operation(summary = "添加AI云文件表")
    @PostMapping()
    public ApiResult<?> save(@RequestBody AiCloudFile aiCloudFile) {
        User loginUser = getLoginUser();
        if (loginUser != null) {
            aiCloudFile.setUserId(loginUser.getUserId());
        }
        if (aiCloudFileService.save(aiCloudFile)) {
            return success("添加成功");
        }
        return fail("添加失败");
    }

    //@PreAuthorize("hasAuthority('ai:aiCloudFile:update')")
    @Operation(summary = "修改AI云文件表")
    @PutMapping()
    public ApiResult<?> update(@RequestBody AiCloudFile aiCloudFile) {
        if (aiCloudFileService.updateById(aiCloudFile)) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    //@PreAuthorize("hasAuthority('ai:aiCloudFile:remove')")
    @Operation(summary = "删除AI云文件表")
    @DeleteMapping("/{id}")
    public ApiResult<?> remove(@PathVariable("id") Integer id) {
        if (aiCloudFileService.removeFileWithCloudAndIndex(id)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

    //@PreAuthorize("hasAuthority('ai:aiCloudFile:save')")
    @Operation(summary = "批量添加AI云文件表")
    @PostMapping("/batch")
    public ApiResult<?> saveBatch(@RequestBody List<AiCloudFile> list) {
        if (aiCloudFileService.saveBatch(list)) {
            return success("添加成功");
        }
        return fail("添加失败");
    }

    //@PreAuthorize("hasAuthority('ai:aiCloudFile:update')")
    @Operation(summary = "批量修改AI云文件表")
    @PutMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody BatchParam<AiCloudFile> batchParam) {
        if (batchParam.update(aiCloudFileService, "id")) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    //@PreAuthorize("hasAuthority('ai:aiCloudFile:remove')")
    @Operation(summary = "批量删除AI云文件表")
    @DeleteMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
        if (aiCloudFileService.removeFilesWithCloudAndIndex(ids)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

    @Operation(summary = "上传文档到云中心")
    @PostMapping("/uploadFiles")
    public ApiResult<?> uploadFiles(@RequestParam Integer docId, @RequestParam String categoryId, @RequestParam("files") MultipartFile[] files) {
        try {
            if (files == null || files.length == 0) {
                return fail("请选择要上传的文件");
            }

            if (files.length > 10) {
                return fail("一次最多只能上传10个文件");
            }
            
            User loginUser = getLoginUser();
            
            List<CompletableFuture<String>> futures = new ArrayList<>();
            List<String> successFiles = new ArrayList<>();
            List<String> failedFiles = new ArrayList<>();
            
            // 收集所有异步任务
            for (MultipartFile file : files) {
                if (file.isEmpty()) {
                    continue;
                }
                if (file.getSize() > 100 * 1024 * 1024) {
                    failedFiles.add(file.getOriginalFilename() + "(文件过大)");
                    continue;
                }
                
                // 调用Service层的异步方法并收集Future
                CompletableFuture<String> future = aiCloudFileService.processFileAsync(categoryId, docId, file, loginUser);
                futures.add(future);
            }
            
            // 等待所有异步任务完成
            CompletableFuture<Void> allFutures = CompletableFuture.allOf(
                futures.toArray(new CompletableFuture[0])
            );
            
            // 获取所有任务结果
            CompletableFuture<List<String>> allResults = allFutures.thenApply(v -> 
                futures.stream()
                       .map(CompletableFuture::join)
                       .collect(Collectors.toList())
            );
            
            // 等待所有任务完成并处理结果
            List<String> results = allResults.get(10, TimeUnit.MINUTES); // 设置10分钟超时
            
            List<String> fileIds = new ArrayList<>();
            // 统计成功和失败的文件
            for (int i = 0; i < futures.size(); i++) {
                CompletableFuture<String> future = futures.get(i);
                try {
                    String fileId = future.get();
                    fileIds.add(fileId);
                    successFiles.add(files[i].getOriginalFilename());
                } catch (Exception e) {
                    failedFiles.add(files[i].getOriginalFilename() + "(" + e.getCause().getMessage() + ")");
                }
            }
            
            // 构建返回消息
            StringBuilder message = new StringBuilder("文件上传完成");
            if (!successFiles.isEmpty()) {
                message.append("，成功上传: ").append(successFiles.size()).append("个");
            }
            if (!failedFiles.isEmpty()) {
                message.append("，失败: ").append(String.join("、", failedFiles));
            }
            
            // 返回前提交上传的文档到单位默认知识库
            aiCloudFileService.submitDocuments(docId, fileIds);
            
            return success(message.toString());
            
        } catch (Exception e) {
            return fail("上传失败: " + e.getMessage());
        }
    }
}