package com.ruoyi.cms.controller.app;

import com.ruoyi.cms.util.IdGenerator;
import com.ruoyi.cms.util.ProxyServerUtil;
import com.ruoyi.common.core.domain.entity.File;
import com.ruoyi.cms.service.IFileService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.SiteSecurityUtils;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/app/file")
public class AppFileController extends BaseController {
    @Autowired
    private IFileService fileService;
    @Autowired
    private IdGenerator idGenerator;

    @ApiOperation("上传文件")
    @PostMapping("/upload")
    public AjaxResult upload(@RequestParam("file") MultipartFile file, @RequestParam(value = "bussinessid",required = false) Long bussinessId) {
       if(!(SiteSecurityUtils.isLogin() || SecurityUtils.isLogin())){
            return AjaxResult.error("未登录，请登录后在上传文件!");
       }
        return fileService.upload(file,bussinessId);
    }

    @ApiOperation("获取附件列表")
    @GetMapping("/list")
    public TableDataInfo list(File file)
    {
        List<File> results = fileService.selectFileList(file);
        return getDataTable(results);
    }

    @ApiOperation("删除附件")
    @DeleteMapping("/{id}")
    public AjaxResult remove(@PathVariable Long id)
    {
        return toAjax(fileService.deleteFileByIds(new Long[]{id}));
    }

    @ApiOperation("上传文件")
    @PostMapping("/uploadFile")
    public AjaxResult uploadFile(@RequestParam("file") MultipartFile file, @RequestParam(value = "bussinessid",required = false) Long bussinessId, HttpServletRequest request) {
        String proxyServer = ProxyServerUtil.getProxyServer(request);
        System.out.println("获取服务器地址======================"+proxyServer);
        if(!(SiteSecurityUtils.isLogin() || SecurityUtils.isLogin())){
            return AjaxResult.error("未登录，请登录后在上传文件!");
        }
        if(bussinessId==null){
            bussinessId=idGenerator.generateId();
        }
        return fileService.uploadFile(file,bussinessId,request);
    }
}
