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

// import { setComments } from 'root/actions/blog/comment'
// import { fetchPostSharing } from 'root/actions/blog/sharing'
// import { setError } from 'root/actions/common/error'
// import { getError } from 'root/selectors/common/error'
// import { getCategories } from 'root/selectors/blog/category'
// import { getPosts } from 'root/selectors/blog/post'
// import { getBanners, getShortcuts } from 'root/selectors/blog/setting'
// import { getUserInfo } from 'root/selectors/common/global'
// import {
//   getStyle,
//   getAttr,
//   getNavigationBar,
// } from 'root/selectors/common/global'
// import { getMixLayout } from 'root/utils/helpers/helper'
// import { getComponents } from 'root/selectors/common/componentsSelector'
// import {
//   login,
//   bindGetUserInfoHandler
// } from 'wechat_common/utils/wrappedWXTool'
// import { trackUI } from 'wechat_common/tracker/index.bs'
// // // import shareView from 'root/templates/shareView/shareView'
// import { getTeamMemberId } from 'root/selectors/presentation/teamMemberSelector'

const { iconComment, iconLike, iconSearch, iconSearchWhite } = iconPaths

const component = {
  properties: {
    showSlider: {
      type: Boolean,
      value: false
    },
    showShortcuts: {
      type: Boolean,
      value: false
    },
    showBlogPosts: {
      type: Boolean,
      value: true
    }
  },
  data: {
    currentTab: 'post',
    dotPosition: 0,
    iconComment: '/assets/blog/icon-comment.png',
    iconLike: '/assets/blog/icon-like.png',
    iconSearch: '/assets/blog/icon-search.png',
    iconSearchWhite: '/assets/blog/icon-white-search.png',
    shareLoading: false,
    selectedPostId: '',
    currentComment: '',
    isCommenting: false,
    posts: [
      {
        postedToWechat: false,
        publishedAt: '1 个月前',
        settings: {
          hideBlogDate: null,
        },
        relativeUrl: '/blog/96789f79667',
        approvedCommentsCount: 0,
        pendingCommentsCount: 0,
        publicUrl: 'http://site-376580-3028-5672.sxl.cn/blog/96789f79667',
        updatedAt: '2018-07-07T02:04:29.037-07:00',
        headerImage: {
          storageKey: null,
          backgroundVariation: null,
          noCompression: null,
          videoHtml: null,
          h: null,
          linkTarget: null,
          url: '//res.cloudinary.com/hrscywv4p/image/upload/c_limit,fl_progressive,h_1200,q_90,w_2000/wxewyckdmotqycwfb8pk.jpg',
          defaultValue: null,
          linkInputEnabled: null,
          s: null,
          descriptionInputEnabled: null,
          useImage: null,
          videoUrl: null,
          linkUrl: null,
          textColor: 'light',
          w: null,
          format: null,
          userClassName: null,
          type: 'Blog.BackgroundImage',
          id: 'f_0e58f04a-374f-47d0-a5f6-93205fa418c9',
          storage: null,
          sizing: 'cover',
        },
        state: 'published',
        firstContentImage: null,
        iconUrl: 'https://res.cloudinary.com/hrscywv4p/image/upload/c_limit,fl_progressive,h_1200,q_90,w_2000/wxewyckdmotqycwfb8pk.jpg',
        allTagsList: [
          '及',
        ],
        title: '添加博客标题',
        pinned: false,
        icon: {
          storageKey: null,
          backgroundVariation: null,
          noCompression: null,
          videoHtml: null,
          h: null,
          linkTarget: null,
          url: '//res.cloudinary.com/hrscywv4p/image/upload/c_limit,fl_progressive,h_1200,q_90,w_2000/wxewyckdmotqycwfb8pk.jpg',
          defaultValue: null,
          linkInputEnabled: null,
          s: null,
          descriptionInputEnabled: null,
          useImage: null,
          videoUrl: null,
          linkUrl: null,
          textColor: 'light',
          w: null,
          format: null,
          userClassName: null,
          type: 'Blog.BackgroundImage',
          id: 'f_0e58f04a-374f-47d0-a5f6-93205fa418c9',
          storage: null,
          sizing: 'cover',
        },
        blurb: '',
        id: 1622941,
        createdAt: '2018-06-27T05:53:29.801-07:00',
        likesString: '',
      },
      {
        postedToWechat: false,
        publishedAt: '1 个月前',
        settings: {
          hideBlogDate: null,
        },
        relativeUrl: '/blog/5671fc1179e',
        approvedCommentsCount: 0,
        pendingCommentsCount: 0,
        publicUrl: 'http://site-376580-3028-5672.sxl.cn/blog/5671fc1179e',
        updatedAt: '2018-07-07T02:04:07.562-07:00',
        headerImage: {
          storageKey: null,
          backgroundVariation: null,
          noCompression: null,
          videoHtml: null,
          h: null,
          linkTarget: null,
          url: '//assets.strikingly.com/static/backgrounds/blur/1.jpg',
          defaultValue: null,
          linkInputEnabled: null,
          s: null,
          descriptionInputEnabled: null,
          useImage: null,
          videoUrl: null,
          linkUrl: null,
          textColor: 'light',
          w: null,
          format: null,
          userClassName: null,
          type: 'Blog.BackgroundImage',
          id: 'f_f163553c-fe33-451c-b8b8-4e11c7beffbc',
          storage: null,
          sizing: 'cover',
        },
        state: 'published',
        firstContentImage: null,
        iconUrl: 'https://assets.strikingly.com/static/backgrounds/blur/1.jpg',
        allTagsList: [],
        title: '添加博客标题',
        pinned: false,
        icon: {
          storageKey: null,
          backgroundVariation: null,
          noCompression: null,
          videoHtml: null,
          h: null,
          linkTarget: null,
          url: '//assets.strikingly.com/static/backgrounds/blur/1.jpg',
          defaultValue: null,
          linkInputEnabled: null,
          s: null,
          descriptionInputEnabled: null,
          useImage: null,
          videoUrl: null,
          linkUrl: null,
          textColor: 'light',
          w: null,
          format: null,
          userClassName: null,
          type: 'Blog.BackgroundImage',
          id: 'f_f163553c-fe33-451c-b8b8-4e11c7beffbc',
          storage: null,
          sizing: 'cover',
        },
        blurb: '',
        id: 1694849,
        createdAt: '2018-07-07T02:03:29.403-07:00',
        likesString: '',
      },
    ],
    isFetchingPosts: false,
    paginationPosts: {
      currentPage: 1,
      previousPage: null,
      nextPage: null,
      perPage: 8,
      totalPages: 1,
      totalCount: 2,
    },
    enableComments: true,
    isLikingPost: false,
    categories: [
      {
        name: '及',
        count: 1,
        id: 28066,
        url: 'https://assets.sxlcdn.com/images/ecommerce/ecommerce-default-image.png',
      },
    ],
    isFetchingCategories: false,
    siteId: '11417761',
    layout: 'a',
    searchEnable: false,
    background: '#fff',
    isWhiteBackground: true,
    companyName: '',
    name: '',
    logoUrl: 'https://user-assets.sxlcdn.com/images/796/FrHBzlUnK-Gt018qFnq8-DKwvrc3.jpg?imageMogr2/strip/thumbnail/500x1000>/quality/90!/interlace/1/format/jpg',
    errorMessage: '',
    nickName: '',
    avatarUrl: '',
    shortcuts: [
      {
        iconType: 'square',
        id: 'cc7e704a-b47d-4bdf-9c7f-ae40e1de4fd3',
        type: 'page',
        url: 'https://user-assets.sxlcdn.com/images/376562/Frj2f53OLrwiz2ArUZCnt1SExckY.png?imageMogr2/strip/thumbnail/800x450>/format/png',
        name: 'A',
        value: '/pages/ecommerce/about/about',
        linkError: false,
      },
      {
        iconType: 'square',
        id: 'a8b6d2dd-9e6b-45b3-aa09-04a6609f6ffa',
        type: 'page',
        url: 'https://user-assets.sxlcdn.com/images/376562/Fsr-ix0nhHO9UJpWMqJxm86l6ZCA.png?imageMogr2/strip/thumbnail/800x450>/format/png',
        name: 'B',
        value: '/pages/ecommerce/about/about',
        linkError: false,
      },
      {
        iconType: 'square',
        id: 'e36d9873-0bac-48aa-abbf-5029946945d9',
        type: 'page',
        url: 'https://user-assets.sxlcdn.com/images/376562/FmfiJDD_rafmiMhEGUey1352Wze4.jpg?imageMogr2/strip/thumbnail/800x450>/interlace/1/format/jpg',
        name: 'C',
        value: '/pages/ecommerce/about/about',
        linkError: false,
      },
    ],
    shortcutsFirstLine: [],
    shortcutsSecondLine: [],
    shortcutsSecondLineWrapperClass: ' ',
    banners: [
      {
        type: '',
        url: 'https://uploads.sxlcdn.com/static/backgrounds/patterns/26.jpg',
      },
      {
        type: '',
        url: 'https://user-assets.sxlcdn.com/images/376562/Frj2f53OLrwiz2ArUZCnt1SExckY.png?imageMogr2/strip/thumbnail/800x450>/format/png',
      },
      {
        type: '',
        url: 'https://uploads.sxlcdn.com/static/backgrounds/patterns/24.jpg',
      },
      {
        type: '',
        url: 'https://uploads.sxlcdn.com/static/backgrounds/patterns/16.jpg',
      },
    ],
    tabs: [
      {
        id: 'post',
        name: '文章',
      },
      {
        id: 'category',
        name: '分类',
      },
    ],
    mix: [
      'store',
      'blog',
    ],
    navigationBar: {},
    showContactBtn: false,
    showSlider: true,
    showShortcuts: true,
    showBlogPosts: true,
    ifInPageDesign: true,
    isWept: false,
    showShareVariation: false,
    shareAnimation: {
      actions: [
        {
          animates: [
            {
              type: 'translateY',
              args: [
                '100%',
              ],
            },
          ],
          option: {
            transformOrigin: '50% 50% 0',
            transition: {
              duration: 400,
              timingFunction: 'ease',
              delay: 0,
            },
          },
        },
      ],
    },
  },
  ready() {
    wx.setNavigationBarTitle({ title: this.data.name })
  },
  handleTab(event) {
    this.setData({
      currentTab: event.currentTarget.dataset.id
    })
  },
  handleSearch() {
    // let { mix } = this.data,
    url = urls.PAGES.POST_SEARCH
    // if (mix && mix.length == 2) {
    //   if (mix[0] == 'store') {
    //     switch (mix[1]) {
    //       case 'blog':
    //         url = mixinUrls.PAGES.SEARCH
    //         break
    //       default:
    //         break
    //     }
    //   }
    // }
    wx.navigateTo({ url })
  },

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

  handleCategory(e) {
    const { id, name } = e.currentTarget.dataset
    wx.navigateTo({
      url: `${urls.PAGES.POST_LIST}?category=${name}&categoryId=${id}`
    })
  },

  handlePage(e) {
    const { id } = e.currentTarget.dataset
    const navigateUrl = [
      '/pages/blog/about/about',
      '/pages/ecommerce/about/about'
    ]
    if (navigateUrl.includes(id)) {
      wx.navigateTo({ url: id })
    } else {
      wx.switchTab({ url: id })
    }
  },

  handleSliderChange(e) {
    this.setData({
      dotPosition: e.detail.current
    })
  },

  makePhoneCall(e) {
    if (wx.isWept) {
      this.setError('预览模式下暂不支持拨打电话，请手机预览')
    } else {
      const { phone = '' } = e.currentTarget.dataset
      wx.makePhoneCall({
        phoneNumber: phone
      })
    }
  },
  liveChat() {
    if (wx.isWept) {
      this.setError('预览模式下暂不支持客服功能，请手机预览')
    }
  },
  share() {
    if (wx.isWept) {
      this.setError('预览模式下暂不支持分享功能，请手机预览')
    }
  },
  navigation(e) {
    const addressDetail = e.currentTarget.dataset.address
    const addressLocation = e.currentTarget.dataset.coordinate

    if (addressLocation) {
      const latitude = addressLocation.lat
      const longitude = addressLocation.lng
      wx.openLocation({
        latitude,
        longitude,
        scale: 18,
        address: addressDetail
      })
    }
  },

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

  handleCard(e) {
    const { post } = e.currentTarget.dataset
    this.setData({ currentPost: post })
  },
  onShareAppMessage() {
    const { currentPost = {}, showShareVariation } = this.data
    const { title, id } = currentPost
    if (id && showShareVariation) {
      return {
        title,
        path: `${urls.PAGES.POST_DETAIL}?postId=${id}`
      }
    } else {
      return {
        path: `${urls.PAGES.POST_INDEX}`
      }
    }
  },
  sharePicture() {
    const { siteId, currentPost } = this.data
    const { id: postId } = currentPost
    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 { isLikingPost } = this.data
    const { postId, isLiked } = e.currentTarget.dataset

    const cb = userInfo => {
      const { nickName, avatarUrl } = userInfo
      this.setData({
        selectedPostId: ''
      })
      if (!isLikingPost) {
        this.likePost(!isLiked, postId, nickName, avatarUrl)
        if (!isLiked) {
          trackUI(
            'likeBlogPost',
            postId,
            JSON.stringify({
              team_member_id: this.data.teamMemberId || -1,
              key: `likeBlogPost${postId}`
            })
          )
        }
      }
    }
    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 { nickName, avatarUrl, currentPost, currentComment } = 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() {
    this.fetchPosts(this.data.siteId, 'all', 1).then(res =>
      wx.stopPullDownRefresh()
    )
  }
}

// function mapStateToProps(state) {
//   const { list: categories, isFetching: isFetchingCategories } = getCategories(
//       state,
//     ),
//     {
//       list: posts,
//       isFetching: isFetchingPosts,
//       pagination: paginationPosts,
//       isLikingPost,
//     } = getPosts(state, urls.PAGES.POST_INDEX),
//     { mainBackground: background, isWhiteBackground } = getStyle(state),
//     { siteId, layout, searchEnable, mix, companyName, name, logoUrl } = getAttr(
//       state,
//     ),
//     { nickName, avatarUrl } = getUserInfo(state),
//     { navigationBar } = getNavigationBar(state),
//     {
//       shortcuts,
//       shortcutsFirstLine,
//       shortcutsSecondLine,
//       shortcutsSecondLineWrapperClass,
//     } = getShortcuts(state),
//     { errorMessage } = getError(state),
//     tabs = [{ id: 'post', name: '文章' }]
//   if (categories && categories.length) {
//     tabs.push({ id: 'category', name: '分类' })
//   }
//   const showContactBtn = state.getIn(['globalData', 'attr', 'showContactBtn'])
//   let blogLayout = getMixLayout(mix, layout, 'blog')

//   let ifInPageDesign = false
//   let components = []
//   let shortcutsLayout = ''

//   if (state.get('components') !== null) {
//     components = getComponents(state, 'blog')
//     ifInPageDesign = true
//     const blogAndCategoryComp = components.find(
//       comp => comp.type === 'blogAndCategory',
//     )
//     const shortcutsComp = components.find(comp => comp.type === 'shortcuts')
//     if (blogAndCategoryComp && blogAndCategoryComp.settings) {
//       blogLayout = blogAndCategoryComp.settings.layout || 'a'
//     }
//     if (shortcutsComp && shortcutsComp.settings) {
//       shortcutsLayout = shortcutsComp.settings.layout || 'circle'
//     }
//   }

//   // hack temporarily, will be removed in v2
//   if (Array.isArray(mix) && mix[0] === 'presentation') {
//     ifInPageDesign = false
//   }

//   const enableComments = state.getIn([
//     'blog',
//     'setting',
//     'settings',
//     'enableComments',
//   ])
//   const teamMemberId = getTeamMemberId(state)
// return
// }

// function mapDispatchToProps(dispatch) {
//   return {
//     fetchPosts: (siteId, category, pageNum) =>
//       dispatch(fetchPosts(urls.PAGES.POST_INDEX, siteId, category, pageNum)),
//     setError: errorMessage => dispatch(setError(errorMessage)),
//     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 = (shareView, connect(mapStateToProps, mapDispatchToProps))

Component(component)
