package com.liquidnet.service.platform.controller.basicServices;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.liquidnet.commons.lang.util.DateUtil;
import com.liquidnet.commons.lang.util.FilesUtils;
import com.liquidnet.commons.lang.util.IDGenerator;
import com.liquidnet.service.kylin.dto.vo.basicServices.UploadVo;
import com.liquidnet.service.kylin.entity.PlatformOssFiles;
import com.liquidnet.service.kylin.mapper.PlatformOssFilesMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.time.LocalDateTime;
import java.util.UUID;

/**
 * <p>
 * 阿里云上传
 * </p>
 *
 * @author jiangxiulong
 * @since 2021-07-09
 */

@Api(tags = "basicServices")
@RestController
@RequestMapping("basicServices/alOss")
public class AlOssController {

    @Value("${liquidnet.al-oss.endpoint}")
    private String endpoint;
    @Value("${liquidnet.al-oss.accessKeyId}")
    private String accessKeyId;
    @Value("${liquidnet.al-oss.accessKeySecret}")
    private String accessKeySecret;

    @Autowired
    private PlatformOssFilesMapper platformOssFilesMapper;

    @PostMapping("/upload")
    @ApiOperation("阿里云上传")
    @ApiImplicitParams({
            @ApiImplicitParam(type = "form", dataType = "MultipartFile", name = "files", value = "文件", required = true),
            @ApiImplicitParam(type = "query", dataType = "String", name = "pathName", value = "归类的文件夹名称 比如banner上传就传 banner 返回的地址就会是bnanner/XXX", required = true),
            @ApiImplicitParam(type = "query", dataType = "Integer", name = "buckType", value = "buckType 1正常的任何文件上传 2apk上传", required = true),
    })
    public UploadVo upload(@RequestParam MultipartFile files, @RequestParam String pathName, @RequestParam Integer buckType) {
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        File file = null;
        try {
            file = FilesUtils.multipartFileToFile(files);
        } catch (Exception e) {
            return null;
        }

        // file md5
        String fileMD5 = FilesUtils.getFileMD5(file);
        PlatformOssFiles platformOssFiles = platformOssFilesMapper.selectOne(Wrappers.lambdaQuery(PlatformOssFiles.class).eq(PlatformOssFiles::getMd5str, fileMD5));
        if (null != platformOssFiles) {
            UploadVo uploadVo = new UploadVo();
            uploadVo.setOssPath(platformOssFiles.getOssPath());
            uploadVo.setSize(platformOssFiles.getSize());
            uploadVo.setContentType(platformOssFiles.getContentType());
            return uploadVo;
        }

        String filename = files.getResource().getFilename();// time.jpeg
        //这里文件名用了uuid 防止重复，可以根据自己的需要来写
        String uploadName = UUID.randomUUID() + filename.substring(filename.lastIndexOf("."));// 078a77e0-cf80-481b-824c-5935247cff15.jpeg
        uploadName = uploadName.replace("-", "");// 078a77e0cf80481b824c5935247cff15.jpeg
        String uploadpath = pathName + "/" + DateUtil.format(LocalDateTime.now(), DateUtil.Formatter.yyyy_MM_dd2) + "/" + uploadName;
        String buckName = "img-zhengzai-tv";
        if (2 == buckType) {
            buckName = "app-zhengzai-tv";
        }
        PutObjectRequest putObjectRequest = new PutObjectRequest(buckName, uploadpath, file);
        ossClient.putObject(putObjectRequest);

        ossClient.shutdown();
        FilesUtils.delteTempFile(file); // 删除临时文件

        // 入库
        PlatformOssFiles platformOssFilesDate = new PlatformOssFiles();
        String ossFilesId = IDGenerator.nextSnowId();
        platformOssFilesDate.setOssFilesId(ossFilesId);
        platformOssFilesDate.setOssPath(uploadpath);
        platformOssFilesDate.setFileName(filename);
        platformOssFilesDate.setContentType(files.getContentType());
        platformOssFilesDate.setSize((int) files.getSize());
        platformOssFilesDate.setMd5str(fileMD5);
        platformOssFilesDate.setCreatedAt(DateUtil.getNowTime());
        platformOssFilesMapper.insert(platformOssFilesDate);

        // 返回值
        UploadVo uploadVo = new UploadVo();
        uploadVo.setOssPath(platformOssFilesDate.getOssPath());
        uploadVo.setSize(platformOssFilesDate.getSize());
        uploadVo.setContentType(platformOssFilesDate.getContentType());
        return uploadVo;
    }

}
