package net.northking.cctp.upperComputer.utils;

import net.northking.cctp.upperComputer.exception.ParamMistakeException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * 附件相关工具类
 */
public class AttachUtils {

    private static final Logger logger = LoggerFactory.getLogger(AttachUtils.class);

    /**
     * 生成附件id
     * /yyyy/MM/dd/32位uuid[.文件后缀]
     *
     * @param filename 附件名称
     * @return 附件id
     */
    public static String createId(String filename) {
        if (StringUtils.isBlank(filename)) {
            logger.error("上传资源失败：附件名称不能为空");
            throw new ParamMistakeException("上传资源失败：附件名称不能为空");
        }
        String id;
        int i = filename.lastIndexOf(".");
        if (i <= 0) {   // 文件没有后缀名称
            id = createDatePath() + UUID.randomUUID().toString().replace("-","");
        } else {    // 文件存在后缀名称
            String postfix = filename.substring(i + 1);
            id = createDatePath() + UUID.randomUUID().toString().replace("-","") + "." + postfix;
        }
        logger.debug("文件[{}] --> id: {}", filename, id);
        return id;
    }


    public static String exchangeToUrl(String attachId, String tenantId) {
        return String.format("%s%s", tenantId, encodeAttachId(attachId));
    }

    private static String encodeAttachId(String id) {
        return id.replace("/", "_");
    }


    /**
     * 根据日期创建目录
     *
     * @return 根据日期创建目录
     */
    private static String createDatePath()
    {
        SimpleDateFormat format = new SimpleDateFormat("/yyyy/MM/dd/");
        return format.format(new Date());
    }

}
