package com.hys.app.controller.base;

import cn.hutool.core.collection.ListUtil;
import com.hys.app.framework.exception.ResourceNotFoundException;
import com.hys.app.framework.exception.ServiceException;
import com.hys.app.framework.util.ArrayUtils;
import com.hys.app.framework.util.FileUtil;
import com.hys.app.model.base.dto.FileDTO;
import com.hys.app.model.base.vo.FileVO;
import com.hys.app.model.errorcode.SystemErrorCode;
import com.hys.app.service.base.service.FileManager;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import java.util.UUID;


/**
 * 存储方案控制器
 *
 * @author zh
 * @version v7.0.0
 * @since v7.0.0
 * 2018-03-22 10:54:47
 */
@RestController
@RequestMapping("/uploaders")
@Api(description = "上传图片api")
public class FileBaseController {

    @Autowired
    private FileManager fileManager;


    @ApiOperation(value = "文件上传", response = FileVO.class)
    @ApiImplicitParam(name = "scene", value = "业务场景", allowableValues = "goods,shop,member,other", required = true, dataType = "String", paramType = "query")
    @PostMapping
    public FileVO list(MultipartFile file, String scene) throws IOException {
        if (file != null && file.getOriginalFilename() != null) {
            //文件类型
            String contentType = file.getContentType();
            //获取文件名称
            String ext = contentType.substring(contentType.lastIndexOf("/") + 1, contentType.length());
            //如果是图片类型 则验证不允许上传超过2M
            if (FileUtil.isAllowUpImg(ext)) {
                if (!FileUtil.checkFileSize(file.getSize(), 2, "M")) {
                    throw new ServiceException(SystemErrorCode.E901.code(), "图片超过上传限制大小，请上传2M以内图片");
                }
            }
            if (!FileUtil.isAllowUpFile(ext)) {
                throw new ServiceException(SystemErrorCode.E901.code(), "不允许上传的文件格式，请上传gif,jpg,png,jpeg,mp4,pdf,mov格式文件。");
            }
            FileDTO input = new FileDTO();
            input.setName(file.getOriginalFilename());
            input.setStream(file.getInputStream());
            input.setExt(ext);
            return this.fileManager.upload(input, scene);
        } else {
            throw new ResourceNotFoundException("没有文件");
        }
    }

    @ApiOperation(value = "文件删除")
    @ApiImplicitParam(name = "file_path", value = "文件路径", required = true, dataType = "String", paramType = "query")
    @DeleteMapping
    public String delete(@ApiIgnore String filePath) {
        this.fileManager.deleteFile(filePath);
        return null;
    }


    @ApiOperation(value = "文件上传", response = FileVO.class)
    @ApiImplicitParam(name = "scene", value = "业务场景", allowableValues = "goods,shop,member,other", required = true, dataType = "String", paramType = "query")
    @PostMapping("uploadSmall")
    public FileVO uploadSmall(MultipartFile file, String scene) throws IOException {
        if (file != null && file.getOriginalFilename() != null) {
            //文件类型
            String contentType = file.getContentType();
            //获取文件名称
            String ext = contentType.substring(contentType.lastIndexOf("/") + 1, contentType.length());
            String jpg = ext.substring(contentType.lastIndexOf(".") + 1, ext.length());

            //如果是图片类型 则验证不允许上传超过2M
            if (FileUtil.isAllowUpImg(ext)) {
                if (!FileUtil.checkFileSize(file.getSize(), 2, "M")) {
                    throw new ServiceException(SystemErrorCode.E901.code(), "图片超过上传限制大小，请上传2M以内图片");
                }
            }
            if (!FileUtil.isAllowUpFile(ext)) {
                throw new ServiceException(SystemErrorCode.E901.code(), "不允许上传的文件格式，请上传gif,jpg,png,jpeg,mp4,pdf,mov格式文件。");
            }

            String fileName = file.getOriginalFilename();
            String newName = UUID.randomUUID().toString() + fileName.substring(fileName.indexOf("."));
            // 获取当前操作系统
            String osName = System.getProperties().get("os.name").toString().toLowerCase(Locale.ROOT);
            String path = "";

            if (osName.startsWith("win")) {
                path = "D:\\Test\\";
            } else {
                path = "/mnt/test";
            }
            File saveFile = new File(path + newName);
            if (!saveFile.getParentFile().exists()) {
                saveFile.getParentFile().mkdirs();
            }
            file.transferTo(saveFile);
            String path1 = saveFile.getPath();


            File inputFile = new File(path1);
            BufferedImage inputImage = ImageIO.read(inputFile);

            // 创建一个新的缓冲图片
            BufferedImage outputImage = new BufferedImage(80, 80, inputImage.getType());

            // 绘制并缩放原图片到新图片中
            outputImage.getGraphics().drawImage(inputImage.getScaledInstance(80, 80, BufferedImage.SCALE_SMOOTH), 0, 0, null);

            // 写入到输出文件
            String newNameSmall ="small"+ newName ;

            File outputFile = new File(path + newNameSmall);
            ImageIO.write(outputImage, jpg, outputFile); // 根据原图片格式选择"jpg", "png"等

            File inputFile2 = new File(path + newNameSmall);
            FileInputStream input2 = new FileInputStream(inputFile2);
            MultipartFile multipartFile2 = new MockMultipartFile("file", newName, "text/plain", input2);
            FileDTO fileDTO2 = new FileDTO();
            fileDTO2.setName(multipartFile2.getOriginalFilename());
            fileDTO2.setStream(multipartFile2.getInputStream());
            fileDTO2.setExt(ext);
            FileVO upload2 = this.fileManager.upload(fileDTO2, scene);
            upload2.setType("small");
            inputFile2.delete();
            inputFile.delete();
            return  upload2;
        } else {
            throw new ResourceNotFoundException("没有文件");
        }
    }
}
