// components/house-item/house-item.js
import { isPhoneX } from './../../utils/tools'
let app = getApp()
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    inactiveColor: {
      type: String,
      value: '#79868F'
    },
    activeColor: {
      type: String,
      value: '#1FE4DC'
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    active: 0,
    tabItems: [
      {
        title: '房源',
        url: '/pages/index/index',
        icon: {
          normal: '/image/4Dage/tab/icon_tab_hose_normal@2x.png',
          active: '/image/4Dage/tab/icon_tab_hose_active@2x.png'
        }
      },
      {
        title: '客源',
        url: '/pages/client/client',
        icon: {
          normal: '/image/4Dage/tab/icon_atab_customer_normal@2x.png',
          active: '/image/4Dage/tab/icon_atab_customer_active@2x.png'
        }
      },
      {
        title: '消息',
        url: '/pages/chat-list/chat-list',
        info: 0,
        icon: {
          normal: '/image/4Dage/tab/icon_atab_msg_normal@2x.png',
          active: '/image/4Dage/tab/icon_atab_msg_active@2x.png'
        }
      },
      {
        title: '我的',
        url: '/pages/my/my',
        icon: {
          normal: '/image/4Dage/tab/icon_atab_me_normal@2x.png',
          active: '/image/4Dage/tab/icon_atab_me_active@2x.png'
        }
      },
    ],
    isPhoneX: false
  },

  attached: function() {
    // const currentRoute = getCurrentPages()[0].route
    // const { tabItems } = this.data
    // tabItems.forEach((item, index) => {
    //   if (item.url.indexOf(currentRoute) !== -1) {
    //     this.setData({
    //       active: index
    //     })
    //   }
    // })
  },
  pageLifetimes: {
    show () {
      const currentRoute = getCurrentPages()[0].route
      const { tabItems } = this.data
      tabItems[2].info = app.globalData.unViewMsg
      console.log('show', app.globalData.unViewMsg)
      tabItems.forEach((item, index) => {
        if (item.url.indexOf(currentRoute) !== -1) {
          this.setData({
            active: index,
            tabItems: tabItems
          })
        }
      })
      isPhoneX().then(res => {
        this.setData({
          isPhoneX: res
        })
      })
      this.init()
    },
    hide () {
      getApp().getIMHandler().removeOnReceiveMessageListener({listener: this.fn})
    }
  },
  /**
   * 组件的方法列表
   */
  methods: {
    onChange(e) {
      const index = e.detail, { tabItems } = this.data
      getApp().autoSubcrebe()
      wx.switchTab({
        url: tabItems[index].url,
      })
    },
    init () {
      this.fn = (msg) => {
        
        const { tabItems } = this.data
        app.globalData.unViewMsg = app.globalData.unViewMsg ? app.globalData.unViewMsg+1 : 1
        tabItems[2].info = app.globalData.unViewMsg
        this.setData({
          tabItems
        })
        app.getNewMessage(msg)
      }
      getApp().getIMHandler().setOnReceiveMessageListener({
        listener: this.fn
    });
    }
  }
})
