import { connect } from 'root/wmp-redux'
import compose from 'ramda/src/compose'
import { fetchPosts, likePost } from 'root/actions/blog/post'
import urls from 'root/constants/blog/urls'
import iconPaths from 'root/constants/blog/iconPaths'

import { setComments } from 'root/actions/blog/comment'
import { fetchPostSharing } from 'root/actions/blog/sharing'
import { getPosts } from 'root/selectors/blog/post'
import { getAttr, getUserInfo } from 'root/selectors/common/global'
import { getComponents } from 'root/selectors/common/componentsSelector'
import {
  login,
  bindGetUserInfoHandler,
} from 'wechat_common/utils/wrappedWXTool'
import { getMixLayout } from 'root/utils/helpers/helper'

import shareView from 'root/templates/shareView/shareView'
import { trackUI } from 'wechat_common/tracker/index.bs'
import { getTeamMemberId } from 'root/selectors/presentation/teamMemberSelector'

const { iconComment, iconLike } = iconPaths

const page = {
  data: {
    currentCategory: 'all',

    iconComment,
    iconLike,

    shareLoading: false,
    selectedPostId: '',

    currentComment: '',
    isCommenting: false,
  },

  onLoad(options) {
    wx.setNavigationBarTitle({
      title: options.category,
    })
    this.setData({
      isFetchingPosts: true,
      currentCategory: options.category,
    })
    const { paginationPosts, siteId } = this.data
    if (!paginationPosts) {
      this.fetchPosts(siteId, options.category, 1)
    }
  },

  handlePost(e) {
    const { id } = e.currentTarget.dataset
    wx.navigateTo({ url: `${urls.PAGES.POST_DETAIL}?postId=${id}` })
  },

  loadMorePosts() {
    const { paginationPosts, siteId, currentCategory } = this.data
    if (paginationPosts.nextPage) {
      this.fetchPosts(siteId, currentCategory, paginationPosts.nextPage)
    }
  },

  handleCard(e) {
    const { post } = e.currentTarget.dataset
    this.setData({ currentPost: post })
  },
  onShareAppMessage() {
    const { currentPost = {}, showShareVariation, currentCategory } = this.data
    const { title, id } = currentPost
    if (id && showShareVariation) {
      return {
        title,
        path: `${urls.PAGES.POST_DETAIL}?postId=${id}`,
      }
    } else {
      return {
        path: `${urls.PAGES.POST_LIST}?category=${currentCategory}`,
      }
    }
  },
  sharePicture() {
    const { siteId, currentPost } = this.data
    const { id: postId } = currentPost
    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 { postId, isLiked } = e.currentTarget.dataset
    const cb = userInfo => {
      const { nickName, avatarUrl } = userInfo
      this.setData({ selectedPostId: '' })
      if (!isLiked) {
        trackUI(
          'likeBlogPost',
          postId,
          JSON.stringify({
            team_member_id: this.data.teamMemberId || -1,
            key: `likeBlogPost${postId}`,
          }),
        )
      }
      this.likePost(!isLiked, postId, nickName, avatarUrl)
    }

    bindGetUserInfoHandler(e, cb)
  },
  switchOperation(e) {
    const { post } = e.currentTarget.dataset
    const { selectedPostId } = this.data
    this.setData({
      isCommenting: false,
      currentComment: '',
      selectedPostId:
        selectedPostId && selectedPostId == post.id ? '' : post.id,
      currentPost: post,
    })
  },
  handleComment(e) {
    const cb = () => {
      this.setData({ isCommenting: true, selectedPostId: '' })
    }

    bindGetUserInfoHandler(e, cb)
  },
  handleInputComment(e) {
    this.setData({ currentComment: e.detail.value })
  },
  handleSendComment(e) {
    const { currentComment } = this.data
    if (!currentComment || !currentComment.trim()) {
      this.setError('评论内容不能为空')
    } else if (wx.isWept) {
      this.setError('预览模式下暂不支持，请手机预览')
    } else {
      this.setData({ isCommenting: false })
      this.createComment(e.detail.formId)
    }
  },
  createComment(formId) {
    const { currentPost, currentComment, nickName, avatarUrl } = this.data
    const that = this
    this.setData({
      submitting: true,
    })
    const sendData = {
      content: currentComment,
      nickname: nickName,
      wechat_photo: [avatarUrl],
      settings: {
        form_id: formId,
      },
    }
    login({
      success: loginRes => {
        sendData.code = loginRes.code
        that.setComments(
          currentPost.id,
          sendData,
          () => {
            that.setData({
              submitting: false,
              currentComment: '',
            })
            wx.showToast({
              title: '评论成功，审核通过后显示在留言列表',
              icon: 'none',
              duration: 2000,
            })
            trackUI(
              'commentBlogPost',
              currentPost.id,
              JSON.stringify({
                team_member_id: this.data.teamMemberId || -1,
                key: `commentBlogPost${currentPost.id}`,
              }),
            )
          },
          () => {
            that.setData({ submitting: false })
          },
        )
      },
      fail() {
        wx.showModal({
          content: '请求失败，请重试',
        })
        that.setData({
          submitting: false,
        })
      },
    })
  },

  handleGlobalTab() {
    this.setData({
      selectedPostId: '',
      isCommenting: false,
      currentComment: '',
    })
  },

  onPullDownRefresh() {
    const { siteId, currentCategory } = this.data
    this.fetchPosts(siteId, currentCategory, 1).then(res =>
      wx.stopPullDownRefresh(),
    )
  },
}

function mapStateToProps(state, options) {
  const {
      list: posts,
      isFetching: isFetchingPosts,
      pagination: paginationPosts,
    } = getPosts(state, `${urls.PAGES.POST_LIST}_${options.category}`),
    { siteId, layout, mix, companyName, name, logoUrl } = getAttr(state),
    enableComments = state.getIn([
      'blog',
      'setting',
      'settings',
      'enableComments',
    ])
  const { nickName, avatarUrl } = getUserInfo(state)

  let blogLayout = getMixLayout(mix, layout, 'blog')
  let components = []
  if (state.get('components') !== null) {
    components = getComponents(state, 'blog')
    const blogAndCategoryComp = components.find(
      comp => comp.type === 'blogAndCategory',
    )
    if (blogAndCategoryComp && blogAndCategoryComp.settings) {
      blogLayout = blogAndCategoryComp.settings.layout || 'a'
    }
  }
  const teamMemberId = getTeamMemberId(state)
  return {
    posts,
    isFetchingPosts,
    paginationPosts,
    enableComments,
    teamMemberId,
    siteId,
    layout: blogLayout,
    logoUrl,
    companyName,
    name,
    nickName,
    avatarUrl,
  }
}

function mapDispatchToProps(dispatch) {
  return {
    fetchPosts: (siteId, category, pageNum) =>
      dispatch(
        fetchPosts(
          `${urls.PAGES.POST_LIST}_${category}`,
          siteId,
          category,
          pageNum,
        ),
      ),
    fetchPostSharing: (siteId, data) =>
      dispatch(fetchPostSharing(siteId, data)),
    setComments: (postId, setData, successCb, failCb) =>
      dispatch(setComments(postId, setData, successCb, failCb)),
    likePost: (status, postId, nickName, avatarUrl) =>
      dispatch(likePost(status, postId, nickName, avatarUrl)),
  }
}

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

Page(enhance(page))
