import Taro from '@tarojs/taro'

export default function factory(selector) {
  return new Promise((resolve) => {
    const query = Taro.createSelectorQuery()
    query.select(selector)
      .node((res) => {
        const canvas = res.node
        resolve(posterSDK(canvas))
      })
      .exec()
  })
}

export function posterSDK(canvas) {
  let onError = (err) => console.error(err);
  const ctx = canvas.getContext('2d')

  /**
   * 初始化 canvas
   * @param {*} config 
   */
  function initCanvas(config) {
    canvas.width = config.canvas.width
    canvas.height = config.canvas.height

    // 默认白色背景
    ctx.fillStyle="#FFFFFF";
    ctx.fillRect(0, 0, canvas.width, canvas.height)
    ctx.save()
  }

  /**
   * 生成 canvas 可用 image
   * @param {*} canvas 
   * @param {*} url 
   * @returns 
   */
  function getImage(url) {
    return new Promise((resolve, reject) => {
      Taro.downloadFile({
        url,
        success: (res) => {
          if (res.statusCode === 200) {
            const image = canvas.createImage()
            image.onload = () => resolve(image)
            image.onerror = (err) => {
              onError('importImage', err)
              reject(err)
            }
            image.src = res.tempFilePath
          }
        },
        fail: (err) => {
          onError('downloadImage', err)
          reject(err)
        }
      })
    })
  }

  /**
   * 绘制图像
   * @param {*} ctx 
   * @param {*} image 
   * @param {*} conf 
   */
  function drawImage(image, conf) {
    ctx.save()
    if (conf.arc) {
      // 圆心
      const x = conf.x + conf.width / 2
      const y = conf.y + conf.height / 2
      const r = conf.width / 2
      ctx.arc(x, y, r, 0, 2 * Math.PI)
      ctx.clip()
    }
    
    ctx.drawImage(image, conf.x, conf.y, conf.width, conf.height)
    ctx.restore()
  }

  /**
   * 绘制文字
   * @param {*} ctx 
   * @param {*} text 
   * @param {*} conf 
   */
  function darwText(text, conf) {
    ctx.fillStyle = conf.fillStyle
    ctx.font = conf.font
    ctx.fillText(text, conf.x, conf.y, conf.maxWidth)
  }

  /**
   * canvas 转为图片
   * @param {*} type 
   * @param {*} encoderOptions 
   * @returns 
   */
  function toDataURL(type = 'image/jpeg', encoderOptions = 0.8) {
    return canvas.toDataURL(type, encoderOptions)
  }

  /**
   * 下载到本地
   * @param {*} options 
   * @returns 
   */
  function download(options) {
    return new Promise((resovle, reject) => {
      Taro.canvasToTempFilePath({
        canvas,
        fileType: 'jpg',
        quality: 0.8,
        ...(options || {}),
        success: (res) => resovle(res.tempFilePath),
        fail: (err) => {
          onError('exportImage', err)
          reject(err)
        },
      })
    })
  }

  function listenError(callback) {
    onError = callback
  }

  return {
    canvas,
    ctx,
    initCanvas,
    download,
    getImage,
    drawImage,
    darwText,
    toDataURL,
    onError: listenError,
  }
}
