
import Axios from '@/api/axios'
import {getStoreGetter} from '@/store/utils'
import { Loading } from 'quasar'

/**
 * 配置相关
 */
export function CommonConfig() {
  return {
    FileConfig: {
      FileUrl: 'http://192.168.20.214:8130', //本地服务器文件预览地址
      UploadUrl: 'http://192.168.20.214:8120' //本地上传文件地址
    }
  }
}

/**
 * 上传文件
 */
// interface uploadConfigParams {

// }
  //用户登录缓存
const cacheInfo = getStoreGetter('user', 'getLoginUserInfo')
export function UploadSelfFile(path, file, callback, configObj?) {
  //上传配置
  let uploadConfig: any = {}
  if ( cacheInfo.UploadConfig ) {
    uploadConfig = JSON.parse(JSON.stringify(cacheInfo.UploadConfig)) 
  }
  //获取文件扩展名
  const index = file.name.lastIndexOf('.')
  const suffix = file.name.substr(index)
  const timestamp1 = Date.parse(new Date().toString()) + '_' + Math.ceil(Math.random() * 1000)
  const str = '/Test'
  let newPath = '/EduSystem' + str + '/Upload/' + path
  const 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) {
  const uploadLoadding = Loading
  uploadLoadding.show({
    message: '正在上传文件,请稍后...'
  })
  const fileConfig = CommonConfig()
  let viewFileUrl = fileConfig.FileConfig.FileUrl
  let vtUploadUrl = fileConfig.FileConfig.UploadUrl
  const 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'
  }
  const UploadConfig = {
    Bucket: '系统',
    CustomDomain: viewFileUrl,
    Region: '成都',
    SecretId: 'SecreId',
    SecretKey: 'SecreKey',
    StoreType: 3,
    UploadDomain: vtUploadUrl
  }
  const configObj = {
    isCreateCover: 1
  }
  UploadFileToSystem(UploadConfig, path, file, uploadLoadding, callback, configObj)
}

// 上传Blob视频文件到本地服务器
export function UploadViittoBlobFile(path, file, callback) {
  const uploadLoadding = Loading
  uploadLoadding.show({
    message: '正在上传文件,请稍后...'
  })
  let viewFileUrl = 'http://192.168.20.214:8130'
  let vtUploadUrl = 'http://192.168.20.214:8120/upload/UploadBlob'
  const 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'
  }
  const UploadConfig = {
    Bucket: '系统',
    CustomDomain: viewFileUrl,
    Region: '成都',
    SecretId: 'SecreId',
    SecretKey: 'SecreKey',
    StoreType: 3,
    UploadDomain: vtUploadUrl
  }
  const 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'
    }
  }
  const formData = new FormData()
  formData.append('myfile', fileObj)
  const xhr = new XMLHttpRequest()
  xhr.onload = function () {
    uploadLoadding.hide()
    const jsonObj:any = JSON.parse(xhr.responseText)
    if ((jsonObj.StatusCode === 1 || jsonObj.StatusCode === 0) && successCall) {
      const tempArray:Array<any> = []
      if (jsonObj.OtherFile && jsonObj.OtherFile.length > 0) {
        jsonObj.OtherFile.forEach(item => {
          tempArray.push(uploadConfig.CustomDomain + item)
        })
      }
      
      const 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 UploadFileToSystem(uploadConfig, fileFullPath, fileObj, uploadLoadding, successCall, configObj) {
  // const fileConfig = CommonConfig()
  // const 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'
    }
  }
  const formData = new FormData()
  formData.append('myfile', fileObj)
  const xhr = new XMLHttpRequest()
  xhr.onload = function () {
    uploadLoadding.hide()
    const jsonObj = JSON.parse(xhr.responseText)
    if (jsonObj.StatusCode === 1 && successCall) {
      const tempArray:Array<any> = []
      if (jsonObj.OtherFile && jsonObj.OtherFile.length > 0) {
        jsonObj.OtherFile.forEach(item => {
          tempArray.push(uploadConfig.CustomDomain + item)
        })
      }
      const uploadResult = {
        Code: 1,
        Size: (fileObj.size/1000).toFixed(2)+'KB',
        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) {
  // const OSS = require('ali-oss')
  // // const oss = new OSS({
  // //   region: uploadConfig.Region,
  // //   accessKeyId: uploadConfig.SecretId,
  // //   accessKeySecret: uploadConfig.SecretKey,
  // //   bucket: uploadConfig.Bucket
  // // })
  // // const result = oss
  //   .multipartUpload(fileFullPath, fileObj, {
  //     progress: function (p) {
  //       console.log('ali',p)
  //     }
  //   })
  //   .then(res => {
  //     uploadLoadding.hide()
  //     const 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) {
  // const COS = require('cos-js-sdk-v5')
  // const 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) {
  //       console.log('progressData', progressData)
  //     }
  //   },
  //   function (err, data) {
  //     uploadLoadding.hide()
  //     if (data && data.statusCode == 200) {
  //       const 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', '')
  const url = process.env.BASE_APP_API
  a.setAttribute('href', url + '/Upload/DownloadFileForPdf?fileName=' + fileName + '.pdf&fPath=' + filePath)
  a.click()
}


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

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

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

/**
 * 上传文件 企微写死阿里云
 */
// export function wechatUploadSelfFile(path, file, callback) {
//   //用户登录缓存
//   //配置写死的 腾讯云
//   const uploadConfig = {
//     Region: 'ap-chengdu',
//     SecretId: 'AKIDDPnbIzi8C1eqEOPP8dw6MNAg9H9ldDKd',
//     SecretKey: 'PdcLtOjslUzNFYdU4OSI1fKtdHpFT2Ob',
//     Bucket: 'viitto-1301420277'
//   }
//   //获取文件扩展名
//   const index = file.name.lastIndexOf('.')
//   const suffix = file.name.substr(index)
//   const timestamp1 = Date.parse(new Date()) + '_' + Math.ceil(Math.random() * 1000)
//   const str = '/Test'
//   let newPath = '/EduSystem' + str + '/Upload/' + path
//   const uploadLoadding = Loading
//   uploadLoadding.show({
//     message: '正在上传文件,请稍后...'
//   })
//   if (uploadConfig) {
//     newPath += '/' + timestamp1 + '' + suffix
//     UploadFileToTencent(uploadConfig, newPath, file, uploadLoadding, callback)
//   }
// }


/**
 * 上传到当前站点
 */
export function UploadLocalSystem(configObj, fileObj, successCall) {
  const uploadLoadding = Loading
  uploadLoadding.show({
    message: '正在上传文件,请稍后...'
  })
  const url = process.env.BASE_APP_API + '/Upload/UploadFile'
  const formData = new FormData()
  if (configObj) {
    formData.append("params", configObj);
  }
  formData.append('myfile', fileObj)
  const xhr = new XMLHttpRequest()
  xhr.onload = function () {
    uploadLoadding.hide();
    const jsonObj = JSON.parse(xhr.responseText)
    if (jsonObj && jsonObj.StatusCode && jsonObj.StatusCode == 1 && successCall) {
      const uploadResult = {
        Code: 1,
        FileName: fileObj.name,
        FileUrl: process.env.BASE_APP_API + jsonObj.FilePath,
        VideoCoverImg: process.env.BASE_APP_API + jsonObj.VideoCoverImg,
        Data: jsonObj.Data
      }
      if (successCall) {
        successCall(uploadResult);
      }
    }
    if (jsonObj && jsonObj.Code && jsonObj.Code == 1 && successCall) {
      const uploadResult = {
        Code: 1,
        Data: jsonObj.Data,
        Message: jsonObj.Message
      }
      if (successCall) {
        successCall(uploadResult);
      }
    }
  }
  xhr.open('post', url, true)
  xhr.send(formData)
}