
package org.tio.sitexxx.service.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.RandomUtil;
import org.tio.sitexxx.service.vo.Const;
import org.tio.utils.hutool.DatePattern;

import java.io.File;
import java.util.Date;

/**
 * 上传工具处理类
 * @author xufei
 * 2021年4月27日 下午3:50:46
 */
public class UploadUtils {
	/**
	 * 根据用户id获取其im-data路径(位于上传资源服务器)
	 * @param subDir
	 * @param uid
	 * @return
	 * @author tanyaowu
	 */
	public static String dataRootPath(String subDir, int uid) {
		long uid1 = uid + 74541287548L;
		long base = 107;
		long dir1 = uid1 % base;
		long dir2 = uid1 % (base * base);
		long dir3 = uid1 % (base * base * base);
		long dir4 = uid1 % (base * base * base * base);

		return "/" +
				DateUtil.format(new Date(), "yyyyMM") +
				"/" +
				subDir +
				"/" +
				dir1 +
				"/" +
				dir2 +
				"/" +
				dir3 +
				"/" +
				dir4 +
				"/" +
				uid1;
	}

	/**
	 * 新上传的文件，不含后缀。形如："/im/upload/img/1/1/1/2/44/20/121212"
	 * @param subDir
	 * @param uid
	 * @param filename 可以为null
	 * @return
	 */
	public static String newFile(String subDir, int uid, String filename) {
		String path = dataRootPath(subDir, uid);
		Date date = new Date();
		path = path + "/" + RandomUtil.randomInt(1, 120);

		String resRootDir = Const.RES_ROOT;
		File dir = new File(resRootDir, path);
		FileUtil.mkdir(dir);

		String newFileName = DateUtil.format(date, "HHmmss");
		if (filename != null) {
			//			fileName += "/" + FileUtil.mainName(filename);
			newFileName += "/" +filename+"-"+SnowflakeUtils.nextId();
		} else {
			newFileName += "/" + SnowflakeUtils.nextId();
		}
		return path + "/" + newFileName;
	}

	/**
	 *  按时间产生路径
	 * @param subDir
	 * @return
	 * @author xufei
	 * 2020年1月14日 下午4:12:11
	 */
	public static String dateFile(String subDir) {
		String path = "/" + subDir + "/";
		Date date = new Date();
		path += DateUtil.format(new Date(), DatePattern.PURE_DATE_PATTERN);
		path = path + RandomUtil.randomInt(1, 120);
		String resRootDir = Const.RES_ROOT;
		File dir = new File(resRootDir, path);
		FileUtil.mkdir(dir);
		return path + "/" + DateUtil.format(date, "HHmmss") + SnowflakeUtils.nextId();
	}
}
