package com.xjrsoft.module.oss.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xjrsoft.common.annotation.XjrLog;
import com.xjrsoft.common.constant.GlobalConstant;
import com.xjrsoft.common.exception.MyException;
import com.xjrsoft.common.model.result.R;
import com.xjrsoft.module.oss.factory.OssFactory;
import com.xjrsoft.module.system.entity.File;
import com.xjrsoft.module.system.service.IFileService;
import com.xjrsoft.module.system.vo.FileVo;
import io.swagger.annotations.Api;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @Author: tzx
 * @Date: 2022/3/8 11:07
 */
@RestController
@RequestMapping(GlobalConstant.SYSTEM_MODULE_PREFIX + "/oss")
@Api(value = GlobalConstant.SYSTEM_MODULE_PREFIX + "/oss", tags = "对象存储模块")
@AllArgsConstructor
public class OssController {


    private final IFileService fileService;

    /**
     * 上传文件
     */
    @PostMapping("/upload")
    @XjrLog(value = "上传文件")
    @SneakyThrows
    public R upload(@RequestParam("file") MultipartFile file, @RequestParam(value = "folderId", required = false) Long folderId,
                    @RequestParam(value = "processId", required = false) String processId) {
        if (ObjectUtil.isNull(file)) {
            throw new MyException("上传文件不能为空");
        }

        //上传文件
        String suffix = Objects.requireNonNull(file.getOriginalFilename()).substring(file.getOriginalFilename().lastIndexOf(StringPool.DOT));
        String url = Objects.requireNonNull(OssFactory.build()).uploadSuffix(file.getBytes(), suffix);

        //保存文件信息
        File fileEntity = new File();


        Long newfolderId = IdWorker.getId();

        List<File> insertFile = new ArrayList<>();

        //如果有folder id  默认修改 上一次folderid
        if (!ObjectUtil.isNull(folderId)) {
            //找到所有原有文件id
            List<File> list = fileService.list(Wrappers.lambdaQuery(File.class).eq(File::getFolderId, folderId));

            for (File newFile : list) {
                newFile.setId(null);
                newFile.setFolderId(newfolderId);
            }

            insertFile.addAll(list);

        }

        fileEntity.setFolderId(newfolderId);
        fileEntity.setFileUrl(url);
        fileEntity.setFileType(suffix);
        fileEntity.setFileSuffiex(suffix.replace(StringPool.DOT, StringPool.EMPTY));
        fileEntity.setFileName(file.getOriginalFilename().replace(suffix, StringPool.EMPTY));
        fileEntity.setFileSize(file.getSize());

        if (GlobalConstant.imageType.contains(StringUtils.lowerCase(suffix.replace(StringPool.DOT, StringPool.EMPTY)))) {

            String thSuffix = StringPool.DOT + ImgUtil.IMAGE_TYPE_JPEG;

            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            ImgUtil.scale(file.getInputStream(), outputStream, 200, 200, null);



            byte[] thBytes = outputStream.toByteArray();

            String thUrl = Objects.requireNonNull(OssFactory.build()).uploadSuffix(thBytes, StringPool.DOT + ImgUtil.IMAGE_TYPE_JPEG);
            outputStream.close();


            fileEntity.setThUrl(thUrl);
            fileEntity.setThType(thSuffix);
            fileEntity.setThName(file.getOriginalFilename().replace(suffix, StringPool.EMPTY) + "-缩略图");
            fileEntity.setThSize(Convert.toLong(thBytes.length));

        }

        if (StrUtil.isNotBlank(processId)) {
            fileEntity.setProcessId(processId);
        }

        insertFile.add(fileEntity);
        fileService.saveBatch(insertFile);

        return R.ok(BeanUtil.toBean(fileEntity, FileVo.class));
    }

    /**
     * 上传文件
     */
    @PostMapping("/multi-upload")
    @XjrLog(value = "上传文件")
    @SneakyThrows
    public R multiUpload(@RequestParam("file") MultipartFile[] file, @RequestParam(value = "folderId", required = false) Long folderId,
                         @RequestParam(value = "processId", required = false) String processId) {
        if (ObjectUtil.isNull(file)) {
            throw new MyException("上传文件不能为空");
        }

        Long newfolderId = IdWorker.getId();

        List<File> insertFile = new ArrayList<>();

        //如果有folder id  默认修改 上一次folderid
        if (!ObjectUtil.isNull(folderId)) {
            //找到所有原有文件id
            List<File> list = fileService.list(Wrappers.lambdaQuery(File.class).eq(File::getFolderId, folderId));

            for (File newFile : list) {
                newFile.setId(null);
                newFile.setFolderId(newfolderId);
            }

            insertFile.addAll(list);

        }

        //上传文件
        List<FileVo> resultList = new ArrayList<>();
        for (MultipartFile f : file) {
            String suffix = Objects.requireNonNull(f.getOriginalFilename()).substring(f.getOriginalFilename().lastIndexOf(StringPool.DOT));
            String url = Objects.requireNonNull(OssFactory.build()).uploadSuffix(f.getBytes(), suffix);

            //保存文件信息
            Long id = IdWorker.getId();
            File fileEntity = new File();
            fileEntity.setId(id);
            fileEntity.setFolderId(newfolderId);
            fileEntity.setFileUrl(url);
            fileEntity.setFileType(suffix);
            fileEntity.setFileSuffiex(suffix.replace(StringPool.DOT, StringPool.EMPTY));
            fileEntity.setFileName(f.getOriginalFilename().replace(suffix, StringPool.EMPTY));
            fileEntity.setFileSize(f.getSize());
            if (StrUtil.isNotBlank(processId)) {
                fileEntity.setProcessId(processId);
            }

            if (GlobalConstant.imageType.contains(suffix.replace(StringPool.DOT, StringPool.EMPTY))) {

                String thSuffix = StringPool.DOT + ImgUtil.IMAGE_TYPE_JPEG;

                FileOutputStream outputStream = new FileOutputStream(Thread.currentThread().getName() + "temp.jpeg");
                ImgUtil.scale(f.getInputStream(), outputStream, 200, 200, null);

                outputStream.close();

                java.io.File thFile = new java.io.File(Thread.currentThread().getName() + "temp.jpeg");

                byte[] thBytes = FileUtil.readBytes(thFile);

                String thUrl = Objects.requireNonNull(OssFactory.build()).uploadSuffix(FileUtil.readBytes(thFile), StringPool.DOT + ImgUtil.IMAGE_TYPE_JPEG);


                fileEntity.setThUrl(thUrl);
                fileEntity.setThType(thSuffix);
                fileEntity.setThName(f.getOriginalFilename().replace(suffix, StringPool.EMPTY) + "-缩略图");
                fileEntity.setThSize(Convert.toLong(thBytes.length));

                boolean delete = thFile.delete();
            }


            insertFile.add(fileEntity);
            resultList.add(BeanUtil.toBean(fileEntity, FileVo.class));
        }

        fileService.saveBatch(insertFile);

        return R.ok(resultList);
    }
}
