import request from '../../utils/request'
import ds from '../../utils/erpindex'
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 CommonConfig() {
  return {
    FileConfig: {
      FileUrl: 'http://192.168.10.214:8130', //本地服务器文件预览地址
      UploadUrl:'http://192.168.10.214:8120'
    }
  }

}

/**
 * 上传文件 
 */
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 fileConfig = CommonConfig()
  let viewFileUrl = fileConfig.FileConfig.FileUrl;
  let vtUploadUrl = fileConfig.FileConfig.UploadUrl;
  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";
  } else if (locationName.indexOf('kookaku') !== -1) {
    vtUploadUrl = "https://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 fileConfig = CommonConfig();
  let locationName = window.location.hostname;
  if (locationName.indexOf('localhost') !== -1) {
    uploadConfig.UploadDomain = fileConfig.FileConfig.UploadUrl;
    uploadConfig.CustomDomain = fileConfig.FileConfig.FileUrl;
  }
  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"
    }
    if (configObj.isOcr && configObj.isOcr == 1) {
      url += "&ocr=1"
    }
    if (configObj.isTencentOcr && configObj.isTencentOcr == 1) {
      url += "&isTencentOcr=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,
        Message: jsonObj.Message
      }
      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 queryCountryList(data) {
  return request({
    url: '/Public/GetCountryList',
    method: 'post',
    data
  })
}

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

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

/**
 * 根据编号获取地区详情
 */
export function queryAreaInfo(data) {
  return request({
    url: '/Public/GetAreaInfo',
    method: 'post',
    data
  })
}

/**
 * 根据编号删除地区
 */
export function deleteArea(data) {
  return request({
    url: '/Public/RemoveArea',
    method: 'post',
    data
  })
}

/**
 * 新增修改地区
 */
export function saveArea(data) {
  return request({
    url: '/Public/SetArea',
    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);
    }
  })
}

/**
 * 上传文件 企微写死阿里云 
 */
export function wechatUploadSelfFile(path, file, callback, configObj) {
  //用户登录缓存
  //配置写死的 腾讯云
  var uploadConfig = {
    Region: "ap-chengdu",
    SecretId: "AKIDDPnbIzi8C1eqEOPP8dw6MNAg9H9ldDKd",
    SecretKey: "PdcLtOjslUzNFYdU4OSI1fKtdHpFT2Ob",
    Bucket: "viitto-1301420277"
  };
  //获取文件扩展名
  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) {
    newPath += "/" + timestamp1 + "" + suffix;
    UploadFileToTencent(uploadConfig, newPath, file, uploadLoadding, callback);
  }
}