import { debounce } from 'wechat_common/utils/utils'
import { connect } from 'root/wmp-redux'
import { afterClearData } from 'root/actions/common/tools'
import {
  fetchPostsSearch,
  clearPostsSearch,
} from 'root/actions/blog/postSearch'
import urls from 'root/constants/blog/urls.js'
import iconPaths from 'root/constants/blog/iconPaths'

import { getPostsSearch } from 'root/selectors/blog/postSearch'
import { getStyle, getAttr } from 'root/selectors/common/global'

const { iconClear, iconLink, iconNoResult, iconClearWhite } = iconPaths

const page = {
  data: {
    keywords: '',
    isFirst: true,

    iconClear,
    iconClearWhite,
    iconLink,
    iconNoResult,
  },

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

  handleInput(event) {
    const value = event.detail.value
    this.setData({ isFirst: false, keywords: value })

    const { siteId, keywords } = this.data
    this.fetchPostsAfterClear(siteId, keywords, 1)
  },

  handleClear() {
    this.setData({ keywords: '' })

    this.clearPosts()
  },

  loadMorePosts() {
    let {
      paginationPosts: { pages, currPage },
      siteId,
      keywords,
      isFetchingPosts,
    } = this.data
    if (!isFetchingPosts && currPage < pages) {
      this.fetchPosts(siteId, keywords, ++currPage)
    }
  },
}

function mapStateToProps(state) {
  const {
      list: posts,
      isFetching: isFetchingPosts,
      pagination: paginationPosts,
    } = getPostsSearch(state, urls.PAGES.POST_SEARCH),
    { mainBackground: background, isWhiteBackground } = getStyle(state),
    { siteId } = getAttr(state)
  return {
    posts,
    isFetchingPosts,
    paginationPosts,

    siteId,
    background,
    isWhiteBackground,
  }
}

function mapDispatchToProps(dispatch) {
  const PAGE = urls.PAGES.POST_SEARCH
  return {
    clearPosts: () => dispatch(clearPostsSearch(PAGE)),
    fetchPosts: (siteId, keywords, pageNum) =>
      dispatch(fetchPostsSearch(PAGE, siteId, keywords, pageNum)),
    fetchPostsAfterClear: debounce(
      (siteId, keywords, pageNum) =>
        dispatch(
          afterClearData(
            clearPostsSearch(PAGE),
            fetchPostsSearch(PAGE, siteId, keywords, pageNum),
          ),
        ),
      600,
    ),
  }
}

const connectedPage = connect(page, mapStateToProps, mapDispatchToProps)
Page(connectedPage)
