package com.yushu.web.controller.system;

import java.util.List;
import java.util.Map;
import jakarta.servlet.http.HttpServletResponse;
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.yushu.common.annotation.Log;
import com.yushu.common.core.controller.BaseController;
import com.yushu.common.core.domain.AjaxResult;
import com.yushu.common.enums.BusinessType;
import com.yushu.system.domain.SysFileShare;
import com.yushu.system.service.ISysFileShareService;
import com.yushu.common.utils.poi.ExcelUtil;
import com.yushu.common.core.page.TableDataInfo;
import com.yushu.common.exception.ServiceException;

/**
 * 文件分享Controller
 * 
 * @author yushu
 * @date 2024-11-15
 */
@RestController
@RequestMapping("/system/file/share")
public class SysFileShareController extends BaseController
{
    @Autowired
    private ISysFileShareService sysFileShareService;

    /**
     * 查询文件分享列表
     */
    @PreAuthorize("@ss.hasPermi('system:file:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysFileShare sysFileShare)
    {
        startPage();
        List<SysFileShare> list = sysFileShareService.selectSysFileShareList(sysFileShare);
        return getDataTable(list);
    }

    /**
     * 导出文件分享列表
     */
    @PreAuthorize("@ss.hasPermi('system:file:export')")
    @Log(title = "文件分享", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysFileShare sysFileShare)
    {
        List<SysFileShare> list = sysFileShareService.selectSysFileShareList(sysFileShare);
        ExcelUtil<SysFileShare> util = new ExcelUtil<SysFileShare>(SysFileShare.class);
        util.exportExcel(response, list, "文件分享数据");
    }

    /**
     * 获取文件分享详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:file:query')")
    @GetMapping(value = "/{shareId}")
    public AjaxResult getInfo(@PathVariable("shareId") Long shareId)
    {
        return success(sysFileShareService.selectSysFileShareByShareId(shareId));
    }

    /**
     * 创建文件分享
     */
    @PreAuthorize("@ss.hasPermi('system:file:add')")
    @Log(title = "文件分享", businessType = BusinessType.INSERT)
    @PostMapping("/create")
    public AjaxResult create(
            @RequestParam Long fileId,
            @RequestParam(required = false, defaultValue = "0") Integer expireDays,
            @RequestParam(required = false, defaultValue = "false") Boolean needPassword)
    {
        SysFileShare share = sysFileShareService.createFileShare(fileId, expireDays, needPassword);
        return success(share);
    }
    
    /**
     * 创建文件夹分享
     */
    @PreAuthorize("@ss.hasPermi('system:file:add')")
    @Log(title = "文件夹分享", businessType = BusinessType.INSERT)
    @PostMapping("/createFolder")
    public AjaxResult createFolder(
            @RequestParam Long folderId,
            @RequestParam(required = false, defaultValue = "0") Integer expireDays,
            @RequestParam(required = false, defaultValue = "false") Boolean needPassword)
    {
        SysFileShare share = sysFileShareService.createFolderShare(folderId, expireDays, needPassword);
        return success(share);
    }

    /**
     * 修改文件分享
     */
    @PreAuthorize("@ss.hasPermi('system:file:edit')")
    @Log(title = "文件分享", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysFileShare sysFileShare)
    {
        return toAjax(sysFileShareService.updateSysFileShare(sysFileShare));
    }

    /**
     * 删除文件分享
     */
    @PreAuthorize("@ss.hasPermi('system:file:remove')")
    @Log(title = "文件分享", businessType = BusinessType.DELETE)
	@DeleteMapping("/{shareIds}")
    public AjaxResult remove(@PathVariable Long[] shareIds)
    {
        return toAjax(sysFileShareService.deleteSysFileShareByShareIds(shareIds));
    }
    
    /**
     * 验证分享（无需登录）
     */
    @GetMapping("/verify/{shareCode}")
    public AjaxResult verify(
            @PathVariable String shareCode,
            @RequestParam(required = false) String password)
    {
        try
        {
            SysFileShare share = sysFileShareService.verifyShare(shareCode, password);
            return success(share);
        }
        catch (Exception e)
        {
            return error(e.getMessage());
        }
    }
    
    /**
     * 获取文件的分享信息
     */
    @PreAuthorize("@ss.hasPermi('system:file:query')")
    @GetMapping("/file/{fileId}")
    public AjaxResult getByFileId(@PathVariable Long fileId)
    {
        return success(sysFileShareService.selectSysFileShareByFileId(fileId));
    }
    
    /**
     * 获取文件夹的分享信息
     */
    @PreAuthorize("@ss.hasPermi('system:file:query')")
    @GetMapping("/folder/{folderId}")
    public AjaxResult getByFolderId(@PathVariable Long folderId)
    {
        return success(sysFileShareService.selectSysFileShareByFolderId(folderId));
    }
    
    /**
     * 取消文件分享
     */
    @PreAuthorize("@ss.hasPermi('system:file:remove')")
    @Log(title = "取消文件分享", businessType = BusinessType.DELETE)
    @DeleteMapping("/cancel/{fileId}")
    public AjaxResult cancel(@PathVariable Long fileId)
    {
        return toAjax(sysFileShareService.cancelFileShare(fileId));
    }
    
    /**
     * 通过分享码下载文件（单文件分享）
     */
    @GetMapping("/download/{shareCode}")
    public void download(@PathVariable String shareCode, HttpServletResponse response)
    {
        try
        {
            sysFileShareService.downloadByShareCode(shareCode, response);
        }
        catch (Exception e)
        {
            throw new ServiceException("下载失败: " + e.getMessage());
        }
    }
    
    /**
     * 通过分享码和文件ID下载文件（文件夹分享中的单个文件）
     */
    @GetMapping("/download/{shareCode}/{fileId}")
    public void downloadFile(@PathVariable String shareCode, @PathVariable Long fileId, HttpServletResponse response)
    {
        try
        {
            sysFileShareService.downloadFileByShareCode(shareCode, fileId, response);
        }
        catch (Exception e)
        {
            throw new ServiceException("下载失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取分享文件夹下的子文件夹内容
     */
    @GetMapping("/folder/{shareCode}/{folderId}")
    public AjaxResult getFolderFiles(@PathVariable String shareCode, @PathVariable Long folderId)
    {
        return success(sysFileShareService.getShareFolderFiles(shareCode, folderId));
    }
    
    /**
     * 下载文件夹（打包成ZIP）
     */
    @GetMapping("/downloadFolder/{shareCode}/{folderId}")
    public void downloadFolder(@PathVariable String shareCode, @PathVariable Long folderId, HttpServletResponse response)
    {
        try
        {
            sysFileShareService.downloadFolderByShareCode(shareCode, folderId, response);
        }
        catch (Exception e)
        {
            throw new ServiceException("下载失败: " + e.getMessage());
        }
    }
    
    /**
     * 批量下载（打包成ZIP）
     */
    @PostMapping("/downloadBatch/{shareCode}")
    public void downloadBatch(
            @PathVariable String shareCode,
            @RequestBody Map<String, Object> params,
            HttpServletResponse response)
    {
        try
        {
            // 处理类型转换
            List<Long> fileIds = null;
            List<Long> folderIds = null;
            
            if (params.get("fileIds") != null)
            {
                fileIds = ((List<?>) params.get("fileIds")).stream()
                    .map(id -> Long.valueOf(id.toString()))
                    .collect(java.util.stream.Collectors.toList());
            }
            
            if (params.get("folderIds") != null)
            {
                folderIds = ((List<?>) params.get("folderIds")).stream()
                    .map(id -> Long.valueOf(id.toString()))
                    .collect(java.util.stream.Collectors.toList());
            }
            
            sysFileShareService.downloadBatchByShareCode(shareCode, fileIds, folderIds, response);
        }
        catch (Exception e)
        {
            throw new ServiceException("下载失败: " + e.getMessage());
        }
    }
}
