package com.ruoyi.project.controller;

import java.util.Date;
import java.util.List;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.project.domain.TrsAttachment;
import com.ruoyi.project.service.ITrsAttachmentService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 智能报告Controller
 * 
 * @author ruoyi
 * @date 2025-03-30
 */
@Controller
@RequestMapping("/project/attachment")
public class TrsAttachmentController extends BaseController
{
    private String prefix = "project/attachment";

    @Autowired
    private ITrsAttachmentService trsAttachmentService;

    @RequiresPermissions("project:attachment:view")
    @GetMapping()
    public String attachment()
    {
        return prefix + "/attachment";
    }

    /**
     * 查询智能报告列表
     */
    @RequiresPermissions("project:attachment:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(TrsAttachment trsAttachment)
    {
        startPage();
        List<TrsAttachment> list = trsAttachmentService.selectTrsAttachmentList(trsAttachment);
        return getDataTable(list);
    }

    /**
     * 导出智能报告列表
     */
    @RequiresPermissions("project:attachment:export")
    @Log(title = "智能报告", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(TrsAttachment trsAttachment)
    {
        List<TrsAttachment> list = trsAttachmentService.selectTrsAttachmentList(trsAttachment);
        ExcelUtil<TrsAttachment> util = new ExcelUtil<TrsAttachment>(TrsAttachment.class);
        return util.exportExcel(list, "智能报告数据");
    }

    /**
     * 新增智能报告
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存智能报告
     */
    @Log(title = "智能报告", businessType = BusinessType.INSERT)
    @PostMapping("/upload")
    @ResponseBody
    public AjaxResult addSave(@RequestParam("file") MultipartFile file,
                              @RequestParam(required = false) String description) {
        try {
            // 基本验证
            if (file == null || file.isEmpty()) {
                return AjaxResult.error("请选择要上传的文件");
            }
            // 上传文件路径
            String filePath = FileUploadUtils.upload(file);
            filePath = filePath.replace("//", "/");
            // 获取文件原始名称
            String fileName = file.getOriginalFilename();
            // 获取文件大小
            long fileSize = file.getSize();
            // 获取文件类型
            String fileType = FileUploadUtils.getExtension(file);

            TrsAttachment attachment = new TrsAttachment();

            Long deptId = getSysUser().getDeptId();
            attachment.setDeptId(deptId);
            attachment.setUserId(getUserId());

            attachment.setFileName(fileName);
            attachment.setFilePath(filePath);
            attachment.setFileSize(fileSize);
            attachment.setFileType(fileType);
            attachment.setDescription(description);
            attachment.setTime(new Date());

            return toAjax(trsAttachmentService.insertTrsAttachment(attachment));
        } catch (Exception e) {
            return error("上传文件失败：" + e.getMessage());
        }
    }

    /**
     * 下载文件
     */
    @GetMapping("/download/{id}")
    public void download(@PathVariable("id") Long id, HttpServletResponse response, HttpServletRequest request) {
        try {
            TrsAttachment attachment = trsAttachmentService.selectTrsAttachmentById(id);
            String filePath = RuoYiConfig.getProfile()+attachment.getFilePath().substring(8, attachment.getFilePath().length());
            String fileName = attachment.getFileName();
            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition",
                    "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, fileName));
            FileUtils.writeBytes(filePath, response.getOutputStream());
        } catch (Exception e) {
            logger.error("下载文件失败", e);
        }
    }

    /**
     * 新增保存智能报告
     */
/*    @RequiresPermissions("project:attachment:add")
    @Log(title = "智能报告", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(TrsAttachment trsAttachment)
    {
        return toAjax(trsAttachmentService.insertTrsAttachment(trsAttachment));
    }*/

    /**
     * 修改智能报告
     */
    @RequiresPermissions("project:attachment:edit")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        TrsAttachment trsAttachment = trsAttachmentService.selectTrsAttachmentById(id);
        mmap.put("trsAttachment", trsAttachment);
        return prefix + "/edit";
    }

    /**
     * 修改保存智能报告
     */
    @RequiresPermissions("project:attachment:edit")
    @Log(title = "智能报告", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(TrsAttachment trsAttachment)
    {
        return toAjax(trsAttachmentService.updateTrsAttachment(trsAttachment));
    }

    /**
     * 删除智能报告
     */
    @RequiresPermissions("project:attachment:remove")
    @Log(title = "智能报告", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(trsAttachmentService.deleteTrsAttachmentByIds(ids));
    }
}
