package net.northking.cctp.se.util;

import net.northking.cctp.common.util.UUIDUtil;
import net.northking.cctp.element.core.exception.ExecuteException;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

/**
 * 附件相关工具类
 */
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 ExecuteException("上传资源失败：附件名称不能为空");
        }
        String id;
        int i = filename.lastIndexOf(".");
        if (i <= 0) {   // 文件没有后缀名称
            id = createDatePath() + UUIDUtil.create32UUID();
        } else {    // 文件存在后缀名称
            String postfix = filename.substring(i + 1);
            id = createDatePath() + UUIDUtil.create32UUID() + "." + 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());
    }

}
