package com.ruoyi.interfaces.controller;

import com.github.pagehelper.PageHelper;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.exception.CheckException;
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.PtServiceFile;
import com.ruoyi.interfaces.service.PtServiceFileService;
import io.swagger.annotations.ApiOperation;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.List;
import java.util.Optional;

/**
 * @author weking
 * @date 2019-3-22
 */
@RestController
@RequestMapping("/pt/service/file")
public class PtServiceFileController extends BaseController {

    private final PtServiceFileService ptServiceFileService;

    @Autowired
    public PtServiceFileController(PtServiceFileService ptServiceFileService) {
        this.ptServiceFileService = ptServiceFileService;
    }

    @ApiOperation("添加数据")
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public AjaxResult insert(@RequestParam("file") MultipartFile file, PtServiceFile ptServiceFile, HttpServletRequest request) throws IOException {
        String uuid = IdUtils.simpleUUID();
        String srvId = request.getParameter("srvId");
        Optional.ofNullable(srvId).orElseThrow(() -> new CheckException("srvId.no"));
        /* 第一步：写入文件 */
        // 格式化小数，不足的补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.getServiceFilePath(), file);

        /* 第二步：写入数据库 */
        ptServiceFile.setFileId(uuid);
        ptServiceFile.setFileType(suffix);
        ptServiceFile.setFilePath(path);
        ptServiceFile.setFileViewname(fileName);
        ptServiceFile.setFileSize(fileSize);
        ptServiceFile.setRelId(srvId);
        int ret = ptServiceFileService.insert(ptServiceFile);
        return AjaxResult.check(ret > 0);
    }

    @ApiOperation("数据列表")
    @RequestMapping(value = "/list")
    public Page list(PageParam<PtServiceFile> ptServiceFilePageParam) {
        PageHelper.startPage(ptServiceFilePageParam);
        // PageHelper.orderBy("CATE_ID desc");
        List<PtServiceFile> queryResult = ptServiceFileService.selectByPrimaryKey(ptServiceFilePageParam.getData());
        return PageUtils.convert(queryResult);
    }

    @ApiOperation("数据列表")
    @RequestMapping(value = "/list/{srvId}")
    public Page listBySrvId(@PathVariable("srvId") String srvId, PageParam<PtServiceFile> ptServiceFilePageParam) {
        PageHelper.startPage(ptServiceFilePageParam);
        PageHelper.orderBy(" FILE_TIME DESC ");
        PtServiceFile file = Optional.ofNullable(ptServiceFilePageParam.getData()).orElse(new PtServiceFile());
        file.setRelId(srvId);
        List<PtServiceFile> queryResult = ptServiceFileService.selectByPrimaryKey(file);
        return PageUtils.convert(queryResult);
    }

    @ApiOperation("根据主键获取数据")
    @RequestMapping(value = "/get", method = RequestMethod.GET)
    public AjaxResult get(PtServiceFile ptServiceFile) {
        List<PtServiceFile> ptServiceFileList = ptServiceFileService.selectByPrimaryKey(ptServiceFile);
        if (ptServiceFileList.get(0) == null) {
            return AjaxResult.error("未找到相关数据！");
        } else {
            return AjaxResult.success(ptServiceFileList.get(0));
        }
    }

    @ApiOperation("根据主键更新数据")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public AjaxResult update(PtServiceFile ptServiceFile) {
        int ret = ptServiceFileService.updateByPrimaryKey(ptServiceFile);
        return ret > 0 ? AjaxResult.success() : AjaxResult.error();
    }

    @ApiOperation("根据主键删除数据")
    @RequestMapping(value = "/delete/{keys}", method = RequestMethod.GET)
    public AjaxResult delete(@PathVariable("keys") String keys) {
        String[] idArr = keys.split(",");
        for (String idStr : idArr) {
            ptServiceFileService.deleteByPrimaryKey(idStr);
        }
        return AjaxResult.success();
    }

}
