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

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.haoban.common.anno.IgnoreLogin;
import com.gic.haoban.common.utils.HaobanResponse;
import com.gic.haoban.common.utils.UploadUtils;
import com.gic.haoban.manage.web.errCode.HaoBanErrCode;
import com.gic.thirdparty.api.service.QQCloudPicService;
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 com.gic.thirdparty.cloudfile.pojo.ImageCloudFileInfo;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.springframework.beans.factory.annotation.Autowired;
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.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.InputStream;
import java.util.*;

@RestController
public class UploadController extends WebBaseController {
    private static org.apache.logging.log4j.Logger logger = LogManager.getLogger(UploadController.class);
    @Autowired
    private AccountService accountService;
    @Autowired
    private EnterpriseService enterpriseService ;

    /**
     * 获取桶名称
     * @param fileType 文件后缀 mp4、jpg....
     * @param fileFlag 视频类型 3为cme临时资源  - 此字段保持原来业务
     * @param tempFlag 是否临时文件,1是0否
     * @return
     */
    @RequestMapping("get-bucket")
    @ResponseBody
    public RestResponse<CloudFileInfo> getBucket(String fileType,String enterpriseId, @RequestParam(required = false)Integer fileFlag , String businessType , @RequestParam(defaultValue = "0") int tempFlag) {
        CloudFileBusinessOptEnum businessOptEnum = null ;
        // 天
        Long timeOut = null ;
        if(StringUtils.isBlank(businessType)) {
            businessType = "material_content" ;
        }
        // 内容中心
        if("material_content".equals(businessType)) {
            //存储空间余额校验
            if (!accountService.storageFeeCheck(enterpriseId)){
                return RestResponse.failure("-1", "存储余额不足，暂不支持图片/视频上传，请充值");
            }
            businessOptEnum = CloudFileBusinessOptEnum.MATERIAL_CONTENT ;
        }else if("haoban".equals(businessType)) {
            // 好办
            if(tempFlag==0) {
                businessOptEnum = CloudFileBusinessOptEnum.HAOBAN_COMMON ;
            }else {
                businessOptEnum = CloudFileBusinessOptEnum.COMMON ;
                timeOut = 7L ;
            }
        }
        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 {
            EnterpriseDTO enterpriseDTO = enterpriseService.getEnterpriseById(enterpriseId);
            cloudFileInfo = CloudFileUtil.getPreUploadTempFileInfo(fileType, cloudFileTypeEnum, enterpriseDTO.getFactoryCode(), businessOptEnum,timeOut);
        }
        if (cloudFileInfo == null){
            return RestResponse.failure("-1", "获取桶名称失败");
        }
        return RestResponse.successResult(cloudFileInfo);
    }


    @RequestMapping("upload-img")
    @IgnoreLogin
    public HaobanResponse imgUpload(HttpServletRequest request,String enterpriseId) throws Exception {
        EnterpriseDTO enterprise = this.enterpriseService.getEnterpriseById(enterpriseId) ;
        if(null == enterprise) {
            return resultResponse(HaoBanErrCode.ERR_OTHER, "商户不存在") ;
        }
        String factoryCode = enterprise.getFactoryCode() ;
        MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
        Iterator<String> iter = multiRequest.getFileNames();
        java.util.List<Map<String, Object>> picList = new ArrayList<>();
        while (iter.hasNext()) {
            String fileName = iter.next();
            List<MultipartFile> list = multiRequest.getMultiFileMap().get(fileName);
            Map<String, Object> map = null;
            for (int i = 0; i < list.size(); i++) {
                map = new HashMap<>();
                MultipartFile mf = list.get(i);
                InputStream in = mf.getInputStream();
                byte[] fileBuffer = null;
                if (null != in) {
                    int len = in.available();
                    fileBuffer = new byte[len];
                    in.read(fileBuffer);
                }
                //上传接口替换
//                PicUploadResDTO picUploadResDTO = qqCloudPicService.uploadPic(
//                        GlobalVar.ctxPropertiesMap.get(GlobalInfo.QQPIC_KEY_ENTERPRISE), fileBuffer);
                String suffix = "";
                String name = mf.getOriginalFilename() ;
                if(name.contains(".")) {
                    suffix = name.substring(name.lastIndexOf(".")+1) ;
                }
                logger.info("后缀={}",suffix);
                CloudFileTypeEnum cloudFileTypeEnum = CloudFileTypeEnum.OTHER;
                if (UploadUtils.isPicture(suffix)) {
                    cloudFileTypeEnum = CloudFileTypeEnum.IMAGE;
                } else if (UploadUtils.isOffice(suffix)) {
                    cloudFileTypeEnum = CloudFileTypeEnum.FILE;
                } else if (UploadUtils.isMusic(suffix)) {
                    cloudFileTypeEnum = CloudFileTypeEnum.AUDIO;
                } else if (UploadUtils.isVedio(suffix)) {
                    cloudFileTypeEnum = CloudFileTypeEnum.VIDEO;
                }
                CloudFileInfo cloudFileInfo =   CloudFileUtil.uploadFile(fileBuffer, suffix, cloudFileTypeEnum,factoryCode, CloudFileBusinessOptEnum.HAOBAN_COMMON);
                logger.info("上传返回的实体信息为:{}",cloudFileInfo);
                if (cloudFileInfo != null) {
                    map.put("qcloudImageUrl", cloudFileInfo.getOrgFileUrl());
                    map.put("imageFiledCode", cloudFileInfo.getFileId());
                }
                picList.add(map);
            }
        }
        return resultResponse(HaoBanErrCode.ERR_1, picList);
    }
    
    // fileType image:图片 video:视频  file:文件 audio音频 other:其它
    @RequestMapping("upload-img-fee")
    public RestResponse<Object> imgUploadFee(HttpServletRequest request , String fileType , String enterpriseId) throws Exception {
        if(StringUtils.isEmpty(enterpriseId)) {
            return RestResponse.failure("9999", "企业未传") ;
        }
        EnterpriseDTO enterprise = this.enterpriseService.getEnterpriseById(enterpriseId) ;
        if(null == enterprise) {
            return RestResponse.failure("9999", "商户不存在") ;
        }
        String factoryCode = enterprise.getFactoryCode() ;
        MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
        Iterator<String> iter = multiRequest.getFileNames();
        java.util.List<Map<String, Object>> picList = new ArrayList<>();
        while (iter.hasNext()) {
            String fileName = iter.next();
            List<MultipartFile> list = multiRequest.getMultiFileMap().get(fileName);
            Map<String, Object> map = null;
            for (int i = 0; i < list.size(); i++) {
                map = new HashMap<>();
                MultipartFile mf = list.get(i);
                CloudFileTypeEnum type = getType(fileType) ;
                File file = File.createTempFile("tmp", null);
                mf.transferTo(file);
                try {
                    String name = mf.getOriginalFilename() ;
                    if(name.contains(".")) {
                        name = name.substring(name.lastIndexOf(".")+1) ;
                    }
                    CloudFileInfo uploadInfo = CloudFileUtil.uploadTempFile(file, name, type, factoryCode , CloudFileBusinessOptEnum.COMMON, 7L) ;
                    if (uploadInfo != null) {
                        map.put("qcloudImageUrl", uploadInfo.getOrgFileUrl());
                        map.put("imageFiledCode", "imageFiledCode");
                        if(uploadInfo instanceof ImageCloudFileInfo) {
                            ImageCloudFileInfo info = (ImageCloudFileInfo) uploadInfo ;
                            map.put("compressFileUrl", info.getCompressFileUrl());
                        }
                    }
                }catch(Exception e) {
                    return RestResponse.failure("9999", e.getMessage()) ;
                }
                picList.add(map);
                //方法替换
                file.delete();
            }
        }
        return RestResponse.successResult(picList);
    }
    
    
    private CloudFileTypeEnum getType(String fileType) {
        if(StringUtils.isBlank(fileType)) {
            return CloudFileTypeEnum.IMAGE ;
        }
        CloudFileTypeEnum[] arr = CloudFileTypeEnum.values() ;
        for(int i=0;i<arr.length;i++) {
            if(arr[i].getType().equals(fileType)) {
                return arr[i];
            }
        }
        return CloudFileTypeEnum.IMAGE ;
    }

}
