import urls from '/constants/blog/urls'
import * as apis from '/api/blogApi'
import moment from '/lib/moment'
import { formatProtocol } from '/utils/utils'
import { getQnUrl } from '/utils/helpers/imageHelper'
import { html2json } from '/utils/wxParse/html2json'

import iconPaths from '/constants/blog/iconPaths'

function traverse(o, func) {
  for (const i in o) {
    func.apply(this, [i, o[i]])
    if (o[i] !== null && typeof o[i] === 'object') {
      // going one step down in the object tree!!
      traverse(o[i], func)
    }
  }
}

const {
  iconWechat,
  iconBookmark,
  iconBookmarked,
  iconLock,
  iconComment,
  iconLike,
  imgAvatar,
  iconShare,
  iconShareMessage,
  iconShareImage,
  homeBtn,
  iconMomentLike,
  iconMomentLikeGrey,
  iconMomentLikeTotal
} = iconPaths

const page = {
  data: {
    currentPost: {},
    iconWechat,
    iconBookmark,
    iconBookmarked,
    iconLock,
    iconComment,
    iconLike,
    imgAvatar,
    submitting: false,
    errorMessage: '',
    iconShare,
    iconShareMessage,
    iconShareImage,
    homeBtn,
    iconMomentLike,
    iconMomentLikeGrey,
    iconMomentLikeTotal,
    shareLoading: false,
    cachedSections: null,
    // mapStateToProps
    teamMemberId: '11363837',
    comments: [],
    isFetchingComments: false,
    totalCountComments: 1,
    paginationComments: {
      currentPage: 1,
      previousPage: null,
      nextPage: null,
      perPage: 9999,
      totalPages: 0,
      totalCount: 0
    },
    sections: [],
    headerTitle: '',
    headerTitleString: '',
    headerSubTitle: '',
    backgroundUrl: '',
    publishedAt: '',
    textColor: '',
    isLikingPost: false,
    enableComments: true,
    nickName: '',
    avatarUrl: '',
    canUseSearch: true,
    canUseCollection: false,
    canUseShare: false,
    siteId: '11363837',
    isFromSharedProductCard: false,
    isFromSharedProductQRCode: false,
    postId: '',
    showShareVariation: false,
    shareAnimation: {
      actions: [
        {
          animates: [
            {
              type: 'translateY',
              args: ['100%']
            }
          ],
          option: {
            transformOrigin: '50% 50% 0',
            transition: {
              duration: 400,
              timingFunction: 'ease',
              delay: 0
            }
          }
        }
      ]
    }
  },
  onLoad(options) {
    const { postId, scene } = options
    const postIdFromScene = decodeURIComponent(scene)
    this.setData({ postId: postId || postIdFromScene })
    this.fetchPostDetail(postId || postIdFromScene)
    this.fetchComments(postId || postIdFromScene)
  },
  fetchPostDetail(postId) {
    apis.getPostDetail(postId).then(({ data: { data } }) => {
      let currentPost = JSON.parse(JSON.stringify(data)),
        { content = { header: {} }, publishedAt } = currentPost,
        {
          header = { backgroundImage: {}, title: {} },
          sections = []
        } = content,
        { backgroundImage = {}, title = {}, subTitle = {} } = header,
        { url: backgroundUrl, textColor = 'light' } = backgroundImage

      const headerTitleString = title.value.replace(/<\/?[^>]+(>|$)/g, '')
      publishedAt = moment(publishedAt)
        .locale('zh-cn')
        .fromNow()

      backgroundUrl =
        backgroundUrl && backgroundUrl !== '!'
          ? backgroundUrl
          : getQnUrl(currentPost.content.header.backgroundImage)
      backgroundUrl = formatProtocol(backgroundUrl).replace('.mp4', '.jpg')

      const textList = [
        'Blog.Quote',
        'Quote',
        'Blog.Text',
        'RichText',
        'Blog.Title',
        'Title'
      ]
      traverse(currentPost, (key, value) => {
        if (value) {
          if (textList.includes(value.type)) {
            value.value = html2json(value.value)
          } else if (value.type === 'Image' || value.type === 'Blog.Image') {
            value.imageUrl =
              value.url && value.url !== '!' ? value.url : getQnUrl(value)
          }
        }
      })

      const headerTitle = currentPost.content.header.title.value
      const headerSubTitle = currentPost.content.header.subTitle.value

      this.setData({
        currentPost: data,
        sections,
        headerTitle,
        headerTitleString,
        headerSubTitle,
        publishedAt,
        backgroundUrl,
        textColor
      })
    })
  },
  fetchComments(postId, pageNum = 1) {
    this.setData({
      isFetchingComments: true
    })
    apis.getComments(postId, pageNum).then(({ data: { data } }) => {
      this.setData({
        comments: data,
        isFetchingComments: false
      })
    })
  },
  bindShare() {
    wx.showShareMenu({
      withShareTicket: true
    })
  },
  bindMark() {
    this.setData({
      'currentPost.marked': true
    })
    wx.showToast({
      title: '已收藏',
      icon: 'success'
    })
  },
  bindUnmark() {
    this.setData({
      'currentPost.marked': false
    })
    wx.showToast({
      title: '已取消收藏',
      icon: 'success'
    })
  },
  bindTextAreaChange(e) {
    this.setData({
      currentComment: e.detail.value
    })
  },
  // bindGetUserInfoHandler,
  onClickSubmit(e) {
    const { currentComment } = this.data
    if (!currentComment || !currentComment.trim()) {
      this.setError('评论内容不能为空')
    } else if (wx.isWept) {
      this.setError('预览模式下暂不支持，请手机预览')
    } else {
      this.createComment(e.detail.formId)
    }
  },
  createComment(formId) {
    const { currentPost, currentComment, nickName, avatarUrl } = this.data

    if (!nickName && !avatarUrl) {
      return
    }
    const that = this
    this.setData({
      submitting: true
    })
    const sendData = {
      content: currentComment,
      nickname: nickName,
      wechat_photo: [avatarUrl],
      settings: {
        form_id: formId
      }
    }
    wrappedWXTool.login({
      success: loginRes => {
        sendData.code = loginRes.code
        that.setComments(
          currentPost.id,
          sendData,
          () => {
            that.setData({
              submitting: false,
              currentComment: ''
            })
            wx.showToast({
              title: '评论成功，审核通过后显示在留言列表',
              icon: 'none',
              duration: 2000
            })
          },
          () => {
            that.setData({ submitting: false })
          }
        )
      },
      fail() {
        wx.showModal({
          content: '请求失败，请重试'
        })
        that.setData({
          submitting: false
        })
      }
    })
  },
  showImage(e) {
    wx.previewImage({
      urls: [e.target.dataset.imageUrl]
    })
  },
  loadMoreComment() {
    const { paginationComments, postIdString } = this.data

    if (paginationComments.nextPage) {
      this.fetchComments(postIdString, paginationComments.nextPage)
    }
  },
  onIsExtend(e) {
    const currentId = e.currentTarget.dataset.eventId
    this.onExtend(currentId)
  },
  onIsReplyExtend(e) {
    const currentId = e.currentTarget.dataset.eventId
    this.onReplyExtend(currentId)
  },

  gotoHome() {
    wx.switchTab({
      url: urls.PAGES.POST_INDEX
    })
    this.setGlobalData({
      isFromSharedProductCard: false,
      isFromSharedProductQRCode: false
    })
  },

  onShareAppMessage() {
    const { currentPost, headerTitleString } = this.data
    return {
      title: headerTitleString,
      path: `/pages/blog/postDetail/postDetail?postId=${currentPost.id}`
    }
  },
  sharePicture() {
    const {
      siteId,
      currentPost: { id: postId }
    } = this.data
    if (wx.isWept) {
      this.setError('预览模式下暂不支持，请手机预览')
    } else {
      this.setData({
        shareLoading: true
      })
      this.fetchPostSharing(siteId, {
        scene: postId.toString(),
        page: 'pages/blog/postDetail/postDetail'
      }).then(res => {
        this.setData({
          shareLoading: false
        })
        if (res.success) {
          wx.navigateTo({
            url: `${urls.PAGES.POST_SHARE}?postId=${postId}`
          })
        } else {
          wx.showModal({
            title: '获取分享信息错误',
            content: '请稍后重试',
            showCancel: false,
            success: res => {
              if (res.confirm) {
                this.closeShareView()
              }
            }
          })
        }
      })
    }
  },
  handleLike(e) {
    const { currentPost, isLikingPost } = this.data
    const { isLiked } = e.currentTarget.dataset
    const cb = userInfo => {
      const { nickName, avatarUrl } = userInfo
      if (!isLikingPost) {
        this.likePost(!isLiked, currentPost.id, nickName, avatarUrl)
        if (!isLiked) {
        }
      }
    }
  }
}

Page(page)
