import { getQnUrl } from 'wechat_common/utils/helpers/imageHelper'

export function getMixLayout(mix, layout, type, isMain) {
  const index = isMain ? 0 : 1
  if(Array.isArray(mix) && Array.isArray(layout) && mix[index] === type){
    return layout[index]
  }
  return layout
}

// Chinese character、full Angle symbol takes up two widths
// English character、half - Angle symbol takes up one widths
export function cutString(str, width) {
  const re = /[^\x00-\xff]/g
  const result = []
  let cnlen = 0
  if (str.match(re)) {
    cnlen = str.match(re).length
  }
  let strlen = Number(str.length) + cnlen
  while (strlen > width) {
    let tmplen = 0
    let index = 0
    for (let i = 0; i < str.length; i++) {
      if (str[i].match(re)) {
        tmplen += 2
      } else {
        tmplen++
      }
      if (tmplen > width) {
        index = i
        break
      }
    }
    result.push(str.substring(0, index))
    str = str.substring(index)
    if (str.match(re)) {
      cnlen = str.match(re).length
    }
    strlen = Number(str.length) + cnlen
  }
  result.push(str)
  return result
}

// save the canvas as a image
export function saveCanvasImage(canvasId) {
  wx.canvasToTempFilePath({
    canvasId: canvasId,
    success(res) {
      const filePath = res.tempFilePath
      wx.getSetting({
        success(res) {
          if (!res.authSetting['scope.writePhotosAlbum']) {
            wx.authorize({
              scope: 'scope.writePhotosAlbum',
              success() {
                wx.saveImageToPhotosAlbum({
                  filePath,
                  success(result) {
                    wx.showToast({
                      title: '保存成功',
                      icon: 'success',
                      duration: 2000,
                    })
                  },
                  fail(result) {
                    console.log(result)
                  },
                })
              },
              fail() {
                wx.showModal({
                  title: '提示',
                  content: '保存图片需要进行授权操作，请前往小程序设置页完成授权。',
                  showCancel: false,
                })
              },
            })
          } else {
            wx.saveImageToPhotosAlbum({
              filePath,
              success(result) {
                wx.showToast({
                  title: '保存成功',
                  icon: 'success',
                  duration: 2000,
                })
              },
            })
          }
        },
      })
    },
  })
}

// canvas draw image need use this api to get image local path
export const getImageInfo = function(url) {
  return new Promise((resolve, reject) => {
    wx.getImageInfo({
      src: url,
      success: res => resolve(res),
      fail: e => reject(e),
    })
  })
}

export function parseUploadImage(upload) {
  const uploadImage = []
  const previewImage = []
  if (upload) {
    upload.forEach(image => {
      uploadImage.push({
        productId: image.productId,
        hash: image.hash,
        image: getQnUrl(image),
      })
      previewImage.push({
        productId: image.productId,
        url: getQnUrl(image)
      })
    })
  }
  return {
    uploadImage,
    previewImage,
  }
}

export function extendMethod(...fns) {
  return function(...args) {
    fns.forEach(
      fn => (typeof fn === 'function' ? fn.bind(this)(...args) : null),
    )
  }
}
