import {
  getAuthorityMsg,
  getMessageRecord,
  msgTopping
} from '~/api/message'
import {
  getMyInfo,
} from '~/api/user'
import {
  createStoreBindings
} from 'mobx-miniprogram-bindings'
import {
  store
} from '~/store/index'
import event from '~/mixins/event'
import reachBottom from '~/mixins/reachBottom'
const app = getApp()
Page({
  behaviors: [reachBottom,event],
  data: {
    targetId: "",
    menu: {
      show: false,
      top: 0,
      left: 0
    },
    menuH: 0,
    authorityMsg: {},
    uid: '',
    userInfo: {},
    isTop: false
  },
  onLoad(options) {
    this.setData({
      uid: wx.getStorageSync('uid')
    })
    this.storeBindings = createStoreBindings(this, {
      store,
      actions: {
        setUser: 'setUser'
      }
    })
  },
  async onShow() {
    if (typeof this.getTabBar === 'function') {
      this.getTabBar().setData({
        selected: 3
      })
    }
    this.getAuthorityMsg()
    this.resetData()
    let userInfo = await getMyInfo()
    this.setData({
      userInfo
    })
    this.setUser(userInfo.user)
    wx.createSelectorQuery().select('.menu').boundingClientRect((rect) => {
      this.setData({
        menuH: rect.height
      })
    }).exec()
  },
  async getAuthorityMsg() {
    let authorityMsg = await getAuthorityMsg()
    this.setData({
      authorityMsg
    })
  },
  loadMore() {
    this.getData(getMessageRecord, {
      pageSize: 20
    })
  },
  setSearch({
    detail
  }) {
    wx.navigateTo({
      url: '/pages/searchFriend/index',
    })
  },
  onLongPress(e) {
    let {
      currentTarget,
      detail,
      touches,
      target
    } = e
    let remainingW = app.globalData.windowWidth - touches[0].clientX
    let remainingH = app.globalData.windowHeight - touches[0].clientY
    let menuH = this.data.menuH
    let wFlag = remainingW - 145 > 0
    let hFlag = remainingH - menuH + 10 > 0
    let {
      receiverUid,
      senderUid
    } = currentTarget.dataset.item
    this.setData({
      targetId: receiverUid != this.data.uid ? receiverUid : senderUid,
      isTop: currentTarget.dataset.top,
      menu: {
        show: true,
        top: hFlag ? touches[0].clientY : touches[0].clientY - menuH,
        left: wFlag ? touches[0].clientX : touches[0].clientX - 135,
      }
    })
  },
  cancelMenu() {
    this.setData({
      'menu.show': false
    })
  },
  async msgTopping() {
    await msgTopping({
      topUid: this.data.targetId
    })
    this.cancelMenu()
    this.getAuthorityMsg()
    this.resetData()
  },
  delMessage() {
    this.setData({
      'menu.show': false
    })
  },
  jump({
    currentTarget
  }) {
    wx.navigateTo({
      url: `/pages/${currentTarget.dataset.url}/index`,
    })
  },
  jumpChat({
    currentTarget
  }) {
    let {
      nickName,
      eid,
      uid
    } = currentTarget.dataset.item.user
    wx.navigateTo({
      url: `/pages/chat/index?title=${nickName||eid}&uid=${uid}`,
    })
  },
  onReachBottom() {
    this.loadMore()
  }
})