import CommonSet from '@/api/setting-center/CommonSet'
const log = console.log.bind(console)

class CommonSetApi {
  constructor() {
    this.api = new CommonSet()
  }
  getBase64FormUrl(url) {
    const p = new Promise((resolve, reject) => {
      const img = new Image()
      let result = ''
      img.crossOrigin = ''
      img.src = url
      img.onload = function() {
        var canvas = document.createElement('canvas')
        canvas.width = img.width
        canvas.height = img.height
        var ctx = canvas.getContext('2d')
        ctx.drawImage(img, 0, 0, img.width, img.height)
        var ext = img.src.substring(img.src.lastIndexOf('.') + 1).toLowerCase()
        var dataURL = canvas.toDataURL('image/' + ext)
        result = dataURL
        resolve(result)
      }
    })
    return p
  }

  async base64ByObject(animaList) {
    let pList = []
    animaList.map(item => {
      const p = this.getBase64FormUrl(item.img)
      pList.push(p)
    })
    await Promise.all(pList).then((i, index) => {
      pList = i
    })
    animaList.map((item, index) => {
      item.img = pList[index]
    })
  }

  async formateData(data) {
    const d = data
    const appLogo = await this.getBase64FormUrl('http://' + d.appLogo)
    const holderImage = await this.getBase64FormUrl('http://' + d.holderImage)
    const loadAnima = d.loadAnima
    await this.base64ByObject(loadAnima)
    let result = {
      appName: d.appName,
      appDesc: d.describe,
      appInviteType: d.inviteCodeSeting,
      appInviteLength: d.inviteLength,
      appLogo: appLogo,
      goodsBgImg: holderImage,
      appLoadingList: loadAnima,
      sharePlatform: d.shareList,
      sharePlatformIcon: d.platformList
    }
    result = JSON.stringify(result)
    // log(result, 'result')
    return result
  }

  // 更新提交数据
  async updata(data) {
    const formate = await this.formateData(data)
    // log(formate, 'in updata')
    const u = this.api.updata(formate)
    return u
  }

  cleanFileItem(item) {
    const i = item
    const result = {
      name: i.showName,
      id: i.fileFid,
      provider: i.provider,
      userName: i.userNickname,
      width: i.width,
      height: i.height,
      date: i.date,
      size: i.fileSize,
      imgUrl: 'http://' + i.imageUrl
    }
    log(result, 'result')
    return result
  }

  cleanFileList(fileList) {
    const f = fileList
    const result = []
    f.map(item => {
      result.push(this.cleanFileItem(item))
    })
    return result
  }
  // 获取通用设置图片文件管理列表
  loadFileList() {
    const l = this.api.loadFileList()
    return l.then(res => {
      const data = res.data.fileList
      // log(data, 'in loadFileList')
      return this.cleanFileList(data)
    })
  }

  loadFileList2(params) {
    const l = this.api.loadFileList(params)
    return l.then(res => {
      return res.data
    })
  }
}

const commonApi = new CommonSetApi()

export default commonApi
