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;
  var uploadLoadding = Loading;
  uploadLoadding.show({
    message: '正在上传文件,请稍后...'
  })
  if (uploadConfig) {
    switch (uploadConfig.StoreType) {
      //上传文件到腾讯云
      case 1:
        newPath += "/" + timestamp1 + "" + suffix;
        UploadFileToTencent(uploadConfig, newPath, file, uploadLoadding, callback);
        break;
      //上传文件到阿里云
      case 2:
        newPath += "/" + timestamp1 + "" + suffix;
        UploadFileToALi(uploadConfig, newPath, file, uploadLoadding, callback);
        break;
      //上传文件到自己文件服务器
      case 3:
        UploadFileToSystem(uploadConfig, newPath, file, uploadLoadding, callback, configObj);
        break;
    }
  }
}

//上传视频文件到本地服务器
export function UploadViittoFile(path, file, callback) {
  var uploadLoadding = Loading;
  uploadLoadding.show({
    message: '正在上传文件,请稍后...'
  })
  let viewFileUrl = 'http://192.168.20.214:8130';
  let vtUploadUrl = "http://192.168.20.214:8120";
  let locationName = window.location.hostname;
  if (locationName.indexOf('testerp.oytour') !== -1) {
    vtUploadUrl = "http://upload.oytour.com";
    viewFileUrl = "https://imgfile.oytour.com";
  } else if (locationName.indexOf('oytour') !== -1) {
    vtUploadUrl = "http://upload.oytour.com";
    viewFileUrl = "https://imgfile.oytour.com";
  }
  var UploadConfig = {
    Bucket: "系统",
    CustomDomain: viewFileUrl,
    Region: "成都",
    SecretId: "SecreId",
    SecretKey: "SecreKey",
    StoreType: 3,
    UploadDomain: vtUploadUrl,
  };
  var configObj = {
    isCreateCover: 1
  }
  UploadFileToSystem(UploadConfig, path, file, uploadLoadding, callback, configObj)
}

// 上传Blob视频文件到本地服务器
export function UploadViittoBlobFile(path, file, callback) {
  var uploadLoadding = Loading;
  uploadLoadding.show({
    message: '正在上传文件,请稍后...'
  })
  let viewFileUrl = 'http://192.168.20.214:8130';
  let vtUploadUrl = "http://192.168.20.214:8120/upload/UploadBlob";
  let locationName = window.location.hostname;
  if (locationName.indexOf('testerp.oytour') !== -1) {
    vtUploadUrl = "http://upload.oytour.com/upload/UploadBlob";
    viewFileUrl = "https://imgfile.oytour.com";
  } else if (locationName.indexOf('oytour') !== -1) {
    vtUploadUrl = "http://upload.oytour.com/upload/UploadBlob";
    viewFileUrl = "https://imgfile.oytour.com";
  }
  var UploadConfig = {
    Bucket: "系统",
    CustomDomain: viewFileUrl,
    Region: "成都",
    SecretId: "SecreId",
    SecretKey: "SecreKey",
    StoreType: 3,
    UploadDomain: vtUploadUrl,
  };
  var configObj = {
    isCreateCover: 1
  }
  UploadBolbFileToSystem(UploadConfig, path, file, uploadLoadding, callback, configObj)
}
/**
 * 上传bolb文件到本地文件系统
 */
export function UploadBolbFileToSystem(uploadConfig, fileFullPath, fileObj, uploadLoadding, successCall, configObj) {
  let url = uploadConfig.UploadDomain + "/Upload?filePath=" + fileFullPath;
  if (configObj) {
    //是否转换图片
    if (configObj.isTrans && configObj.isTrans == 1) {
      url += "&isTrans=1"
    }
    if (configObj.isCreateCover && configObj.isCreateCover == 1) {
      url += "&isCreateCover=1"
    }
  }
  let formData = new FormData()
  formData.append('myfile', fileObj)
  let xhr = new XMLHttpRequest()
  xhr.onload = function () {
    uploadLoadding.hide();
    var jsonObj = JSON.parse(xhr.responseText);
    if ((jsonObj.StatusCode === 1 || jsonObj.StatusCode === 0) && 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 UploadLocalSystem(configObj, fileObj, successCall) {
  var uploadLoadding = Loading;
  uploadLoadding.show({
    message: '正在上传文件,请稍后...'
  })
  let url = process.env.API + "/Upload/UploadFile";
  let formData = new FormData()
  if (configObj) {
    formData.append("params", configObj);
  }
  formData.append('myfile', fileObj)
  let xhr = new XMLHttpRequest()
  xhr.onload = function () {
    uploadLoadding.hide();
    var jsonObj = JSON.parse(xhr.responseText);
    if (jsonObj && jsonObj.StatusCode && jsonObj.StatusCode == 1 && successCall) {
      var uploadResult = {
        Code: 1,
        FileName: fileObj.name,
        FileUrl: process.env.API + jsonObj.FilePath,
        VideoCoverImg: process.env.API + jsonObj.VideoCoverImg,
        Data: jsonObj.Data
      }
      if (successCall) {
        successCall(uploadResult);
      }
    }
    if (jsonObj && jsonObj.Code && jsonObj.Code == 1 && successCall) {
      var uploadResult = {
        Code: 1,
        Data: jsonObj.Data,
        Message: jsonObj.Message
      }
      if (successCall) {
        successCall(uploadResult);
      }
    }
  }
  xhr.open('post', url, true)
  xhr.send(formData)
}

/**
 * 上传文件到本地文件系统
 */
export function UploadFileToSystem(uploadConfig, fileFullPath, fileObj, uploadLoadding, successCall, configObj) {
  let url = uploadConfig.UploadDomain + "/Upload?filePath=" + fileFullPath;
  if (configObj) {
    //是否转换图片
    if (configObj.isTrans && configObj.isTrans == 1) {
      url += "&isTrans=1"
    }
    if (configObj.isCreateCover && configObj.isCreateCover == 1) {
      url += "&isCreateCover=1"
    }
  }
  let formData = new FormData()
  formData.append('myfile', fileObj)
  let xhr = new XMLHttpRequest()
  xhr.onload = function () {
    uploadLoadding.hide();
    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, uploadLoadding, 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 => {
    uploadLoadding.hide();
    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, uploadLoadding, 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) {
    uploadLoadding.hide();
    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 downloadLocalFile(fileName, filePath) {
  const a = document.createElement('a');
  a.setAttribute('download', '');
  var url = process.env.API;
  a.setAttribute('href', url + '/Upload/DownloadFileForPdf?fileName=' + fileName + '.pdf&fPath=' + filePath);
  a.click();
}

/**
 * 获取省市区
 */
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, callBack) {
  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();
    if (callBack) {
      var result = {
        Code: 1
      };
      callBack(result);
    }
  })
}
