package com.crm.manager.service.impl;

import com.crm.manager.service.CommonService;
import com.crm.manager.service.FIleFeignService;
import com.crm.manager.service.impl.base.BaseUploadServiceImpl;
import com.crm.rely.backend.core.entity.upload.UploadTokenEntity;
import com.crm.rely.backend.service.RedisService;
import com.crm.rely.backend.util.Base64Util;
import com.google.common.base.Strings;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

@Slf4j
@Service
public class CommonServiceImpl extends BaseUploadServiceImpl implements CommonService {

    @Autowired
    private RedisService redisService;
    @Autowired
    private FIleFeignService fIleFeignService;
    /*@Override
    public String uploadFile1(String middlePath,MultipartFile file) throws Exception {

        String path = saveFile(middlePath, file);

        return path;
    }*/

    private static UploadTokenEntity getUploadTokenInfo(String uploadToken, String path, String fileHash) {
        UploadTokenEntity uploadTokenInfo = new UploadTokenEntity();
        uploadTokenInfo.setUploadToken(uploadToken);
        uploadTokenInfo.setFilePath(path);
        uploadTokenInfo.setFileHash(fileHash);
        return uploadTokenInfo;
    }

//    @Override
//    public String uploadFile(String middlePath, MultipartFile file) throws Exception {
//        String fileHash = DigestUtils.md5DigestAsHex(file.getInputStream()); //转hash
//        String uploadToken = UUIDUtil.getUUID();
//        String key = Constants.UPLOAD_KEY + uploadToken;
//
//        UploadTokenEntity uploadTokenInfo = getUploadTokenInfo(uploadToken, middlePath, fileHash);
//
//        redisService.save(key, uploadTokenInfo, Constants.UPLOAD_TOKEN_TIME);
//        return uploadToken; //返回校验token
//    }

    @Override
    public String uploadFile(String middlePath, MultipartFile file) {
        if (!Strings.isNullOrEmpty(middlePath) && !middlePath.startsWith("/")) {
            middlePath = "/" + middlePath;
        }
        try {
            return fIleFeignService.commonUpload(file, Base64Util.toBase64String(middlePath));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
//
//        String savePath = UPLOAD + (Strings.isNullOrEmpty(middlePath) ? ("/file/common/") : middlePath);
//
//        String path = FileProcessUtil.upload(file, savePath);
//        return (Strings.isNullOrEmpty(middlePath) ? ("/file/common/") : middlePath) + path;
    }

    @Override
    public String uploadFile(MultipartFile file) throws Exception {
        String middlePath = "/common";
        return uploadFile(middlePath, file);
    }
}
