package com.yd.oss.service.utils;

import com.yd.common.result.Result;
import com.yd.user.feign.client.sysproject.ApiSysProjectFeignClient;
import com.yd.user.feign.response.sysproject.ApiSysProjectDetailResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.core.env.Environment;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Component
public class OssUtils {

    @Autowired
    private Environment environment;

    @Autowired
    private ApiSysProjectFeignClient apiSysProjectFeignClient;

    /**
     * 获取通用文件路径的前缀
     * @param projectBizId 项目ID
     * @param env 环境变量（prod,test）如果不传系统获取
     * @param originalFileName 原始文件名
     * @param fileType（文件类型,文件扩展名）
     * @return
     */
    public String getFilePrefix(String projectBizId,String env,
                                String originalFileName,String fileType) {
        String projectType = "pc";
        if (StringUtils.isNotBlank(projectBizId)) {
            //通过项目ID查询项目类型
            Result<ApiSysProjectDetailResponse> result = apiSysProjectFeignClient.detail(projectBizId);
            if (result.getData() != null) {
                ApiSysProjectDetailResponse response = result.getData();
                projectType = StringUtils.isNotBlank(response.getProjectType()) ? response.getProjectType() : "pc";
            }
        }
        if (StringUtils.isBlank(env)) {
            env = getActiveEnv();
        }
        return projectType + "/" + env + "/" + FileUtil.generateFileKey(originalFileName,fileType);
    }

    /**
     * 获取分片文件路径的前缀
     * @param projectBizId
     * @param env
     * @param env
     * @return
     */
    public String getShardFilePrefix(String projectBizId,String env) {
        String projectType = "pc";
        if (StringUtils.isNotBlank(projectBizId)) {
            //通过项目ID查询项目类型
            Result<ApiSysProjectDetailResponse> result = apiSysProjectFeignClient.detail(projectBizId);
            if (result.getData() != null) {
                ApiSysProjectDetailResponse response = result.getData();
                projectType = StringUtils.isNotBlank(response.getProjectType()) ? response.getProjectType() : "pc";
            }
        }
        if (StringUtils.isBlank(env)) {
            env = getActiveEnv();
        }
        return projectType + "/" + env + "/large_file/uploads/" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd/"));
    }

    private String getActiveEnv() {
        String[] activeProfiles = environment.getActiveProfiles();
        return activeProfiles.length > 0 ? activeProfiles[0] : "prod";
    }
}
