/*
 * Copyright (c) 2023 codvision.com All Rights Reserved.
 */

package com.codvision.base.controller.manager;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.codvision.authcore.annotation.RequiresPermissions;
import com.codvision.authcore.bean.SysUserBean;
import com.codvision.authcore.util.AuthUtil;
import com.codvision.base.entity.FileUploadResult;
import com.codvision.base.entity.SysFile;
import com.codvision.base.enums.StorageType;
import com.codvision.base.service.ISysFileService;
import com.codvision.commoncore.common.ResponseEntity;
import com.codvision.logcore.annotation.MyLog;
import com.codvision.webcore.annotation.ApiSecret;
import com.codvision.webcore.bean.QueryPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 文件管理模块
 *
 * @author lingee
 * @date 2023/8/14
 */
@RestController
@RequestMapping("/v1/manager/sysFile")
@Api(tags = "平台管理端-文件管理模块")
public class ManagerSysFileController {

    @Resource
    private ISysFileService sysFileService;

    @PostMapping("/findAll")
    @ApiOperation(value = "分页查询文件列表", notes = "分页查询文件列表接口")
    @RequiresPermissions("sys_file_list")
    public ResponseEntity<IPage<SysFile>> findAll(@ApiParam(value = "关键字") @RequestParam(required = false) String keyword,
                                                  @RequestParam(value = "page", required = false, defaultValue = "1") int page,
                                                  @RequestParam(value = "size", required = false, defaultValue = "10") int size,
                                                  @ApiParam(value = "来源：0文件上传模块，1其他模块") @RequestParam(value = "source", required = false, defaultValue = "-1") Integer source) {
        ResponseEntity<IPage<SysFile>> response = new ResponseEntity<>();


        LambdaQueryWrapper<SysFile> queryWrapper = Wrappers.lambdaQuery();
        if (StrUtil.isNotBlank(keyword)) {
            queryWrapper.like(SysFile::getFileName, keyword);
        }
        if (source != -1) {
            queryWrapper.eq(SysFile::getSource, source);
        }
        SysUserBean sysUser = AuthUtil.getCurrentUser();
        if (ObjectUtil.isNotEmpty(sysUser)) {
            queryWrapper.eq(StrUtil.isNotBlank(sysUser.getName()), SysFile::getCreateUser, sysUser.getName());
        }
        queryWrapper.orderByDesc(SysFile::getCreateTime);

        IPage<SysFile> pageResult = sysFileService.page(new QueryPage<SysFile>(page, size).getPage(), queryWrapper);
        return response.ok().data(pageResult);
    }


    @MyLog("删除文件")
    @ApiOperation(value = "通过id删除文件管理", notes = "通过id删除文件管理")
    @DeleteMapping("/batchDel")
    @RequiresPermissions("sys_file_del")
    public ResponseEntity<String> removeById(@RequestBody List<Integer> ids) {
        ResponseEntity<String> responseEntity = new ResponseEntity<>();
        sysFileService.deleteFile(ids);
        return responseEntity.ok();
    }

    @MyLog("上传文件")
    @ApiSecret(ignore = true)
    @ApiOperation(value = "文件上传接口", notes = "统一文件上传接口")
    @PostMapping("/upload")
    public ResponseEntity<FileUploadResult> fileUpload(@RequestPart("file") MultipartFile file) {
        FileUploadResult fileUploadResult = sysFileService.uploadFile(file, null);
        return new ResponseEntity<>(fileUploadResult).ok();
    }

    @MyLog("上传oss文件")
    @ApiSecret(ignore = true)
    @PostMapping(value = "/oss/upload")
    @ApiOperation(value = "oss上传文件,默认type=1 为压缩图片，2为非图片文件", notes = "上传文件")
    @RequiresPermissions("sys_file_oss_upload")
    public ResponseEntity<FileUploadResult> upload(@RequestPart("file") MultipartFile file) throws IOException {
        FileUploadResult fileUploadResult = sysFileService.uploadFile(file, StorageType.oss);
        return new ResponseEntity<>(fileUploadResult).ok();
    }

    @MyLog("上传本地文件")
    @ApiSecret(ignore = true)
    @ApiOperation("本地上传")
    @PostMapping("/local/upload")
    @RequiresPermissions("sys_file_local_upload")
    public ResponseEntity<FileUploadResult> uploadLocal(@RequestPart("file") MultipartFile file) {
        FileUploadResult fileUploadResult = sysFileService.uploadFile(file, StorageType.local);
        return new ResponseEntity<>(fileUploadResult).ok();
    }

    @ApiSecret(ignore = true)
    @ApiOperation(value = "获取oss文件", notes = "获取oss文件接口")
    @GetMapping("/{bucket}/{fileName}")
    @RequiresPermissions("sys_file_oss_one")
    public void file(@PathVariable String bucket, @PathVariable String fileName, HttpServletResponse response) {
        sysFileService.getFile(bucket, fileName, response);
    }

    @ApiSecret(ignore = true)
    @ApiOperation(value = "下载文件接口", notes = "统一获取文件接口")
    @GetMapping("/download/{bucket}/{fileName}")
    public void download(@PathVariable String bucket,
                         @PathVariable String fileName,
                         HttpServletResponse response) {
        sysFileService.download(bucket, fileName, response);
    }

    @ApiSecret(ignore = true)
    @ApiOperation(value = "预览文件接口", notes = "统一预览文件接口")
    @GetMapping("/preview/{bucket}/{fileName}")
    public void preview(@PathVariable String bucket,
                        @PathVariable String fileName,
                        HttpServletResponse response) {
        sysFileService.preview(bucket, fileName, response);
    }
}
