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

import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSONObject;
import com.gic.clerk.api.dto.AuthorizedUser;
import com.gic.commons.util.DateUtil;
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.base.api.common.pojo.dto.WebLoginDTO;
import com.gic.haoban.common.utils.AuthWebRequestUtil;
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.qcloud.BucketNameEnum;
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.web.common.utils.SessionContextUtils;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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 java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashSet;
import java.util.Set;

@RestController
public class UploadController extends WebBaseController {
    private static Logger logger = LoggerFactory.getLogger(UploadController.class);
    private static Set<String> FILE_TYPE = new HashSet<>();

    static {
        for (BucketNameEnum value : BucketNameEnum.values()) {
            FILE_TYPE.add(value.getName());
        }
    }

    @Autowired
    private EnterpriseService enterpriseService;

    @RequestMapping("/upload-file")
    @ResponseBody
    public HaobanResponse upload(@RequestParam MultipartFile file) throws Exception {
        if (file == null || file.isEmpty()) {
            return resultResponse(HaoBanErrCode.ERR_2);
        }
        //获取登录人信息
        WebLoginDTO au = AuthWebRequestUtil.getLoginUser();
        if(null == au){
            return resultResponse(HaoBanErrCode.ERR_4);
        }
        EnterpriseDTO enterprise = this.enterpriseService.getEnterpriseById(au.getEnterpriseId());
        if (null == enterprise) {
            return resultResponse(HaoBanErrCode.ERR_OTHER, "商户不存在");
        }
        logger.info("登录人信息:{}", JSONObject.toJSONString(au));
        String name = file.getOriginalFilename();
        // 未加密前文件名称
        String mediaName = file.getOriginalFilename();
        mediaName = mediaName.substring(0, mediaName.lastIndexOf("."));
        if (mediaName.length() > 20) {
            mediaName = mediaName.substring(0, 20);
        }
        String suffix = name.substring(name.lastIndexOf(".") + 1);
        name = SecureUtil.md5(name) + "." + suffix;
        String location = System.getProperty("user.dir") + "/data/tmp/";
        long len = file.getSize();

        File templateFile = new File(location + name);
        FileUtils.copyInputStreamToFile(file.getInputStream(), templateFile);
        // 2.上传腾讯云
        String dayFilePath = LocalDateTime.now().format(DateTimeFormatter.ofPattern(DateUtil.FORMAT_DATETIME_14));
        String nameUpload = mediaName + "." + suffix;
        String key = "haoban/" + dayFilePath + "/" + nameUpload;
        try {
            //替换新的上传接口
//            String url = FileUploadUtil.simpleUploadFileFromLocal(templateFile, key, fileType);
            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(new FileInputStream(templateFile), suffix, cloudFileTypeEnum, enterprise.getFactoryCode(), CloudFileBusinessOptEnum.HAOBAN_COMMON);
            if (templateFile != null) {
                templateFile.delete();
            }
            JSONObject res = new JSONObject();
            res.put("name", name);
            res.put("mediaName", mediaName);
            res.put("ext", suffix);
            res.put("size", len);
            res.put("key", key);
            res.put("url", cloudFileInfo.getOrgFileUrl());
            return resultResponse(HaoBanErrCode.ERR_1, res);
        } catch (Exception e) {
            logger.info("异常:{}", e.getMessage(), e);
            return resultResponse(HaoBanErrCode.ERR_0);
        }
    }

    @RequestMapping("copy-image-url")
    public RestResponse<Object> imgUploadFee(String filetype , String fileUrl , @RequestParam(defaultValue = "0") int videoFlag) throws Exception {
        WebLoginDTO login = AuthWebRequestUtil.getLoginUser();
        String enterpriseId = login.getEnterpriseId() ;
        EnterpriseDTO en = this.enterpriseService.getEnterpriseById(enterpriseId) ;
        URL url = new URL(fileUrl);
        URLConnection connection = url.openConnection();
        connection.setConnectTimeout(1000 * 10);
        connection.setReadTimeout(1000 * 10);
        InputStream inputStream = connection.getInputStream();
        CloudFileTypeEnum type = CloudFileTypeEnum.IMAGE ;
        if(videoFlag==1) {
            type = CloudFileTypeEnum.VIDEO ;
        }
        CloudFileInfo uploadInfo = CloudFileUtil.uploadFile(inputStream, filetype,  type,  en.getFactoryCode(), CloudFileBusinessOptEnum.COMMON) ;
        logger.info("图片={}",JSONObject.toJSONString(uploadInfo));
        return RestResponse.successResult(uploadInfo);
    }

}
