package com.skr.mdm.service.impl.content;

import com.skr.mdm.constant.MinIoMessageConstants;
import com.skr.mdm.constant.RedisPrefixConstant;
import com.skr.mdm.dto.LoginUserDTO;
import com.skr.mdm.manager.oss.MinIoManager;
import com.skr.mdm.result.ResponseResult;
import com.skr.mdm.util.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

/**
 * @ProjectName: mdm_new
 * @Package: com.skr.mdm.service.impl.content
 * @ClassName: ClientFileServiceImpl
 * @Author: Tty
 * @Description: 客户端文件上传
 * @Date: 2021/3/11 14:23
 * @Version: 1.0
 */
@Slf4j
@Service
public class ClientFileServiceImpl {

    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private MinIoManager minIoManager;

    public ResponseResult cmdHandler(LoginUserDTO loginUserDTO, String data) {
        String redisKey = loginUserDTO.getCompanyId() + RedisPrefixConstant.TIER_KEY_PREFIX + loginUserDTO.getId();
        boolean flag = redisUtils.set(redisKey, data, 60L * 5);
        return flag ? ResponseResult.success() : ResponseResult.failure();
    }

    public ResponseResult upload(MultipartFile file, LoginUserDTO loginUserDTO) {
        ResponseResult result;
        try {
            if (file.isEmpty()) {
                return ResponseResult.success();
            }
            String fileName = file.getOriginalFilename();
            String object = MinIoMessageConstants.FILE_ACCESS.concat(loginUserDTO.getUsername()).concat("/" + fileName);
            String url = minIoManager.putObjectMinIo(loginUserDTO.getCompanyId(), object, file, false);
            if (StringUtils.contains(url, "?")) {
                url = StringUtils.substringBefore(url, "?");
            }
            String redisKey = redisUtils.getRedisKey(loginUserDTO.getCompanyId() + RedisPrefixConstant.FILE_KEY_PREFIX.concat(loginUserDTO.getId() + "__0"));
            log.info("新增Key值 ： {}", redisKey);
            redisUtils.set(redisKey, url, 60L * 5);
            result = ResponseResult.success();
        } catch (Exception e) {
            log.error("客户端上传文件出现文件异常：" + loginUserDTO.getId(), e);
            result = ResponseResult.failure();
        }
        return result;
    }

}