import { uniq } from '/lib/lodash/index'
import urls from '/constants/blog/urls'
import * as apis from '/api/blogApi'
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 = {
  // options: {
  //   multipleSlots: true // 在组件定义时的选项中启用多slot支持
  // },
  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: [],
    isFetchingPosts: false,
    paginationPosts: {},
    enableComments: false,
    isLikingPost: false,
    categories: [],
    isFetchingCategories: false,
    siteId: '11363837',
    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/index/index',
        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/mine/mine',
        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/sxl/sxl',
        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,
    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
            }
          }
        }
      ]
    }
  },
  attached() {
    const { siteId } = this.data
    this.fetchPosts(siteId, 'all', 1)
    this.fetchCategories(siteId)
  },
  methods: {
    fetchPosts(siteId, category, pageNum) {
      this.setData({
        isFetchingPosts: true
      })
      let { posts } = this.data

      apis.getPosts(siteId, category, pageNum).then(({ data: { data } }) => {
        const {
          blog: {
            enableComments,
            id,
            miniProgramLogoUrl: logoUrl,
            pagination,
            blogPosts
          }
        } = data
        posts = uniq(posts.concat(blogPosts))
        this.setData({
          isFetchingPosts: false,
          enableComments,
          logoUrl,
          posts,
          paginationPosts: pagination.blogPosts,
          siteId: id
        })
      })
    },
    fetchCategories(siteId) {
      this.setData({
        isFetchingCategories: true
      })
      apis.getCategories(siteId).then(({ data: { data: categories } }) => {
        this.setData({
          categories: categories.map(it =>
            Object.assign(it, { url: `https:${it.url}` })
          ),
          isFetchingCategories: false
        })
      })
    },
    loadMorePosts() {
      const { paginationPosts, siteId } = this.data
      if (paginationPosts.nextPage) {
        this.fetchPosts(siteId, 'all', paginationPosts.nextPage)
      }
    },
    handleTab(event) {
      this.setData({
        currentTab: event.currentTarget.dataset.id
      })
    },
    handleGlobalTab() {
      this.setData({
        selectedPostId: '',
        isCommenting: false,
        currentComment: ''
      })
    },
    handlePost(e) {
      const { id } = e.currentTarget.dataset
      var detail = {
        postId: id
      }
      this.triggerEvent('PostTap', detail)
    },
    handleCategory(e) {
      const { id, name } = e.currentTarget.dataset
      const detail = {
        id,
        name
      }
      this.triggerEvent('CategoryTap', detail)
    },
    setError: () => {},
    fetchPostSharing: () => {},
    setComments: () => {},
    likePost: () => {}
  },
  ready() {
    wx.setNavigationBarTitle({ title: this.data.name })
  },
  handleSearch() {
    url = urls.PAGES.POST_SEARCH
    wx.navigateTo({ url })
  },

  handleProduct(e) {
    this.handlePost(e)
  },
  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
      })
    }
  },

  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.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}`
            })
          )
        }
      }
    }
  },
  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
        })
      }
    })
  },
  onPullDownRefresh() {
    this.fetchPosts(this.data.siteId, 'all', 1).then(res =>
      wx.stopPullDownRefresh()
    )
  }
}

Component(component)
