package com.youlai.boot.system.controller;


import com.youlai.boot.common.result.Result;
import com.youlai.boot.common.util.SystemUtil;
import com.youlai.boot.system.mapper.DemandFileMapper;
import com.youlai.boot.system.model.entity.DemandFile;
import com.youlai.boot.system.model.entity.Record;
import com.youlai.boot.system.service.ConfigService;
import com.youlai.boot.system.service.DemandFileService;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Objects;

import static com.youlai.boot.common.util.SystemUtil.downloadFile;

@RestController
@RequestMapping("/api/v1/demand-file")
@RequiredArgsConstructor
@Slf4j
public class DemandFileController {


    private final DemandFileService demandFileService;



    @GetMapping("/get/{demandId}")
    public Result<List<DemandFile>> getDemandFileList(@PathVariable Long demandId) {
        List<DemandFile> byDemandId = demandFileService.findByDemandId(demandId);
        return Result.success(byDemandId);
    }


    @DeleteMapping("/delete/{id}")
    public Result deleteDemandFile(@PathVariable Long id) {
        int i = demandFileService.getBaseMapper().deleteById(id);
        return Result.success(i);
    }

    @PostMapping("/add/{demandId}")
    public Result addDemandFile(@PathVariable Long demandId, @RequestParam("file") MultipartFile file) {

        if (file.isEmpty()) {
            return Result.failed("文件不能为空！");
        }
        String absPath = demandFileService.saveDemandFile(file, demandId);
        return Result.success(absPath);
    }

    @GetMapping("/download/{id}")
    public void download(@PathVariable Long id, HttpServletResponse response)  {
        DemandFile demandFile = demandFileService.getById(id);
        String path = demandFile.getFilePath();
        downloadFile(path, response);
    }
}
