package com.ruoyi.interfaces.controller;

import com.ruoyi.common.config.RuoYiConfig;
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.PtHelpFile;
import com.ruoyi.interfaces.service.PtHelpFileService;
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/helpFile")
public class PtHelpFileController extends BaseController {

    private final PtHelpFileService ptHelpFileService;

    public PtHelpFileController(PtHelpFileService ptHelpFileService) {
        this.ptHelpFileService = ptHelpFileService;
    }

    @ApiOperation("修改帮助文档")
    @RequestMapping(value = "", method = RequestMethod.POST)
    public AjaxResult insert(@RequestParam("file") MultipartFile file, PtHelpFile ptHelpFile) throws IOException {
        String uuid = IdUtils.simpleUUID();
        /* 第一步：写入文件 */
        //格式化小数，不足的补0
        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 path = FileUploadUtils.upload(RuoYiConfig.getUploadPath(), file);

        /* 第二步：写入数据库 */
        ptHelpFile.setId(uuid);
        ptHelpFile.setSaveName(uuid);
        ptHelpFile.setType(suffix);
        ptHelpFile.setPath(path);
        ptHelpFile.setName(fileName);
        ptHelpFile.setSize(fileSize);
        return AjaxResult.check(ptHelpFileService.insert(ptHelpFile) > 0, ptHelpFile);
    }

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

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

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

}
