package com.fs.chat.controller;

import com.fs.ai.service.IBaiduAIService;
import com.fs.chat.domain.ChatDataset;
import com.fs.chat.domain.ChatDatasetFile;
import com.fs.chat.dto.ChatDatasetFileExportDTO;
import com.fs.chat.service.IChatDatasetFileService;
import com.fs.chat.service.IChatDatasetService;
import com.fs.common.annotation.Log;
import com.fs.common.config.FSConfig;
import com.fs.common.core.controller.BaseController;
import com.fs.common.core.domain.AjaxResult;
import com.fs.common.core.domain.R;
import com.fs.common.core.page.TableDataInfo;
import com.fs.common.enums.BusinessType;
import com.fs.common.exception.file.OssException;
import com.fs.common.utils.file.FileUploadUtils;
import com.fs.common.utils.poi.ExcelUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

/**
 * 文件Controller
 *
 * @author fs
 * @date 2024-04-21
 */
@RestController
@RequestMapping("/chat/chatDatasetFile")
public class ChatDatasetFileController extends BaseController
{
    @Autowired
    private IChatDatasetFileService chatDatasetFileService;
    @Autowired
    private IChatDatasetService chatDatasetService;
    @Autowired
    private IBaiduAIService baiduAIService;
    /**
     * 查询文件列表
     */
    @PreAuthorize("@ss.hasPermi('chat:chatDatasetFile:list')")
    @GetMapping("/list")
    public TableDataInfo list(ChatDatasetFile chatDatasetFile)
    {
        startPage();
        List<ChatDatasetFile> list = chatDatasetFileService.selectChatDatasetFileList(chatDatasetFile);
        return getDataTable(list);
    }

    /**
     * 导出文件列表
     */
    @PreAuthorize("@ss.hasPermi('chat:chatDatasetFile:export')")
    @Log(title = "文件", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(ChatDatasetFile chatDatasetFile)
    {
        List<ChatDatasetFile> list = chatDatasetFileService.selectChatDatasetFileList(chatDatasetFile);
        ExcelUtil<ChatDatasetFile> util = new ExcelUtil<ChatDatasetFile>(ChatDatasetFile.class);
        return util.exportExcel(list, "文件数据");
    }

    /**
     * 获取文件详细信息
     */
    @PreAuthorize("@ss.hasPermi('chat:chatDatasetFile:query')")
    @GetMapping(value = "/{fileId}")
    public AjaxResult getInfo(@PathVariable("fileId") Long fileId)
    {
        return AjaxResult.success(chatDatasetFileService.selectChatDatasetFileByFileId(fileId));
    }

    /**
     * 新增文件
     */
    @PreAuthorize("@ss.hasPermi('chat:chatDatasetFile:add')")
    @Log(title = "文件", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public R add(@RequestParam("file") MultipartFile file,@RequestParam Long datasetId) throws Exception {
        ChatDataset dataset=chatDatasetService.selectChatDatasetByDatasetId(datasetId);
        if (file.isEmpty())
        {
            throw new OssException("上传文件不能为空");
        }
        String originalFilename = file.getOriginalFilename();
        String fileExtension = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        if (fileExtension.equalsIgnoreCase("xls") || fileExtension.equalsIgnoreCase("xlsx")) {
            // 文件属于Excel格式
            String fileName = getFileNameWithoutExtension(originalFilename);
            ExcelUtil<ChatDatasetFileExportDTO> util = new ExcelUtil<>(ChatDatasetFileExportDTO.class);
            List<ChatDatasetFileExportDTO> list = util.importExcel(file.getInputStream());
            file = chatDatasetFileService.convertChatDatasetFileByExcel(list,fileName);
        }
        // 上传文件路径
        String filePath = FSConfig.getUploadPath();
        // 上传并返回新文件名称
        String fileName = FileUploadUtils.upload(filePath, file);
        String url =filePath + fileName.replaceAll("/profile/upload","");
        // 上传文件
        String[] documentIds =baiduAIService.addDocument(dataset.getExtId(),url);
        if(documentIds.length>0){
            ChatDatasetFile chatDatasetFile=new ChatDatasetFile();
            chatDatasetFile.setDatasetId(datasetId);
            chatDatasetFile.setFileName(file.getOriginalFilename());
            chatDatasetFile.setExtId(documentIds[0]);
            if(chatDatasetFileService.insertChatDatasetFile(chatDatasetFile)>0){
                return R.ok("操作成功");
            }
            else{
                return R.error("操作失败");
            }
        }
        else {
            return R.error("文件上传失败");
        }

    }

    /**
     * 修改文件
     */
    @PreAuthorize("@ss.hasPermi('chat:chatDatasetFile:edit')")
    @Log(title = "文件", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ChatDatasetFile chatDatasetFile)
    {
        return toAjax(chatDatasetFileService.updateChatDatasetFile(chatDatasetFile));
    }

    /**
     * 删除文件
     */
    @PreAuthorize("@ss.hasPermi('chat:chatDatasetFile:remove')")
    @Log(title = "文件", businessType = BusinessType.DELETE)
	@DeleteMapping("/{fileIds}")
    public R remove(@PathVariable Long[] fileIds)
    {
        for(Long id:fileIds){
            ChatDatasetFile file=chatDatasetFileService.selectChatDatasetFileByFileId(id);
            ChatDataset dataset=chatDatasetService.selectChatDatasetByDatasetId(file.getDatasetId());
            baiduAIService.delDocument(dataset.getExtId(),file.getExtId());

        }
        chatDatasetFileService.deleteChatDatasetFileByFileIds(fileIds);
        return R.ok();
    }

    private String getFileNameWithoutExtension(String fileName) {
        Path filePath = Paths.get(fileName);
        String nameWithExtension = filePath.getFileName().toString();
        int dotIndex = nameWithExtension.lastIndexOf(".");

        // 检查文件名是否有扩展名
        if (dotIndex > 0 && dotIndex < nameWithExtension.length() - 1) {
            return nameWithExtension.substring(0, dotIndex);
        }

        return nameWithExtension;
    }
}
