// pages/discover/discover.js
import socketApi from '../..//socket'
import api from '../../config/api'
const util = require('../../utils/util.js');
import remote from '../../config.js'


const initData = {
  showGuide: false,
  showCommodity: false,
  showInvitation: false,
  showEnd: false,
  showAlert: false,
  sendShare: false,
  showPacked: false,
  showIsEnd: false,
  showCoupon: false,
  showContact: false,
  showCommodityCtrl: false,
  goodsCount: 0,
  url: '',
  currTab: 'webview',
  showTab: true,
}


Page({
  ...socketApi,
  /**
   * 页面的初始数据
   */
  data: {
    live_base_url: 'rtmp://120.24.85.77:1935/hls',
    page: 1,
    size: 1000,
    roomList: [],
    bottom: 0,
    ...initData
  },

  

  loadWeb() {
    this.setData({
      ...initData, url: this.data.url, 
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad () {
    getApp().checkNetStatu();

    if (!wx.getStorageSync('token')) {
      return;
    }

    this.getRoomList()
    
    this.socketOptions = await this.socketStart({sceneId: ''})
    this.base = remote.viewChildHost + '/discover.html?appname=shop&origin=4Dplaza'
    console.log(this.base)
    // this.base = 'https://test.4dkankan.com/discover.html?appname=shop'
    const url = this.getUrl(this.base, this.socketOptions, false)
    this.setData({ url, loadUrl: true, socketOptions: this.socketOptions })
    this.refers = false
    this.data.reload = true
    this.joinUrl()
  },

  async getRoomList() {
    let {data} = await util.request(api.RoomList + '?pageNum=1&pageSize=1000', {}, 'GET')
    // let aaa = true
    data.list.forEach(item => {
      // 101：直播中，102：未开始，103已结束，104禁播，105：暂停，106：异常，107：已过期
      item.state = item.liveStatus === 101
      // item.state = aaa
      // aaa = !aaa
    })
    this.setData({roomList: data.list})
  },

  gotoShop(ev) {
    let id = ev.currentTarget.dataset.item.brandId
    wx.navigateTo({
      url: '/pages/webview/index?id=' + id,
    })
  },

  async scene(data) {
    this.cacheData = data
    console.log('进入场景', data)
    if (data.data.cmd === 'enter') {
      
      let {data: {brand}} = await util.request(api.BrandDetailByScene + '?sceneNum=' + data.data.num)

      if (brand) {
        this.options.id = brand.id
        this.setData({
          id: brand.id,
          newPicUrl: brand.listPicUrl,
          showCommodityCtrl: true
        })

        this.pauseVideo = true
        this.mcode = data.data.num
        console.log('设置', data.data.num)
        this.setData({numCode: data.data.num})
        this.getBrand(brand.id, data.data.num)

        this.joinUrl()
      }
    } else if (data.data.cmd === 'exit') {
      this.data.navList = null
      this.pauseVideo = false
      this.setData({ ...initData, url: this.data.url, numCode: null })
      // , showTab: false
    }

    wx.setStorageSync('lastSceneNum', data.data.num)
  },

  exit() {
    this.setData({webviewUrl: null})
    socketApi.exit.bind(this)()
  },
  onShareAppMessage: function (res) {
    let { id, newPicUrl } = this.data


    if (res.from === 'button') {
      this.setData({ sendShare: false })
      return {
        imageUrl: newPicUrl,
        path: `/pages/webview/index?id=${id}&join=true&roomId=${this.data.socketOptions.roomId}`,
      }
    }
  },

  gotoGood(ev) {
    let {goodsId} = ev.target.dataset.item

    wx.navigateTo({
      url: '/pages/goods/goods?id=' + goodsId,
    })
  },

  showTabs(data) {
    this.setData( {showTab: data.data} )
  },

  changeTab(ev) {
    this.setData({ showTab: false })
    wx.nextTick(() => {
      if (ev.target.dataset.tab === 'live') {
        // this.setData({ ...initData, showTab: true, currTab: ev.target.dataset.tab })
        this.setData({ showTab: true, currTab: ev.target.dataset.tab })
        this.pauseVideo = true
        this.joinUrl()
      } else {
        this.setData({ showTab: true, currTab: ev.target.dataset.tab })
        this.pauseVideo = false
        this.joinUrl()
      }
    })
  },


  gotoLive(ev) {
    let item = ev.currentTarget.dataset.item
    const goodPath = item.liveRoomGoodsVos.length ?
      encodeURIComponent(JSON.stringify({ path: 'pages/goods/goods', id: item.liveRoomGoodsVos[0].goodsId })) : null

    wx.navigateTo({
      url: `plugin-private://wx2b03c6e691cd7370/pages/live-player-plugin?room_id=${item.roomId}${goodPath ? `&custom_params=${goodPath}` : ''}`,
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  },


  /**
   * 生命周期函数--监听页面显示
   */
  onShow: async function (refer) {
    getApp().updateCardCount()
    
    if (!wx.getStorageSync('token')) {
      return;
    }
    console.error(wx.getStorageSync('token'))
    if (this.cccache && this.cacheToken !== wx.getStorageSync('token')) {
      refer = true
    } 

    this.cacheToken = wx.getStorageSync('token');
    this.cccache = true
    if (this.refers || refer) {
      this.socketOptions = await this.socketStart({sceneId: ''})
      this.base = remote.viewChildHost + '/discover.html?appname=shop&origin=4Dplaza'
      const url = this.getUrl(this.base, this.socketOptions, false)
      this.setData({ url, loadUrl: true, socketOptions: this.socketOptions, reload: true })
      this.refers = false
      if (refer) {
        this.setData({ webviewUrl: null })
        setTimeout(() => {
          console.error('1111')
          this.joinUrl()
        }, 500)
      } else {
        console.error('2222')
        this.joinUrl()
        socketApi.onShow.call(this)
      }
    } else {
      this.setData({
        showComtypesAllTab: false
      })
      
  
      if (this.socketSendMessage) {
        let pages = getCurrentPages()
        this.pauseVideo = !(pages[pages.length - 1].route === 'pages/discover/discover' && this.data.currTab === 'webview' && !this.data.numCode) 
        console.error('3333')
        this.joinUrl()
        this.socketSendMessage('changeOnlineStatus', { status: true  })
      }
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    setTimeout(() => {
      let refers = ['pages/index/index', 'pages/catalog/catalog', 'pages/cart/cart', 'pages/ucenter/index/index']
      // let refers = []

      let pages = getCurrentPages()
      let route = pages[pages.length - 1].route

      if (~refers.indexOf(route)) {
        this.refers = true
        this.setData({...initData})
        wx.nextTick(() => {
          this.socketSendMessage('stopCall', {})
          this.stopCall()
          this.socketStop()
          this.setData({ webviewUrl: null })
        })
      } else {
        console.error('aaaaa')
        socketApi.onHide.call(this)
      }
    }, 100)
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  getUrl(...args) {
    console.error('bbbbbbb')
    let url = socketApi.getUrl.call(this, ...args)
    let num = wx.getStorageSync('lastSceneNum')
    let params = {
      lastSceneNum: num,
      nickname: encodeURI(encodeURI(this.socketOptions.nickname)),
      avatar: encodeURI(encodeURI(this.socketOptions.avatar))
    }

    let p = Object.keys(params).map(key => `${key}=${params[key]}`).join('&')
    url = url + '&' + p

    console.error(p)

    return url
  },

  webMessage(e) {
    console.error('接收', e)
    let msgs = e.detail.data.filter(item => item.type === 'lastSceneNum')
    let msg = msgs[msgs.length - 1]

    if (msg) {
      wx.setStorageSync('lastSceneNum', msg.num)
    }
  }
})