package com.gic.haoban.manage.web.controller.content;

import com.gic.commons.webapi.reponse.RestResponse;
import com.gic.enterprise.api.dto.EnterpriseDTO;
import com.gic.enterprise.api.service.AccountService;
import com.gic.enterprise.api.service.EnterpriseService;
import com.gic.thirdparty.cloudfile.CloudFileUtil;
import com.gic.thirdparty.cloudfile.CmeUtil;
import com.gic.thirdparty.cloudfile.enums.CloudFileBusinessOptEnum;
import com.gic.thirdparty.cloudfile.enums.CloudFileTypeEnum;
import com.gic.thirdparty.cloudfile.pojo.CloudFileInfo;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

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

/**
 * 好办-通用
 */
@Controller
@RequestMapping("/content")
public class ContentImageController {
    private static Logger logger = LogManager.getLogger(ContentImageController.class);

    @Autowired
    private AccountService accountService;
    @Autowired
    private EnterpriseService enterpriseService;


    /**
     * 获取桶名称
     * @param fileType 文件后缀 mp4
     * @param fileFlag 视频类型 3为cme临时资源
     * @return
     */
    @RequestMapping("get-bucket")
    @ResponseBody
    public RestResponse<CloudFileInfo> getBucket(String fileType,String enterpriseId,@RequestParam(required = false)Integer fileFlag) {

        //存储空间余额校验
        if (!accountService.storageFeeCheck(enterpriseId)){
            return RestResponse.failure("-1", "存储余额不足，暂不支持图片/视频上传，请充值");
        }
        EnterpriseDTO enterpriseDTO = enterpriseService.getEnterpriseById(enterpriseId);
        CloudFileTypeEnum cloudFileTypeEnum = CloudFileTypeEnum.getFileTypeByExtension(fileType);
        CloudFileInfo cloudFileInfo = null;
        //cme上传视频走 temp存储桶只存一天有效期
        if (fileFlag != null && fileFlag == 3) {
            cloudFileInfo = CloudFileUtil.getPreUploadTempFileInfo(fileType, cloudFileTypeEnum, CmeUtil.CME_TEMP_COS, CloudFileBusinessOptEnum.MATERIAL_CONTENT, 1L);
        }else {
            cloudFileInfo = CloudFileUtil.getPreUploadFileInfo(fileType, cloudFileTypeEnum, enterpriseDTO.getFactoryCode(), CloudFileBusinessOptEnum.MATERIAL_CONTENT);
        }
        if (cloudFileInfo == null){
            return RestResponse.failure("-1", "获取桶名称失败");
        }
        return RestResponse.successResult(cloudFileInfo);
    }

    /**
     * 图片上传
     *
     * @param request
     * @param videoPicFileId 上传视频首针图片时使用
     * @param fileFlag = 1-普通图片 2-视频截取首针图片（需要与视频建立关联关系）3-cme临时资源
     * @param bucketName    存储桶名称
     * @return
     */
    @RequestMapping("upload-image")
    @ResponseBody
    public RestResponse<CloudFileInfo> uploadCloudImage(HttpServletRequest request,
                                          String enterpriseId,
                                          Integer fileFlag,
                                          String videoPicFileId,
                                          String bucketName) {
        //存储空间余额校验
        if (!accountService.storageFeeCheck(enterpriseId)){
            return RestResponse.failure("-1", "存储余额不足，暂不支持图片/视频上传，请充值");
        }
        if (fileFlag == null){
            fileFlag = 1;
        }
        if (fileFlag == 2 && StringUtils.isBlank(videoPicFileId) || fileFlag ==2 && StringUtils.isBlank(bucketName)){
            return RestResponse.failure("-1", "必传参数不能为空");
        }
        EnterpriseDTO enterpriseDTO = enterpriseService.getEnterpriseById(enterpriseId);
        if (enterpriseDTO == null) {
            return RestResponse.failure("-1", "企业不存在");
        }
        File file = null;
        try {
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            String fileName = multiRequest.getFileNames().next();
            CommonsMultipartFile multiFile = (CommonsMultipartFile) multiRequest.getMultiFileMap().get(fileName).get(0);

            long fileSize = multiFile.getSize();
            Boolean compressFlag = false;
            //大于10M压缩
            if (fileSize / 1024 / 1024 > 10) {
                compressFlag = true;
            }
            String originalFilename = multiFile.getOriginalFilename();
            String fileType = originalFilename.substring(originalFilename.lastIndexOf(".")+1).toLowerCase();
            logger.info("文件名称 originalFilename = {}", originalFilename);
            logger.info("文件类型 fileType = {}", fileType);

            if (!"JPG".equals(fileType) && !"jpg".equals(fileType) && !"PNG".equals(fileType) && !"png".equals(fileType) && !"JPEG".equals(fileType) && !"jpeg".equals(fileType)
                    && !"blob".equals(fileType)) {//blob为了解决 前端截取的视频首针是blob，兼容
                return RestResponse.failure("-1", "图片格式错误");
            }
            String prefix = ".jpg";
            if (!"blob".equals(fileType)){
                prefix = originalFilename.substring(originalFilename.lastIndexOf("."));
            }else {
                fileType = "png";
            }
            file = File.createTempFile(fileName, prefix);
            multiFile.transferTo(file);
            if (fileFlag == 1) {
                CloudFileInfo cloudFileInfo = CloudFileUtil.uploadFileNoRelation(file, fileType, CloudFileTypeEnum.IMAGE, enterpriseDTO.getFactoryCode(), CloudFileBusinessOptEnum.MATERIAL_CONTENT,compressFlag);
                return RestResponse.successResult(cloudFileInfo);
            }else if (fileFlag == 2){
                // 若是前端截取的视频首针图片，则调用新接口
                CloudFileUtil.uploadPreFileByFieldKey(file, bucketName, videoPicFileId);
            }else if (fileFlag == 3) {
                // cme临时图片只能上传到temp存储桶 只存一天有效期
                CloudFileInfo cloudFileInfo = CloudFileUtil.uploadTempFile(file, fileType, CloudFileTypeEnum.IMAGE, CmeUtil.CME_TEMP_COS, CloudFileBusinessOptEnum.MATERIAL_CONTENT, 1L,compressFlag,bucketName,videoPicFileId);
                return RestResponse.successResult(cloudFileInfo);
            }
            return RestResponse.successResult();
        } catch (Exception e) {
            logger.warn("图片上传异常", e);
            return RestResponse.failure("-1", "图片上传异常");
        } finally {
            if (file != null) {
                file.delete();
            }
        }
    }

}
