const env = require('./config.js'); 

const base64 = require('./base64.js');
require('./hmac.js');
require('./sha1.js');
const Crypto = require('./crypto.js');
 
import axios from 'axios'
import modal from '../function/modal.js';

const  getPreviewSrc = (path)=> {
  if(!path) return '';
  var suffix = path.substring(path.lastIndexOf(".") + 1);
  if (suffix == "png" || suffix == "jpg" || suffix == "gif" || suffix == "bmp") {
    return path;
  }
  if (suffix == "doc" || suffix == "docx") {
    return env.uploadImageUrl + "DOC.png";
  }
  if (suffix == "ppt") {
    return env.uploadImageUrl + "PPT.png";
  }
  if (suffix == "xls" || suffix == "xlsx") {
    return env.uploadImageUrl + "Excel.png";
  }
  if (suffix == "txt") {
    return env.uploadImageUrl + "txt.png";
  }
  if (suffix == "pdf") {
    return env.uploadImageUrl + "pdf.png";
  }
  if (suffix == "mp4" || suffix == "m4v") {
    return env.uploadImageUrl + "video.png";
  }
  return env.uploadImageUrl + "file.png";
};
/*
 *上传文件到阿里云oss
 *@param - filePath :文件的本地资源路径
  @param - path :上传oss哪个路径下
  postfix : 文件后缀
 *@param - successc:成功回调
 *@param - failc:失败回调
 */
const uploadFile = function (file, fix,successc) {
  let path = new Date().getFullYear() +"";
  fix = fix.replace('.', '')
  if (!fix) {
    fix = ''
  }
  //存放文件命名格式：自定义时间戳给文件名字(可以自己改)
  const aliyunFileKey = path + '/' + new Date().getTime() +
   parseInt(Math.random() * (9999 - 1000 + 1) + 1000, 10) + '.' + fix.replace('.', '');

  const aliyunServerURL = env.uploadImageUrl; //OSS地址，https
  const accessid = env.OSSAccessKeyId;
  let policyBase64 = getPolicyBase64();
  let signature = getSignature(policyBase64);

  function fileCreate (file) {
    const uploadData = new FormData();
    uploadData.append("OSSAccessKeyId", accessid);
    uploadData.append("key", aliyunFileKey);
    uploadData.append("policy", policyBase64);
    uploadData.append("success_action_status", 200); 
    uploadData.append("name", file.name);
    uploadData.append("Signature", signature);
    uploadData.append("file", file); 
    return uploadData;
  }
 axios({
    url: aliyunServerURL, //开发者服务器 url
    method: 'post',
    headers: { 'Content-Type': 'multipart/form-data' },
    data: fileCreate(file)
  }).then(a=>{

    if (a.status != 200) {
      modal.error('上传错误:' + JSON.stringify(a))
      return;
    }
    successc( aliyunServerURL+ aliyunFileKey,aliyunFileKey);
  })
}


 

const getPolicyBase64 = function () {
  let date = new Date();
  date.setHours(date.getHours() + env.timeout);
  let srcT = date.toISOString();
  const policyText = {
    "expiration": srcT, //设置该Policy的失效时间，超过这个失效时间之后，就没有办法通过这个policy上传文件了 
    "conditions": [
      ["content-length-range", 0, env.maxSize] // 设置上传文件的大小限制,5mb
    ]
  };

  const policyBase64 = base64.encode(JSON.stringify(policyText));
  return policyBase64;
}


function izArrayBufferToBase64(buffer) {
  var binary = '';
  var bytes = new Uint8Array(buffer);
  var len = bytes.byteLength;
  for (var i = 0; i < len; i++) {
    binary += String.fromCharCode(bytes[i]);
  }
  let signature = base64.encode(binary)
  return signature
}


const getSignature = function (policyBase64) {
  const accesskey = env.AccessKeySecret;
  const bytes = Crypto.HMAC(Crypto.SHA1, policyBase64, accesskey, {
    asBytes: true
  });
  const signature = izArrayBufferToBase64(bytes)
  return signature;
}


export default{
  uploadFile ,
  getPreviewSrc
}