package com.goldenwater.web.controller.gx;

import com.goldenwater.common.annotation.Anonymous;
import com.goldenwater.common.annotation.Log;
import com.goldenwater.common.config.RuoYiConfig;
import com.goldenwater.common.core.controller.BaseController;
import com.goldenwater.common.core.domain.AjaxResult;
import com.goldenwater.common.core.domain.R;
import com.goldenwater.common.utils.file.FileUtils;
import com.goldenwater.gx.domain.DocFile;
import com.goldenwater.gx.service.IDocFileService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/gx/file")
public class DocFileController extends BaseController {

    @Resource
    private IDocFileService docFileService;

    @Anonymous
    @GetMapping("/front/list/{dirId}")
    public AjaxResult frontList(@PathVariable Long dirId) {
        List<DocFile> list = docFileService.selectFileList(dirId);
        return AjaxResult.success(list);
    }

    @PreAuthorize("@ss.hasPermi('gx:file:list')")
    @GetMapping("/list/{dirId}")
    public AjaxResult list(@PathVariable Long dirId) {
        List<DocFile> list = docFileService.selectFileList(dirId);
        return AjaxResult.success(list);
    }

    @PreAuthorize("@ss.hasPermi('gx:file:query')")
    @GetMapping("/{id}")
    public AjaxResult getInfo(@PathVariable Long id) {
        return AjaxResult.success(docFileService.selectFileById(id));
    }

    @PreAuthorize("@ss.hasPermi('gx:file:upload')")
    @Log(title = "文件管理", businessType = com.goldenwater.common.enums.BusinessType.IMPORT)
    @PostMapping("/upload")
    public AjaxResult upload(@RequestParam("file") MultipartFile file, 
                             @RequestParam("dirId") Long dirId) {
        if (file.isEmpty()) {
            return AjaxResult.error("上传文件不能为空");
        }

        String originalFilename = file.getOriginalFilename();
        String fileExt = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        String fileName = UUID.randomUUID().toString() + "." + fileExt;
        
        String uploadDir = RuoYiConfig.getProfile() + "/doc/";
        File dir = new File(uploadDir);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        File dest = new File(uploadDir + fileName);
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            return AjaxResult.error("文件上传失败");
        }

        DocFile docFile = new DocFile();
        docFile.setDirId(dirId);
        docFile.setFileName(originalFilename);
        docFile.setFilePath("/doc/" + fileName);
        docFile.setFileSize(file.getSize());
        docFile.setFileType(file.getContentType());
        docFile.setFileExt(fileExt);
        docFile.setUploadBy(getUsername());
        docFile.setStatus("0");
        docFile.setCreateBy(getUsername());

        docFileService.insertFile(docFile);
        return AjaxResult.success("文件上传成功");
    }

    @Anonymous
    @GetMapping("/download/{id}")
    public void download(@PathVariable Long id, HttpServletResponse response) throws IOException {
        DocFile file = docFileService.selectFileById(id);
        if (file == null) {
            response.getWriter().write("文件不存在");
            return;
        }

        String filePath = RuoYiConfig.getProfile() + file.getFilePath();
        File f = new File(filePath);
        if (!f.exists()) {
            response.getWriter().write("文件不存在");
            return;
        }

        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Disposition", 
                "attachment; filename=" + URLEncoder.encode(file.getFileName(), StandardCharsets.UTF_8));

        FileUtils.writeBytes(filePath, response.getOutputStream());
    }

    @PreAuthorize("@ss.hasPermi('gx:file:remove')")
    @Log(title = "文件管理", businessType = com.goldenwater.common.enums.BusinessType.DELETE)
    @DeleteMapping("/{id}")
    public AjaxResult remove(@PathVariable Long id) {
        DocFile file = docFileService.selectFileById(id);
        if (file != null) {
            String filePath = RuoYiConfig.getProfile() + file.getFilePath();
            File f = new File(filePath);
            if (f.exists()) {
                f.delete();
            }
        }
        return toAjax(docFileService.deleteFileById(id));
    }
}
