import './sd-watermark.scss'
// 画布可以在多个水印实例间共享
const height = 500
const width = 500
const fontSize = 20

// 根据45度角，计算出文字的起点位置+最大宽度
const startX = -0.707 * (height - fontSize) + 10
const startY = 0.707 * (height - fontSize / 2)
const maxWidth = 1.4 * height - 40

const canvas = document.createElement('canvas')
canvas.width = width
canvas.height = height
const ctx = canvas.getContext('2d')
ctx.font = `${fontSize}px "-apple-system", "BlinkMacSystemFont", "Segoe UI", "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "Helvetica Neue", "Helvetica", "Arial", "sans-serif", "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol"`

let seq = 0

function bind(el, binding) {
  // 每个水印生成一个id
  seq++
  el.classList.add('sd-watermark')
  el.dataset.sdWatermark = seq
  // 创建每个水印对应的标签
  const styleEl = document.createElement('style')
  styleEl.id = 'sd-watermark-' + seq
  document.head.appendChild(styleEl)
  // 第一次绑定时，更新水印
  doUpdate(el, binding)
}

function update(el, binding) {
  const text = binding.value.text || binding.value
  const oldText = binding.oldValue.text || binding.oldValue
  // 后续只有文本发生了变化，才更新
  if (text !== oldText) {
    doUpdate(el, binding)
  }
}

function doUpdate(el, binding) {
  const text = binding.value.text || binding.value
  if (!text) return

  // 清除旧的内容
  ctx.clearRect(0, 0, canvas.width, canvas.height)
  // 写上新的内容
  ctx.rotate(-Math.PI / 4)
  ctx.fillText(text, startX, startY, maxWidth)
  ctx.rotate(Math.PI / 4)

  const style = document.getElementById('sd-watermark-' + el.dataset.sdWatermark)
  // @ts-ignore
  const styleSheet = style.sheet
  // 删除旧的css规则
  if (styleSheet.cssRules.length > 0) styleSheet.deleteRule(0)
  // 写入新的css规则
  styleSheet.insertRule(
    `.sd-watermark[data-sd-watermark="${
      el.dataset.sdWatermark
    }"]::after{background-image:url(${canvas.toDataURL()})}`,
    0
  )
}

function unbind(el) {
  // 销毁水印相关的 style 标签
  const style = document.getElementById('sd-watermark-' + el.dataset.sdWatermark)
  style.parentNode.removeChild(style)
}

export default {
  bind,
  update,
  unbind,
}
