import request from '@/utils/request'
import axios from 'axios'

class CommonSet {
  fetchCommonSet() {
    return request({
      url: '/setCenter/GeneralSet/index',
      method: 'get'
      // params: { webId }
    })
  }

  updateData(data) {
    return request({
      url: '/setCenter/GeneralSet/index',
      method: 'post',
      headers: { 'Content-Type': 'text/plain' },
      data
    })
  }

  loadFileList(params) {
    return request({
      url: '/FileManage/list',
      method: 'get',
      params: params
    })
  }

  /**
   * 上传文件
   *
   * @param {*} file file文件
   * @param {*} fileId 文件夹id，空为根目录
   * @param {*} modName 模块/文件夹名称，用于直接上传时模块分类
   * @memberof CommonSet
   */
  uploadFile(file, fileId, modName) {
    var params = { saveName: file.name }
    if (fileId) {
      params['fileId'] = fileId
    } else {
      params['fileId'] = ''
    }
    if (modName) {
      params['fileName'] = modName
    } else {
      params['fileName'] = ''
    }

    return this._getUploadToken(params).then(response => {
      const { data } = response
      const { key, host, scheme, token } = data
      return this._uploadFile(
        scheme + '://' + host,
        'post',
        key,
        token,
        file.raw
      )
    })
  }

  /**
   * 获取文件上传参数，私有方法，尽量不用调用
   *
   */
  _getUploadToken(params) {
    return request({
      url: '/Upload/getToken',
      method: 'post',
      headers: { 'Content-Type': 'text/plain' },
      data: params
    })
  }

  // 上传文件
  _uploadFile(url, method, filename, token, file) {
    var formData = new FormData()
    formData.append('key', filename)
    formData.append('token', token)
    formData.append('file', file)

    // return request({
    //   url: '',
    //   method: method,
    //   data: formData,
    //   headers: { 'Content-Type': 'multipart/form-data' },
    //   baseURL: url
    // })

    // 使用axios请求，防止出现跨域问题导致上传失败
    return axios(url, {
      method: method,
      mode: 'no-cors',
      headers: {
        'Access-Control-Allow-Origin': '*',
        'Content-Type': 'application/json'
      },

      data: formData,
      withCredentials: false,
      credentials: 'same-origin'
    }).then(response => {
      return response.data
    })
  }
}

export default CommonSet
