package com.iformall.controller.sys;

import com.amazonaws.services.s3.model.*;
import com.iformall.annotation.SystemControllerLog;
import com.iformall.common.ErrorCode;
import com.iformall.common.ResultData;
import com.iformall.controller.base.BaseController;
import com.iformall.service.QrCodeService;
import com.iformall.utils.ImgUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
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.*;
import java.util.*;
import java.util.List;

@RestController
@RequestMapping(value = "upload")
@Api(description = "文件上传接口")
public class UploadController extends BaseController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private String fmUploadDir;

    @Autowired
    private QrCodeService qrCodeService;

    /**
     * 上传文件
     *
     * @param multiReq
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/awsFileUpload", consumes = "multipart/*", headers = "content-type=multipart/form-data")
    @ApiOperation("上传文件")
    @SystemControllerLog(description = "文件上传")
    public ResultData awsfileUpload(@RequestParam("file") MultipartFile multiReq) throws Exception {
        logger.info("[" + getIpAddr() + "] UploadController::awsfileUpload");

        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentType(multiReq.getContentType());
        metadata.setContentLength(multiReq.getSize());

        String fileName = UUID.randomUUID().toString();
        int dot = multiReq.getOriginalFilename().lastIndexOf('.');
        if (dot >= 0) {
            fileName = getTenantId() + "/" + fileName + multiReq.getOriginalFilename().substring(dot, multiReq.getOriginalFilename().length());
        } else {
            fileName = getTenantId() + "/" + fileName;
        }

        System.out.println(fileName);
        ResultData data = qrCodeService.awsUpload(multiReq.getInputStream(), metadata, fileName, getTenantId());
        return data;
    }


    /**
     * 图片上传
     *
     * @param multiReq
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/awsImgUpload", consumes = "multipart/*", headers = "content-type=multipart/form-data")
    @ApiOperation("上传图片")
    @SystemControllerLog(description = "上传图片")
    public ResultData awsImgUpload(@RequestParam("file") MultipartFile multiReq) {
        logger.info("[" + getIpAddr() + "] UploadController::awsImgUpload");
        long size = multiReq.getSize();
        final long length = 2097152;
        if (size > length) {
            return new ResultData(ErrorCode.PICTURE_SIZE_EXCEED);
        }
        String fileName = UUID.randomUUID().toString();
        String tempFileName = fileName;
        String fileFormat = "";

        int dot = multiReq.getOriginalFilename().lastIndexOf('.');
        if (dot >= 0) {
            fileFormat = multiReq.getOriginalFilename().substring(dot, multiReq.getOriginalFilename().length());
            fileName = getTenantId() + "/" + fileName + fileFormat;
        } else {
            fileName = getTenantId() + "/" + fileName;
        }

        System.out.println(fileName);

        try {
            FileOutputStream fos = null;
            String imgFormat = ImgUtil.getImgFormat(fileFormat);
            if (StringUtils.isNotBlank(imgFormat)) {
                String localImgFileName = fmUploadDir + tempFileName + "-1" + fileFormat;
                String localNewImgFileName = fmUploadDir + tempFileName + fileFormat;
                BufferedInputStream fs = null;
                File localFile = new File(localImgFileName);
                fos = new FileOutputStream(localFile);
                fs = (BufferedInputStream) multiReq.getInputStream();
                byte[] buffer = new byte[1024];
                int len = 0;
                while ((len = fs.read(buffer)) != -1) {
                    fos.write(buffer, 0, len);
                }
                fos.close();
                fs.close();
                logger.info("local file: " + localImgFileName);
                File newFile = ImgUtil.thinImage(localImgFileName, localNewImgFileName, imgFormat);
                logger.info("local new file: " + localNewImgFileName);
                // 删除本地缓存
                localFile.delete();
                ObjectMetadata metadata = new ObjectMetadata();
                metadata.setContentType(multiReq.getContentType());
                metadata.setContentLength(newFile.length());
                ResultData data = qrCodeService.awsUpload(new FileInputStream(newFile), metadata, fileName, getTenantId());
                // 删除本地缓存
                newFile.delete();
                return data;
            } else {
                ObjectMetadata metadata = new ObjectMetadata();
                metadata.setContentType(multiReq.getContentType());
                metadata.setContentLength(size);
                ResultData data = qrCodeService.awsUpload(multiReq.getInputStream(), metadata, fileName, getTenantId());
                return data;
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            return new ResultData(ErrorCode.PICTURE_ANALYZING_ERROR);
        }
    }

    /**
     * 多文件上传
     *
     * @param files
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/awsFilesUpload", consumes = "multipart/*", headers = "content-type=multipart/form-data")
    @ApiOperation("多文件上传")
    @SystemControllerLog(description = "多文件上传")
    public ResultData awsFilesUpload(@RequestParam("files") MultipartFile[] files) throws Exception {
        logger.info("[" + getIpAddr() + "] UploadController::awsFilesUpload");

        if (files.length > 0) {
            ResultData data = new ResultData();
            List<Map<String, String>> dataList = new ArrayList<Map<String, String>>();
            for (MultipartFile multipartFile : files) {
                Map<String, String> map = new HashMap<>();

                ObjectMetadata metadata = new ObjectMetadata();
                metadata.setContentType(multipartFile.getContentType());
                metadata.setContentLength(multipartFile.getSize());

                FileOutputStream fos = null;
                BufferedInputStream fs = null;

                map.put("key", multipartFile.getOriginalFilename());

                String fileName = UUID.randomUUID().toString();
                int dot = multipartFile.getOriginalFilename().lastIndexOf('.');
                if (dot >= 0) {
                    fileName = getTenantId() + "/" + fileName + multipartFile.getOriginalFilename().substring(dot, multipartFile.getOriginalFilename().length());
                } else {
                    fileName = getTenantId() + "/" + fileName;
                }

                ResultData data1 = qrCodeService.awsUpload(multipartFile.getInputStream(), metadata, fileName, getTenantId());
                if (data1.code == ResultData.SUCCESS) {
                    Map _data = (Map) data1.data;
                    map.put("url", (String) _data.get("url"));
                    dataList.add(map);
                } else {
                    // 部分成功
                    data.code = ResultData.SUCCESS;
                    data.data = dataList;
                    return data;
                }
            }
            data.code = ResultData.SUCCESS;
            data.data = dataList;
            return data;

        }
        return new ResultData();
    }

    /**
     * 内部接口-C端上传图片文件
     *
     * @param multiReq
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/cimgUpload", consumes = "multipart/*", headers = "content-type=multipart/form-data")
    @ApiOperation("内部接口-C端上传图片文件")
    public ResultData cimgUpload(@RequestParam("file") MultipartFile multiReq) throws Exception {
        logger.info("[" + getIpAddr() + "] UploadController::cimgUpload");

        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentType(multiReq.getContentType());
        metadata.setContentLength(multiReq.getSize());

        String fileName = multiReq.getOriginalFilename();
        fileName = "cimg/" + fileName;
        ResultData data = qrCodeService.awsUpload(multiReq.getInputStream(), metadata, fileName, "cimg");
        return data;
    }

}
