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.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.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.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 QQCloudPicService qqCloudPicService;
    @Autowired
    private EnterpriseService enterpriseService ;


    @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();
            //获取文件名后缀
            String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
            logger.info("文件的后缀为:{}",suffix);
            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);
                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, 7*24L) ;
                    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.deleteOnExit();
            }
        }
        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 ;
    }

}
