package com.ruoyi.interfaces.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.interfaces.core.page.Page;
import com.ruoyi.interfaces.core.page.PageParam;
import com.ruoyi.interfaces.core.page.PageUtils;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.interfaces.domain.PtFile;
import com.ruoyi.interfaces.service.PtFileService;
import io.swagger.annotations.ApiOperation;

import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.DecimalFormat;

/**
 * @author
 * @date 2022-1-25
 */
@RestController
@RequestMapping("/pt/file")
public class PtFileController extends BaseController {

    private final PtFileService ptFileService;

    public PtFileController(PtFileService ptFileService) {
        this.ptFileService = ptFileService;
    }

    /**
     * 文件上传
     */
    @Log(title = "文件上传", businessType = BusinessType.UPDATE)
    @PostMapping("/upload")
    public AjaxResult avatar(@RequestParam MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            return AjaxResult.success();
        }
        /* 第一步：写入文件 */
        String uuid = IdUtils.simpleUUID();
        DecimalFormat df = new DecimalFormat("0.0");
        String fileSize = df.format((float) file.getSize() / 1024) + "kb";
        String fileName = file.getOriginalFilename();
        assert fileName != null;
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
        String avatar = FileUploadUtils.upload(RuoYiConfig.getUploadPath(), file);
        /* 第二步：写入数据库 */
        PtFile ptFile = new PtFile();
        ptFile.setId(uuid);
        ptFile.setName(fileName);
        ptFile.setType(suffix);
        ptFile.setPath(avatar);
        ptFile.setSize(fileSize);
        ptFileService.insert(ptFile);
        return AjaxResult.success(ptFile);
    }

    @ApiOperation("根据ID删除文档")
    @RequestMapping(value = "delete/{id}", method = RequestMethod.GET)
    public AjaxResult delete(@PathVariable String id) {
        int ret = ptFileService.delete(id);
        return AjaxResult.success();
    }

    @ApiOperation("根据ID获取文档（单表）")
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public AjaxResult get(@PathVariable String id) {
        PtFile ptFile = ptFileService.get(id);
        return AjaxResult.success(ptFile);
    }

    @ApiOperation("文档(分页)")
    @PostMapping("pageList")
    public Page pageList(@RequestBody PageParam<PtFile> pageParam) {
        return PageUtils.convert(ptFileService.findPageInfo(pageParam));
    }

}
