package com.tzld.piaoquan.api.controller;

import com.alibaba.fastjson.JSON;
import com.stuuudy.commons.external.filestorage.enums.EnumPublicBuckets;
import com.tzld.piaoquan.api.common.enums.ExceptionEnum;
import com.tzld.piaoquan.api.common.exception.CommonException;
import com.tzld.piaoquan.api.config.AliOssConfig;
import com.tzld.piaoquan.api.model.param.FileUploadParam;
import com.tzld.piaoquan.api.model.param.OssUploadSignParam;
import com.tzld.piaoquan.api.model.param.contentplatform.StsTokenParam;
import com.tzld.piaoquan.api.model.vo.FileInfo;
import com.tzld.piaoquan.api.model.vo.SignatureVO;
import com.tzld.piaoquan.api.model.vo.StsTokenVO;
import com.tzld.piaoquan.api.util.AliOssFileTool;
import com.tzld.piaoquan.growth.common.common.base.CommonResponse;
import com.tzld.piaoquan.growth.common.utils.RandomUtil;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@RestController
@RequestMapping("/file")
@Slf4j
public class FileController {

    @CrossOrigin(origins = "*")
    @PostMapping("/upload")
    public CommonResponse<FileInfo> fileUpload(@Validated FileUploadParam param, BindingResult bindingResult) throws IOException {
        if (bindingResult.hasErrors()) {
            return CommonResponse.create(ExceptionEnum.PARAM_ERROR.getCode(), bindingResult.getAllErrors().get(0).getDefaultMessage());
        }
        if (StringUtils.isBlank(param.getFileUri())) {
            String fileName = param.getFile().getOriginalFilename();
            // 获取文件名中的文件类型
            if (StringUtils.isBlank(fileName)) {
                param.setFileUri("temp/" + System.currentTimeMillis() + "_" + RandomUtil.generate18String());
            } else {
                String fileType = fileName.substring(fileName.lastIndexOf("."));
                param.setFileUri("temp/" + System.currentTimeMillis() + "_" + RandomUtil.generate18String() + fileType);
            }
        }
        String fileUrl = AliOssFileTool.saveInPublicReturnHost(param.getFile().getInputStream(),
                EnumPublicBuckets.PUBBUCKET, param.getFileUri(), param.getFileType());
        FileInfo fileInfo = new FileInfo();
        fileInfo.setFileUrl(fileUrl);
        String bucketName = AliOssConfig.getBucket(EnumPublicBuckets.PUBBUCKET.getBucketName());
        boolean isExistFile = AliOssFileTool.getOssClient().doesObjectExist(bucketName, param.getFileUri());
        if (!isExistFile) {
            throw new CommonException(ExceptionEnum.PARAM_ERROR.getCode(), "上传文件不存在！！");
        }
        return CommonResponse.create(fileInfo);
    }

    @CrossOrigin(origins = "*")
    @PostMapping("/signature")
    @ApiOperation(value = "获取签名")
    public CommonResponse<SignatureVO> signature(@Validated OssUploadSignParam ossUploadSignParam) {
        log.info("获取OSS签名失败 param" + JSON.toJSONString(ossUploadSignParam));
        SignatureVO signatureVO;
        try {
            signatureVO = AliOssFileTool.getUploadPolicy(ossUploadSignParam.getFileType());
        } catch (Exception e) {
            log.error("获取OSS签名失败", e);
            return CommonResponse.create(ExceptionEnum.SYSTEM_ERROR.getCode(), "获取OSS签名失败");
        }
        return CommonResponse.success(signatureVO);
    }

    /**
     * 尽量控制前端获取oss权限，降低安全风险
     * 有效期为15分钟，getStsToken接口为1小时
     *
     * @param stsTokenParam
     * @param request
     * @return
     * @throws Exception
     */
    @CrossOrigin(origins = "*")
    @PostMapping("/getTempStsToken")
    @ApiOperation(value = "获取STS临时令牌")
    public CommonResponse<StsTokenVO> getTempStsToken(StsTokenParam stsTokenParam, HttpServletRequest request) throws Exception {
        log.info("获取STS临时令牌 param" + JSON.toJSONString(stsTokenParam));
        StsTokenVO stsTokenVO;
        try {
            String fileName = AliOssFileTool.getRandomObjectKey(stsTokenParam.getFileType());
            stsTokenVO = AliOssFileTool.getStsToken(fileName, 15 * 60L);
        } catch (Exception e) {
            log.error("获取STS临时令牌", e);
            return CommonResponse.create(ExceptionEnum.SYSTEM_ERROR.getCode(), "获取STS临时令牌失败");
        }
        return CommonResponse.success(stsTokenVO);
    }
}
