import http from '@/utils/http'
import config from './config'
import crypto from 'crypto-js';
import { Base64 } from 'js-base64';

export default {
	getCredential() {
		return http.post('mini/ali/mini_credential')
	},
	// 图片校验
	checkImg(data) {
		return http.post('mini/mini_wechat_app_info/media_check_async',data)
	},
	// 图片上传
	uploadImg(data) {
		return http.post('mini/lz_tree_image/insert',data)
	},
	// 计算签名
	computeSignature(accessKeySecret, canonicalString) {
	  return crypto.enc.Base64.stringify(crypto.HmacSHA1(canonicalString, accessKeySecret));
	},
	getFormDataParams(){
	  return new Promise((resolve)=>{
	    this.getCredential().then(({code, data})=>{
	      let { accessKeyId, accessKeySecret, securityToken } = data;
	      const policy = Base64.encode(JSON.stringify(this.getPolicyText())) 
	      const signature = this.computeSignature(accessKeySecret, policy)
	      const formData = {
	        OSSAccessKeyId: accessKeyId,
	        signature,
	        policy,
	        "x-oss-security-token":securityToken 
	      }
	      resolve(formData)
	    })
	  })
	},
	getPolicyText(){
	  const date = new Date();
	  date.setHours(date.getHours() + 1);
	  const policyText = {
	    expiration: date.toISOString(), // 设置policy过期时间。
	    conditions: [
	      // 限制上传大小。
	      ["content-length-range", 0, 1024 * 1024 * 1024],
	    ],
	  };
	  return policyText
	},
	upload(formData,key,src){
	    let host = "https://birdseye.oss-cn-guangzhou.aliyuncs.com/"
	    return new Promise((resolve)=>{
	      uni.uploadFile({
	        url: host,
	        filePath: src,
	        name: 'file', // 必须填file。
	        formData: {
	          key,
	          ...formData // 使用STS签名时必传。
	        },
	        success: (res) => {
	          resolve(res)
	        },
	        fail: err => {
	          console.log(err);
	        }
	      });
	    })
	},
}