package com.ruoyi.web.controller.tool;

import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.enums.FileType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.framework.config.ServerConfig;
import com.ruoyi.invest.service.ITProjectInformationService;
import com.ruoyi.web.controller.common.CommonController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.tool.domain.TUnifyFile;
import com.ruoyi.tool.service.ITUnifyFileService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 附件Controller
 * 
 * @author ruoyi
 * @date 2024-02-23
 */
@Api(tags = "附件管理")
@RestController
@RequestMapping("/system/file")
public class TUnifyFileController extends BaseController
{
    private static final Logger log = LoggerFactory.getLogger(TUnifyFileController.class);

    @Autowired
    private ITUnifyFileService tUnifyFileService;

    @Autowired
    private ServerConfig serverConfig;

    @Autowired
    private ITProjectInformationService tProjectInformationService;

    /**
     * 查询附件列表
     */
    @ApiOperation("查询附件列表")
    @GetMapping("/list")
    public TableDataInfo list(TUnifyFile tUnifyFile)
    {
        startPage();
        List<TUnifyFile> list = tUnifyFileService.selectTUnifyFileList(tUnifyFile);
        return getDataTable(list);
    }

    /**
     * 导出附件列表
     */
    @ApiOperation("导出附件列表")
    @Log(title = "附件", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TUnifyFile tUnifyFile)
    {
        List<TUnifyFile> list = tUnifyFileService.selectTUnifyFileList(tUnifyFile);
        ExcelUtil<TUnifyFile> util = new ExcelUtil<TUnifyFile>(TUnifyFile.class);
        util.exportExcel(response, list, "附件数据");
    }

    /**
     * 获取附件详细信息
     */
    @ApiOperation("获取附件详细信息")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        return success(tUnifyFileService.selectTUnifyFileById(id));
    }

    /**
     * 新增附件
     */
    @ApiOperation("新增附件")
    @Log(title = "附件", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TUnifyFile tUnifyFile)
    {
        tUnifyFile.setCreateBy(getNickName());
        return toAjax(tUnifyFileService.insertTUnifyFile(tUnifyFile));
    }

    /**
     * 修改附件
     */
    @ApiOperation("修改附件")
    @Log(title = "附件", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TUnifyFile tUnifyFile)
    {
        return toAjax(tUnifyFileService.updateTUnifyFile(tUnifyFile));
    }

    /**
     * 删除附件
     */
    @ApiOperation("删除附件")
    @Log(title = "附件", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids)
    {
        tProjectInformationService.updateTProjectInformationByFileIds(ids);
        return toAjax(tUnifyFileService.updateTUnifyFileByIds(ids));
    }

    /**
     * 上传附件
     */
    @ApiOperation("上传附件")
    @Log(title = "附件", businessType = BusinessType.INSERT)
    @PostMapping("/uploads")
    public AjaxResult uploadFiles(List<MultipartFile> files)
    {
        try
        {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            for (MultipartFile file : files)
            {
                // 上传并返回新文件名称
                String fileName = FileUploadUtils.upload(filePath, file);
                String url = serverConfig.getUrl() + fileName;
                TUnifyFile tUnifyFile = new TUnifyFile();
                tUnifyFile.setUploadPath(url);
                tUnifyFile.setUploadName(fileName);
                tUnifyFile.setNewUploadName(FileUtils.getName(fileName));
                tUnifyFile.setUploadFormat(file.getOriginalFilename());
                tUnifyFile.setUploadType(String.valueOf(FileType.OTHER.ordinal()));//其他
                tUnifyFile.setCreateBy(getNickName());
                tUnifyFileService.insertTUnifyFile(tUnifyFile);
            }
            return  AjaxResult.success();
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

    @ApiOperation("下载")
    @GetMapping("/download/{id}")
    public void fileDownload(@PathVariable("id")String id, HttpServletResponse response, HttpServletRequest request){
        try
        {
            TUnifyFile tUnifyFile = tUnifyFileService.selectTUnifyFileById(id);

            String fileName = tUnifyFile.getNewUploadName();
            if (!FileUtils.checkAllowDownload(tUnifyFile.getNewUploadName()))
            {
                throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ",fileName));
            }
            // todo 下载文件名
            String realFileName = System.currentTimeMillis() + fileName.substring(0,fileName.indexOf("_")) + "." + tUnifyFile.getUploadFormat();
            // todo 下载地址
            String filePath = RuoYiConfig.getDownloadPath() + realFileName;
            // todo 根据原文件逻辑拷贝到下载路径
            String origFile = RuoYiConfig.getProfile() + tUnifyFile.getUploadName();
            // todo 文件拷贝至下载地址
            Files.copy(Paths.get(origFile),Paths.get(filePath), StandardCopyOption.REPLACE_EXISTING);
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, realFileName);
            FileUtils.writeBytes(filePath, response.getOutputStream());
            // todo 删除拷贝文件
            FileUtils.deleteFile(filePath);
        }
        catch (Exception e)
        {
            log.error("下载文件失败", e);
        }
    }


    /**
     * 根据附件业务ID()获取附件详情信息列表
     */
    @ApiOperation("根据附件业务ID()获取附件详情信息列表")
    @GetMapping("/listFileBusinessId")
    public AjaxResult listFileBusinessId(String fileBusinessId,String uploadType)
    {
        return success(tUnifyFileService.selectTUnifyFileByBusinessIdList(fileBusinessId,uploadType));
    }
    /**
     * 根据ID()获取附件详情信息列表
     */
    @ApiOperation("根据附件业务ID()获取附件详情信息列表")
    @GetMapping("/listFileById")
    public AjaxResult listFileById(String id,String uploadType)
    {
        return success(tUnifyFileService.selectTUnifyFileByIdList(id,uploadType));
    }
    /**
     * 根据fileId()获取项目中所有附件列表
     */
    @ApiOperation("根据fileId()获取项目中所有附件列表")
    @GetMapping("/listFileId")
    public AjaxResult listFileId(String fileId)
    {
        return success(tUnifyFileService.listFileId(fileId));
    }

}
