
package com.kxs.common.file.oss.service;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.util.StrUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.kxs.common.core.util.R;
import com.kxs.common.file.oss.core.FileProperties;
import com.kxs.common.file.oss.vo.PolicyVO;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.InitializingBean;

import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.util.Date;
import java.util.UUID;


/**
 * 实现oss
 *
 * @author 没秃顶的码农
 * @date 2024-04-18
 */
@RequiredArgsConstructor
public class OssTemplate implements InitializingBean {

	private final FileProperties properties;

	private final String fileModel = "app";

	private OSS ossClient;

	public R<PolicyVO> getPolicy(String dirStr) {

		String format = LocalDate.now().format(DatePattern.NORM_DATE_FORMATTER);
		// 用户上传文件时指定的前缀。
		String dir = properties.getFilePrefix() + StrUtil.SLASH + dirStr + StrUtil.SLASH + format + StrUtil.SLASH + UUID.randomUUID();
		//上传过期时间
		long expireEndTime = System.currentTimeMillis() + 30 * 1000;
		Date expiration = new Date(expireEndTime);
		// PostObject请求最大可支持的即CONTENT_LENGTH_RANGE为5*1024*1024*1024。
		PolicyConditions policyCords = new PolicyConditions();
		policyCords.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 20*1024);
		policyCords.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);

		String postPolicy = ossClient.generatePostPolicy(expiration, policyCords);
		byte[] binaryData = postPolicy.getBytes(StandardCharsets.UTF_8);
		String encodedPolicy = BinaryUtil.toBase64String(binaryData);
		String postSignature = ossClient.calculatePostSignature(postPolicy);

		return R.ok(PolicyVO.builder().accessKey(properties.getAccessKey())
				.policy(encodedPolicy)
				.signature(postSignature)
				.dir(dir).host("https://" +  properties.getBucketName() + StrUtil.DOT + properties.getEndpoint())
				.expire(String.valueOf(expireEndTime / 1000)).build()
		);
	}

	/**
	 * 配置oss客户端
	 *
     */
	@Override
	public void afterPropertiesSet() {

		// 创建OSSClient实例。
		this.ossClient = new OSSClientBuilder().
				build(properties.getEndpoint(), properties.getAccessKey(), properties.getSecretKey());
	}

}
