import { connect } from 'root/wmp-redux'
import compose from 'ramda/src/compose'
import urls from 'root/constants/blog/urls'
import {
  fetchComments,
  setComments,
  onExtend,
  onReplyExtend,
  clearComments,
} from 'root/actions/blog/comment'
import { fetchPosts, likePost } from 'root/actions/blog/post'
import { fetchPostDetail, clearPostDetail } from 'root/actions/blog/postDetail'
import { setError } from 'root/actions/common/error'
import { fetchPostSharing } from 'root/actions/blog/sharing'
import { setGlobalData } from 'root/actions/common/global'

import Feature from 'root/constants/common/feature'
import iconPaths from 'root/constants/blog/iconPaths'

import { getComments } from 'root/selectors/blog/comment'
import { getPostDetail } from 'root/selectors/blog/postDetail'
import { getUserInfo, getAttr } from 'root/selectors/common/global'
import { getError } from 'root/selectors/common/error'
import { trackUI } from 'wechat_common/tracker/index.bs'

import { getTeamMemberId } from 'root/selectors/presentation/teamMemberSelector'

import wrappedWXTool, {
  bindGetUserInfoHandler,
} from 'wechat_common/utils/wrappedWXTool'

import shareView from 'root/templates/shareView/shareView'

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,
  },
  onLoad(options) {
    const { postId, scene } = options
    const postIdFromScene = decodeURIComponent(scene)
    wx.getExtConfig({
      success: res => {
        this.fetchPosts(res.extConfig.attr.siteId)
      },
    })
    this.setData({ postId: postId || postIdFromScene })
    this.fetchPostDetail(postId || postIdFromScene)
    this.fetchComments(postId || postIdFromScene)
  },
  onUnload() {
    this.clearPostDetail()
    this.clearComments()
  },
  onHide() {
    this.closeShareView()
  },
  afterStateChange() {
    /**
     * bug fix for RDT-777
     *
     * root cause: wx.previewImage will trigger onHide and onShow,
     *            which leads rerender due to our injected newOnShow method
     *
     * solution: Use a varible cachedSections to cache sections, and use the cached
     *           value until page is destroyed.
     */
    const { sections, cachedSections } = this.data
    if (!cachedSections && sections) {
      this.setData({
        cachedSections: sections,
      })
    }
  },
  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: '',
            })
            trackUI(
              'commentBlogPost',
              currentPost.id,
              JSON.stringify({
                team_member_id: this.data.teamMemberId || -1,
                key: `commentBlogPost${currentPost.id}`,
              }),
            )
            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 => {
        trackUI(
          'shareImageBlogPost',
          postId,
          JSON.stringify({
            team_member_id: this.data.teamMemberId || -1,
            key: `shareImageBlogPost${postId}`,
          }),
        )
        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) {
          trackUI(
            'likeBlogPost',
            currentPost.id,
            JSON.stringify({
              team_member_id: this.data.teamMemberId || -1,
              key: `likeBlogPost${currentPost.id}`,
            }),
          )
        }
      }
    }

    bindGetUserInfoHandler(e, cb)
  },
}

function mapStateToProps(state) {
  const {
    list: comments,
    isFetching: isFetchingComments,
    pagination: paginationComments,
    totalCount: totalCountComments,
  } = getComments(state)
  const {
    currentPost,
    isLikingPost,
    sections,
    headerTitle,
    headerTitleString,
    headerSubTitle,
    publishedAt,
    textColor,
    backgroundUrl,
  } = getPostDetail(state)
  const { nickName, avatarUrl } = getUserInfo(state)
  const { canUseSearch, canUseCollection, canUseShare } = Feature
  const { errorMessage } = getError(state)
  const { siteId } = getAttr(state)
  const enableComments = state.getIn([
    'blog',
    'setting',
    'settings',
    'enableComments',
  ])

  const isFromSharedProductCard = state.getIn([
    'globalData',
    'isFromSharedProductCard',
  ])
  const isFromSharedProductQRCode = state.getIn([
    'globalData',
    'isFromSharedProductQRCode',
  ])
  const teamMemberId = getTeamMemberId(state)
  return {
    comments,
    isFetchingComments,
    totalCountComments,
    paginationComments,
    isLikingPost,
    teamMemberId,
    currentPost,
    enableComments,
    sections,
    headerTitle,
    headerTitleString,
    headerSubTitle,
    backgroundUrl,
    publishedAt,
    textColor,
    nickName,
    avatarUrl,
    canUseSearch,
    canUseCollection,
    canUseShare,
    errorMessage,
    siteId,
    isFromSharedProductCard,
    isFromSharedProductQRCode,
  }
}

function mapDispatchToProps(dispatch) {
  return {
    fetchPosts: siteId => dispatch(fetchPosts(urls.PAGES.POST_INDEX, siteId)),
    fetchPostDetail: postId => dispatch(fetchPostDetail(postId)),
    clearPostDetail: () => dispatch(clearPostDetail()),
    clearComments: () => dispatch(clearComments()),
    onExtend: currentId => dispatch(onExtend(currentId)),
    onReplyExtend: currentId => dispatch(onReplyExtend(currentId)),
    fetchComments: (postId, pageNum) =>
      dispatch(fetchComments(postId, pageNum)),
    setComments: (postId, setData, successCb, failCb) =>
      dispatch(setComments(postId, setData, successCb, failCb)),
    setError: errorMessage => dispatch(setError(errorMessage)),
    fetchPostSharing: (siteId, data) =>
      dispatch(fetchPostSharing(siteId, data)),
    setGlobalData: data => dispatch(setGlobalData(data)),
    likePost: (status, postId, nickName, avatarUrl) =>
      dispatch(likePost(status, postId, nickName, avatarUrl)),
  }
}

const enhance = compose(shareView, connect(mapStateToProps, mapDispatchToProps))

Page(enhance(page))
