import request from '../../utils/request'
import {
  Loading
} from 'quasar'
/**
 * 获取富文本编辑器Font
 */
export function getFontConfig() {
  return {
    arial: 'Arial',
    arial_black: 'Arial Black',
    comic_sans: 'Comic Sans MS',
    courier_new: 'Courier New',
    impact: 'Impact',
    lucida_grande: 'Lucida Grande',
    times_new_roman: 'Times New Roman',
    verdana: 'Verdana'
  };
}


/**
 * 上传文件 
 */
export function UploadSelfFile(path, file, callback, configObj) {
  //用户登录缓存
  var cacheInfo = JSON.parse(window.localStorage["loginUserInfo"]);
  //上传配置
  var uploadConfig = "";
  if (cacheInfo && cacheInfo.data && cacheInfo.data.UploadConfig) {
    uploadConfig = cacheInfo.data.UploadConfig;
  }
  //获取文件扩展名
  var index = file.name.lastIndexOf(".");
  var suffix = file.name.substr(index);
  var timestamp1 = Date.parse(new Date()) + "_" + (Math.ceil(Math.random() * 1000));
  let str = '/Test';
  var newPath = "/EduSystem" + str + '/Upload/' + path;
  Loading.show({
    message: '正在上传文件,请稍后...'
  })
  if (uploadConfig) {
    switch (uploadConfig.StoreType) {
      //上传文件到腾讯云
      case 1:
        newPath += "/" + timestamp1 + "" + suffix;
        UploadFileToTencent(uploadConfig, newPath, file, callback);
        break;
        //上传文件到阿里云
      case 2:
        newPath += "/" + timestamp1 + "" + suffix;
        UploadFileToALi(uploadConfig, newPath, file, callback);
        break;
        //上传文件到自己文件服务器
      case 3:
        UploadFileToSystem(uploadConfig, newPath, file, callback, configObj);
        break;
    }
  }
  Loading.hide();
}

/**
 * 上传文件到本地文件系统
 */
export function UploadFileToSystem(uploadConfig, fileFullPath, fileObj, successCall, configObj) {
  let url = uploadConfig.UploadDomain + "/Upload?filePath=" + fileFullPath;
  if (configObj) {
    //是否转换图片
    if (configObj.isTrans && configObj.isTrans == 1) {
      url += "&isTrans=1"
    }
  }
  let formData = new FormData()
  formData.append('myfile', fileObj)
  let xhr = new XMLHttpRequest()
  xhr.onload = function () {
    var jsonObj = JSON.parse(xhr.responseText);
    if (jsonObj.StatusCode == 1 && successCall) {
      var tempArray = [];
      if (jsonObj.OtherFile && jsonObj.OtherFile.length > 0) {
        jsonObj.OtherFile.forEach(item => {
          tempArray.push(uploadConfig.CustomDomain + item);
        })
      }
      var uploadResult = {
        Code: 1,
        FileName: fileObj.name,
        FileUrl: uploadConfig.CustomDomain + jsonObj.FilePath,
        VideoCoverImg: uploadConfig.CustomDomain + jsonObj.VideoCoverImg,
        ExtFile: tempArray
      }
      if (successCall) {
        successCall(uploadResult);
      }
    }
  }
  xhr.open('post', url, true)
  xhr.send(formData)
}

/**
 * 上传文件到阿里云
 */
export function UploadFileToALi(uploadConfig, fileFullPath, fileObj, successCall) {
  var OSS = require('ali-oss');
  var oss = new OSS({
    region: uploadConfig.Region,
    accessKeyId: uploadConfig.SecretId,
    accessKeySecret: uploadConfig.SecretKey,
    bucket: uploadConfig.Bucket
  })
  var result = oss.multipartUpload(fileFullPath, fileObj, {
    progress: function* (p) {}
  }).then(res => {
    var uploadResult = {
      Code: 1,
      FileName: fileObj.name,
      FileUrl: res.res.requestUrls[0].split('?')[0].replace('http', 'https')
    }
    if (successCall) {
      successCall(uploadResult);
    }
  })
}

/**
 * 上传文件到腾讯云
 */
export function UploadFileToTencent(uploadConfig, fileFullPath, fileObj, successCall) {
  var COS = require('cos-js-sdk-v5');
  var cos = new COS({
    SecretId: uploadConfig.SecretId,
    SecretKey: uploadConfig.SecretKey,
  });
  cos.putObject({
    Bucket: uploadConfig.Bucket,
    Region: uploadConfig.Region, //存储桶所在地域，必须字段
    Key: fileFullPath, //文件名
    StorageClass: 'STANDARD',
    Body: fileObj, // 上传文件对象
    onProgress: function (progressData) {}
  }, function (err, data) {
    if (data && data.statusCode == 200) {
      var uploadResult = {
        Code: 1,
        FileName: fileObj.name,
        FileUrl: "https://" + data.Location
      }
      if (successCall) {
        successCall(uploadResult);
      }
    } else {
      /*上传文件异常*/
      console.log(err || data);
    }
  });
}

/**
 * 获取省市区
 */
export function queryAreaTree(data) {
  return request({
    url: '/Public/GetAreaTree',
    method: 'post',
    data
  })
}

/**
 * 获取省市区列表
 */
export function queryAreaList(data) {
  return request({
    url: '/Public/GetAreaList',
    method: 'post',
    data
  })
}

/**
 * 获取文件扩展名
 */
export function getFileExt(filename) {
  var index = filename.lastIndexOf(".");
  var suffix = filename.substr(index + 1);
  return suffix
}

/**
 * 
 * 教育文件下载
 */

export function EduDownLoad(cmd, msg, fileName) {
  return request({
    url: cmd,
    method: 'post',
    data: msg,
    headers: {
      responseType: 'arraybuffer'
    }
  }).then(res => {
    let blob = new Blob([res.data], {
      type: "application/vnd.ms-excel"
    })
    let url = URL.createObjectURL(blob);
    let link = document.createElement('a');
    link.href = url;
    link.setAttribute("download", fileName);
    document.body.appendChild(link);
    link.click();
  })
}
