import { connect } from 'root/wmp-redux'
import iconPaths from 'root/constants/blog/iconPaths'
import { cutString, saveCanvasImage } from 'root/utils/helpers/helper'
import { getImageInfo } from 'wechat_common/utils/helpers/shareHelper'
import { getSharing } from 'root/selectors/blog/sharing'
import { replaceQnDomain } from 'wechat_common/utils/helpers/imageHelper'
import { formatProtocol } from 'wechat_common/utils/utils'
import urls from 'root/constants/blog/urls'
import { getPosts } from 'root/selectors/blog/post'
import { getPostDetail } from 'root/selectors/blog/postDetail'

const { iconDownload } = iconPaths

const TITLE_PER_LINE_WORDS = 16
const TITILE_MAX_LINES = 2
const CONTENT_PER_LINE_WORDS = 19
const CONTENT_MAX_LINES = 6
const NAME_PER_LINE_WORDS = 9
const NAME_MAX_LINES = 1

const page = {
  data: {
    iconDownload,
    hasDrawn: false,
  },
  onLoad(option) {
    const { postList } = this.data
    const { postId } = option
    const { blurb, title: headerTitle, iconUrl: backgroundUrl } = postList.find(
      item => item.id == postId,
    )
    const { officialName = '', officialIconUrl, sceneCodeUrl } = this.data
    const title = cutString(headerTitle, TITLE_PER_LINE_WORDS * 2)
    const content = cutString(blurb, CONTENT_PER_LINE_WORDS * 2)
    const name = cutString(officialName, NAME_PER_LINE_WORDS * 2)
    const { screenWidth, screenHeight } = wx.getSystemInfoSync()

    const promiseList = [backgroundUrl, officialIconUrl].map(url =>
      getImageInfo(formatProtocol(replaceQnDomain(url))),
    )

    const ctx = wx.createCanvasContext('share-image')

    Promise.all(promiseList)
      .then(([backgroundUrl, officialIconUrl]) => {
        ctx.scale(screenWidth / 375, screenWidth / 375)
        ctx.setFillStyle('white')
        ctx.fillRect(0, 0, 329, 476)
        ctx.drawImage(backgroundUrl.path, 0, 0, 329, 189.5)
        ctx.setFillStyle('rgba(0, 0, 0, 0.2)')
        ctx.fillRect(0, 0, 329, 189.5)
        ctx.setFontSize(18)
        ctx.setFillStyle('#ffffff')
        ctx.setTextAlign('left')
        title.slice(0, TITILE_MAX_LINES).forEach((item, index) => {
          if (
            title.length > TITILE_MAX_LINES &&
            index === TITILE_MAX_LINES - 1
          ) {
            item = `${item.slice(0, item.length - 1)}...`
          }
          ctx.fillText(item, 18, 155 + index * 22)
        })
        ctx.setFontSize(15)
        ctx.setFillStyle('#222222')
        content.slice(0, CONTENT_MAX_LINES).forEach((item, index) => {
          if (
            content.length > CONTENT_MAX_LINES &&
            index === CONTENT_MAX_LINES - 1
          ) {
            item = `${item.slice(0, item.length - 1)}...`
          }
          ctx.fillText(item, 18, 220 + index * 24)
        })
        const grd = ctx.createLinearGradient(0, 245, 0, 355)
        grd.addColorStop(0, 'rgba(255, 255, 255, 0)')
        grd.addColorStop(1, 'white')
        ctx.setFillStyle(grd)
        ctx.fillRect(0, 245, 329, 100)
        ctx.save()
        ctx.beginPath()
        ctx.arc(43, 401, 23, 0, 2 * Math.PI)
        ctx.clip()
        ctx.drawImage(officialIconUrl.path, 20, 378, 46, 46)
        ctx.restore()
        ctx.setFillStyle('#222222')
        ctx.setTextAlign('left')
        ctx.setFontSize(14)
        name.slice(0, NAME_MAX_LINES).forEach((item, index) => {
          if (name.length > NAME_MAX_LINES && index === NAME_MAX_LINES - 1) {
            item = `${item.slice(0, item.length - 1)}...`
          }
          ctx.fillText(item, 72, 395)
        })
        ctx.setFontSize(12)
        ctx.setFillStyle('#bbbbbb')
        ctx.fillText('扫码查看完整文章', 72, 417)
        return getImageInfo(replaceQnDomain(sceneCodeUrl))
      })
      .then(sceneCodeUrl => {
        ctx.drawImage(sceneCodeUrl.path, 201, 350, 110, 110)
        ctx.draw()
        this.setData({
          hasDrawn: true,
        })
      })
      .catch(e => {
        ctx.draw()
        this.setData({
          hasDrawn: true,
        })
        wx.showModal({
          title: '网络错误',
          content: '图片生成失败',
          showCancel: false,
        })
      })
  },
  saveImage() {
    saveCanvasImage('share-image')
  },
}

function mapStateToProps(state, ownProps) {
  const { officialName, officialIconUrl, sceneCodeUrl } = getSharing(state)
  const { list: postList } = getPosts(state, urls.PAGES.POST_INDEX)
  const { headerTitleString, backgroundUrl } = getPostDetail(state)

  return {
    officialName,
    officialIconUrl,
    sceneCodeUrl,
    headerTitleString,
    backgroundUrl,
    postList,
  }
}

const connectedPage = connect(page, mapStateToProps, {})
Page(connectedPage)
