package com.ruoyi.project.controller;

import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.multipart.MultipartFile;

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.RequestParam;
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.project.domain.BizDoc;
import com.ruoyi.project.service.IBizDocService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.models.domain.BizModule;
import com.ruoyi.models.service.IBizModuleService;
import com.ruoyi.project.domain.BizProject;
import com.ruoyi.project.service.IBizProjectService;
import com.ruoyi.common.utils.StringUtils;
import java.net.URLEncoder;

/**
 * 文档Controller
 * 
 * @author ruoyi
 * @date 2025-08-28
 */
@RestController
@RequestMapping("/project/doc")
public class BizDocController extends BaseController
{
    @Autowired
    private IBizDocService bizDocService;

    @Autowired
    private IBizProjectService bizProjectService;

    @Autowired
    private IBizModuleService bizModuleService;

    /**
     * 查询文档列表
     */
    @PreAuthorize("@ss.hasPermi('project:doc:list')")
    @GetMapping("/list")
    public TableDataInfo list(BizDoc bizDoc)
    {
        startPage();
        List<BizDoc> list = bizDocService.selectBizDocList(bizDoc);
        return getDataTable(list);
    }

    /**
     * 根据项目ID查询文档列表
     */
    @PreAuthorize("@ss.hasPermi('project:doc:list')")
    @GetMapping("/project/{projectId}")
    public TableDataInfo listByProject(@PathVariable Long projectId, BizDoc bizDoc)
    {
        bizDoc.setProjectId(projectId);
        bizDoc.setKindType("0"); // 项目文档
        startPage();
        List<BizDoc> list = bizDocService.selectBizDocList(bizDoc);
        return getDataTable(list);
    }

    /**
     * 根据模块ID查询文档列表
     */
    @PreAuthorize("@ss.hasPermi('project:doc:list')")
    @GetMapping("/module/{moduleId}")
    public TableDataInfo listByModule(@PathVariable Long moduleId, BizDoc bizDoc)
    {
        bizDoc.setModuleId(moduleId);
        bizDoc.setKindType("1"); // 模块文档
        startPage();
        List<BizDoc> list = bizDocService.selectBizDocList(bizDoc);
        return getDataTable(list);
    }

    /**
     * 导出文档列表
     */
    @PreAuthorize("@ss.hasPermi('project:doc:export')")
    @Log(title = "文档", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BizDoc bizDoc)
    {
        List<BizDoc> list = bizDocService.selectBizDocList(bizDoc);
        ExcelUtil<BizDoc> util = new ExcelUtil<BizDoc>(BizDoc.class);
        util.exportExcel(response, list, "文档数据");
    }

    /**
     * 获取文档详细信息
     */
    @PreAuthorize("@ss.hasPermi('project:doc:query')")
    @GetMapping(value = "/{docId}")
    public AjaxResult getInfo(@PathVariable("docId") Long docId)
    {
        return success(bizDocService.selectBizDocByDocId(docId));
    }

    /**
     * 新增文档
     */
    @PreAuthorize("@ss.hasPermi('project:doc:add')")
    @Log(title = "文档", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BizDoc bizDoc)
    {
        return toAjax(bizDocService.insertBizDoc(bizDoc));
    }

    /**
     * 修改文档
     */
    @PreAuthorize("@ss.hasPermi('project:doc:edit')")
    @Log(title = "文档", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BizDoc bizDoc)
    {
        return toAjax(bizDocService.updateBizDoc(bizDoc));
    }

    /**
     * 删除文档
     */
    @PreAuthorize("@ss.hasPermi('project:doc:remove')")
    @Log(title = "文档", businessType = BusinessType.DELETE)
	@DeleteMapping("/{docIds}")
    public AjaxResult remove(@PathVariable Long[] docIds)
    {
        return toAjax(bizDocService.deleteBizDocByDocIds(docIds));
    }

    /**
     * 上传文档
     */
    @PreAuthorize("@ss.hasPermi('project:doc:add') or @ss.hasPermi('project:doc:upload')")
    @Log(title = "文档", businessType = BusinessType.INSERT)
    @PostMapping("/upload")
    public AjaxResult uploadDoc(@RequestParam("file") MultipartFile file,
                               @RequestParam("projectId") Long projectId,
                               @RequestParam(value = "moduleId", required = false) Long moduleId,
                               @RequestParam("kindType") String kindType) {

        Long currentUserId = getUserId();

        if ("0".equals(kindType)) {
            // 项目文档：只有项目管理员可以上传
            BizProject project = bizProjectService.selectBizProjectByProjectId(projectId);
            if (!project.getOwnerId().equals(currentUserId)) {
                return AjaxResult.error("无权上传项目文档");
            }
        } else if ("1".equals(kindType)) {
            // 模块文档：只有被指派该模块的用户可以上传
            BizModule module = bizModuleService.selectBizModuleByModuleId(moduleId);
            if (!String.valueOf(currentUserId).equals(module.getAssignee())) {
                return AjaxResult.error("无权上传此模块文档");
            }
        }

        try {
            // 利用通用上传接口能力保存文件
            // 记录到业务表 biz_doc（包含文件内容）
            BizDoc doc = new BizDoc();
            doc.setProjectId(projectId);
            if ("1".equals(kindType)) {
                doc.setModuleId(moduleId);
            }
            doc.setDocName(file.getOriginalFilename());
            doc.setDocPath("/profile/upload/inline");
            doc.setDocContent(file.getBytes());
            doc.setCreateBy(getUsername());
            doc.setKindType(kindType);
            bizDocService.insertBizDoc(doc);
            return AjaxResult.success("上传成功");
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 下载文档
     */
    @PreAuthorize("@ss.hasPermi('project:doc:download')")
    @Log(title = "文档", businessType = BusinessType.EXPORT)
    @GetMapping("/download/{docId}")
    public void download(@PathVariable Long docId, HttpServletResponse response) {
        BizDoc doc = bizDocService.selectBizDocByDocId(docId);
        if (doc == null) {
            return;
        }
        try {
            String fileName = doc.getDocName();
            if (StringUtils.isEmpty(fileName)) {
                fileName = "file";
            }
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            if (doc.getDocContent() != null) {
                response.getOutputStream().write(doc.getDocContent());
            }
        } catch (Exception ignored) {
        }
    }
}