package com.zxdmy.excite.admin.controller.oss;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.zxdmy.excite.common.base.BaseController;
import com.zxdmy.excite.common.base.BaseResult;
import com.zxdmy.excite.component.oss.AliOSSProperties;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.time.LocalDate;
import java.util.*;

/**
 * 系统菜单/权限表 前端控制器
 *
 * @author 沈松
 * @since 2021-09-12
 */
@Controller
@AllArgsConstructor
@RequestMapping("/cloud/oss/")
public class OssController extends BaseController {

    @Autowired//将OSS的配置注入进来，后面需要用到

    private AliOSSProperties aliOSSProperties;


    /**
     * 获取OSS上传凭证（用于前端直传）
     */


    @GetMapping("/policy")
    @ResponseBody
    public BaseResult getUploadPolicy() {
        try {
            // 使用简化版本的Policy生成
            Map<String, String> policy = getSimpleUploadPolicy();
            return success("获取列表成功", policy);
        } catch (Exception e) {
            return error("获取上传凭证失败: " + e.getMessage());
        }
    }




    /**
     * 生成唯一的文件名
     */
    private String generateFileName(String originalFilename) {
        String suffix = "";
        if (originalFilename != null && originalFilename.contains(".")) {
            suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        }
        return UUID.randomUUID().toString().replace("-", "") + suffix;
    }
    /**
     * 简化的Policy获取方法
     */
    public Map<String, String> getSimpleUploadPolicy() {
        Map<String, String> result = new HashMap<>();

        try {
            // 生成目录：按年月
            String dir = "cloud/" +
                    LocalDate.now().getYear() + "-" +
                    String.format("%02d", LocalDate.now().getMonthValue());

            // 确保以/结尾
            if (!dir.endsWith("/")) {
                dir = dir + "/";
            }

            // 使用更简单的key格式：cloud/2026-01/${filename}
            String key = dir + "${filename}";

            // Policy过期时间
            long expireEndTime = System.currentTimeMillis() + 300 * 1000;
            Date expiration = new Date(expireEndTime);

            // 创建Policy
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(
                    PolicyConditions.COND_CONTENT_LENGTH_RANGE,
                    0,
                    1048576000
            );

            // 使用starts-with条件，允许任意文件名
            policyConds.addConditionItem(
                    MatchMode.StartWith,
                    PolicyConditions.COND_KEY,
                    dir
            );

            String endpoint = aliOSSProperties.getEndpoint();
            String accessKeyId = aliOSSProperties.getAccessKeyId();
            String accessKeySecret = aliOSSProperties.getAccessKeySecret();
            String bucketName = aliOSSProperties.getBucketName();
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId,accessKeySecret);

            String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
            String encodedPolicy = Base64.getEncoder().encodeToString(postPolicy.getBytes("UTF-8"));
            String signature = ossClient.calculatePostSignature(postPolicy);

            // 返回结果
            result.put("OSSAccessKeyId", accessKeyId);
            result.put("policy", encodedPolicy);
            result.put("signature", signature);
            result.put("key", key);  // 这个key必须包含${filename}
            result.put("host", "https://" + bucketName + "." + endpoint);
            result.put("dir", dir);
            result.put("expire", String.valueOf(expireEndTime / 1000));
            result.put("success_action_status", "200");



        } catch (Exception e) {
            throw new RuntimeException("生成上传凭证失败", e);
        }

        return result;
    }
}
