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

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.GenericResult;
import com.aliyun.oss.model.ProcessObjectRequest;
import com.aliyun.oss.model.PutObjectRequest;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.liquidnet.commons.lang.util.CollectionUtil;
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.base.ResponseDto;
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.BeanUtils;
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.Formatter;
import java.util.List;
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 = "File", name = "file", value = "文件", required = true),
            @ApiImplicitParam(type = "form", dataType = "String", name = "pathName", value = "归类的文件夹名称 比如banner上传就传 banner 返回的地址就会是bnanner/XXX", defaultValue = "other"),
            @ApiImplicitParam(type = "form", dataType = "Integer", name = "buckType", value = "buckType 1正常的任何文件上传 2apk上传", defaultValue = "1"),
            @ApiImplicitParam(type = "form", dataType = "Integer", name = "resize", value = "resize", defaultValue = "0"),
    })
    public ResponseDto<UploadVo> upload(
            @RequestParam MultipartFile file,
            @RequestParam(defaultValue = "other") String pathName,
            @RequestParam(defaultValue = "1", required = false) int buckType,
            @RequestParam(defaultValue = "0", required = false) int resize
    ) {
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

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

        // file md5
        String fileMD5 = FilesUtils.getFileMD5(fileNew);
        List<PlatformOssFiles> platformOssFiles = platformOssFilesMapper.selectList(
                Wrappers.lambdaQuery(PlatformOssFiles.class)
                        .eq(PlatformOssFiles::getMd5str, fileMD5)
        );
        UploadVo uploadVo = new UploadVo();
        if (CollectionUtils.isEmpty(platformOssFiles)) {
            String filename = file.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, fileNew);
            ossClient.putObject(putObjectRequest);
            if (resize > 0) {
                // 将图片缩放
                StringBuilder sbStyle = new StringBuilder();
                Formatter styleFormatter = new Formatter(sbStyle);
                String styleType = "image/resize,w_" + resize;
                // String styleType = "image/resize,m_fixed,w_100,h_100";
                styleFormatter.format("%s|sys/saveas,o_%s,b_%s", styleType,
                        BinaryUtil.toBase64String(uploadpath.getBytes()),
                        BinaryUtil.toBase64String(buckName.getBytes()));
                ProcessObjectRequest request = new ProcessObjectRequest(buckName, uploadpath, sbStyle.toString());
                GenericResult processResult = ossClient.processObject(request);
            }

            ossClient.shutdown();

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

            BeanUtils.copyProperties(platformOssFilesDate, uploadVo);
        } else {
            PlatformOssFiles platformOssFilesOne = platformOssFiles.get(0);
            BeanUtils.copyProperties(platformOssFilesOne, uploadVo);
        }

        FilesUtils.delteTempFile(fileNew); // 删除临时文件

        return ResponseDto.success(uploadVo);
    }

}
