// 阿里云直传工具
import apiConfig from '../config/api_config.js';
import request from './request.js';

function requestOssSignature(dir) {
      // 使用 Fiber 后端的接口
      const dirParam = dir || 'camp';
      return request({
            url: `/oss/upload/signature?dir=${encodeURIComponent(dirParam)}`,
            method: 'GET'
      }).then(function(res) {
            // Fiber 后端直接返回凭证数据（JSON格式），兼容可能的包裹格式
            // 如果返回 { success: true, data: {...} }，则提取 data；否则直接使用 res
            if (res && res.success === true && res.data) {
                  return res.data;
            }
            // 直接返回数据（Fiber 后端直接返回 PolicyToken 结构）
            return res;
      }).catch(function(err) {
            console.error('获取OSS上传凭证失败:', err);
            return null;
      });
}

function normalizeSignature(raw) {
      if (!raw) return null;
      // Fiber 后端直接返回凭证数据，兼容旧格式 { success, data } 或直接返回
      var data = raw.data || raw;
      // 常见字段名兼容
      var host = data.host || data.endpoint || '';
      var dir = data.dir || data.prefix || '';
      var policy = data.policy;
      var signature = data.signature;

      // v4 字段（表单直传）- Fiber 后端使用这些字段名
      var sigVer = data.x_oss_signature_version || data['x-oss-signature-version'] || data.signature_version || data.SignatureVersion;
      var credential = data.x_oss_credential || data['x-oss-credential'] || data.credential || data.Credential;
      var date = data.x_oss_date || data['x-oss-date'] || data.date || data.Date;
      var securityToken = data.security_token || data['x-oss-security-token'] || data.SecurityToken || data.securityToken;

      // v2 兼容字段（旧接口可能使用）
      var accessId = data.accessid || data.accessKeyId || data.OSSAccessKeyId || data.accessId;

      if (!host || !policy || !signature) return null;

      // Fiber 后端使用 v4 签名，返回 v4 所需字段
      if (sigVer) {
            return {
                  host: host,
                  dir: dir,
                  policy: policy,
                  signature: signature,
                  signatureVersion: sigVer,
                  credential: credential,
                  date: date,
                  securityToken: securityToken
            };
      }

      // v2 兼容（旧接口）
      if (!accessId) return null;
      return { host: host, dir: dir, accessId: accessId, policy: policy, signature: signature };
}

function buildOssKey(options) {
      var now = new Date();
      function pad(n){ return n < 10 ? ('0'+n) : ''+n; }
      var y = now.getFullYear();
      var m = pad(now.getMonth()+1);
      var d = pad(now.getDate());
      var h = pad(now.getHours());
      var mm = pad(now.getMinutes());
      var s = pad(now.getSeconds());
      var ts = now.getTime();

      var userId = String(options.userId || 'anonymous');
      var taskId = String(options.taskId || 'unknown');
      var baseDir = options.baseDir || 'camp';
      var subDir = options.subDir || 'subjective';
      var ext = options.ext || 'jpg';

      return [
            baseDir,
            'user_'+userId,
            subDir,
            taskId,
            ''+y+m+d,
            ts+'_'+Math.floor(Math.random()*100000)+'.'+ext
      ].join('/');
}

async function getOssConfig(dir) {
      var raw = await requestOssSignature(dir || 'camp');
      return normalizeSignature(raw);
}

module.exports = {
      getOssConfig,
      buildOssKey
};


