package com.jd.lightapplication.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jd.lightapplication.common.lang.R;
import com.jd.lightapplication.model.UploadRecord;
import com.jd.lightapplication.model.dto.UploadDto;
import com.jd.lightapplication.service.UploadRecordService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;


@Slf4j
@RestController()
@RequestMapping("/api/upload/record")
@Api(tags = "文件上传记录")
public class UploadRecordController {

    @Resource
    private UploadRecordService uploadRecordService;

    @GetMapping("/list")
    @ApiOperation(value = "1、分页查询")
    public R queryPageBean(Page page) {
        LambdaQueryWrapper<UploadRecord> wrapper = new LambdaQueryWrapper();
        wrapper.eq(UploadRecord::getFileType, 10);//只查图片回传的文件记录，筛选条件：文件类型为10
        return R.success(uploadRecordService.page(page, wrapper));
    }

    @PostMapping("/deleteById")
    @ApiOperation(value = "2、删除")
    public R deleteById(long id) {
        uploadRecordService.removeById(id);
        return R.success();
    }

    @PostMapping("/upload")
    @ApiOperation(value = "3、文件上传")
    public R upload(@RequestParam("file") MultipartFile file, UploadDto uploadDto) {
        if (!this.isImageFile(file)) {
            throw new RuntimeException("请上传正确的图片。");
        }
        return R.success(uploadRecordService.upload(file, uploadDto));
    }

    private boolean isImageFile(MultipartFile multipartFile) {
        BufferedImage bufferedImage = null;
        try {
            InputStream inputStream = multipartFile.getInputStream();
            bufferedImage = ImageIO.read(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bufferedImage != null;
    }
}