import * as SocketHandle from '../../utils/socket-handle'
import { getQueryString } from './../../utils/tools'
import ImSend from './../../utils/imSend'
import ImApi from './../../apis/im'
import CompanyApi from './../../apis/company'
// pages/web/web.js
const app = getApp()

function randomString(e) {
  for (var t = "", i = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", n = 0; n < e; n++)
    t += i.charAt(Math.floor(Math.random() * i.length));
  return t
}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    url: "",
    pullUrl: [],
    pushUrl: '',
    live_base_url: "rtmp://120.24.85.77:1935/hls",
    socketOpts: {},
    room_id: '',
    hasBeLogin: false,
    vr_link: '',
    showWebView: true
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function (options) {
    let vr_link = 'https://www.4dkankan.com/shipin.html?'
    this.vrLink = vr_link
    this.companyDetail = {}
    this.role = this.companyDetail.guideId === (getApp().globalData.userinfo ? getApp().globalData.userinfo.viewerId : null) ? 'agent' : 'customer'
    let opts = {
      roomId: randomString(18),
      userId: getApp().globalData.userinfo.viewerId,
      role: 'customer',
      scene_num: getQueryString(vr_link, 'm') || ''
    }
    this.originUrl = `${vr_link}&room_id=${opts.roomId}${options.is_auto? `&vr=1` : ''}`
    this.setData({
      socketOpts: opts,
      url: this.originUrl,
      room_id: opts.roomId,
      house_id: options.house_id || '',
      vr_link: vr_link
    })
    
    this.socket = SocketHandle.initSocket(this, opts)
    if (app.globalData.token && !getQueryString(this.data.url, 'user_id') && this.role) {
      this.setData({
        url: `${this.originUrl}&user_id=${app.globalData.userinfo.viewerId}${this.data.hasBeLogin ? `&vr=1` : ''}`
      })
    }
  },

  onShow() {
    if (app.globalData.token && !getQueryString(this.data.url, 'user_id') && this.role) {
      this.setData({
        url: `${this.originUrl}&role=${this.role}&user_id=${app.globalData.userinfo.viewerId}${this.data.hasBeLogin ? `&vr=1` : ''}`
      })
    }
  },

  onUnload () {
    this.socket.disconnect()
  },
  countLiveUrl(user_id) {
    return `${this.data.live_base_url}/${this.data.room_id}_${user_id}`
  },
  startPlay(data) {
    console.log(data)
    if (!app.globalData.token) {
      wx.showToast({
        title: '未登录',
      })
      this.setData({
        hasBeLogin: true,
        showLogin: true
      })
      return
    }
    if (!this.hasSend) {
      // this.scene = data.user.scene_num
      this.sendVrCard()
      this.hasSend = true
    }
    this.setData({
      pushUrl: this.countLiveUrl(getApp().globalData.userinfo.user_id)
    })
  },
  createLivePull({persons, roomId}) {
    let arr = []
    persons.forEach(item => {
      arr.push(this.countLiveUrl(item.userId))
    })
    
    this.setData({
      pullUrl: arr
    })
  },
  someoneLeave() {
    this.setData({
      pullUrl: [],
      pushUrl: ''
    })
  },
  sendVrCard () {
    if (this.companyDetail.guideId === getApp().globalData.userinfo.viewerId) {
      return
    }
    ImApi.addFriend(this.companyDetail.guideId).finally(() => {
      ImSend.sendVrMsg({title: '带看', detail_images: [this.companyDetail.vrImg], vrLink: encodeURIComponent(this.vrLink)}, this.data.room_id, this.companyDetail.guideId, true)
    })
  },
  getHouseDetail (scene) {
    return CompanyApi.getCompanyDetailByScene(scene).then(res => {
      res.data.vrImg = JSON.parse(res.data.introduceImage)[0].img
      this.companyDetail = res.data
      // house.detail_images = JSON.parse(house.detail_images)
      // this.setData({
      //   house
      // })
      // return res
    })
  },
  onShareAppMessage: function (res) {
    var path = '/pages/find/find'
    return {
        title: '三维数字化技术助力内循环',
        path: path,
        imageUrl: 'https://houseoss.4dkankan.com/domain/exhibition/demo/hwzff.jpg', // 分享的封面图
    }
},
  bindmessage (e) {
    const img_url = e.detail.data[0]
    getApp().globalData.shared_img = img_url
  },
  loginSuccess () {
    this.onShow()
    this.hideLogin()
  },
  hideLogin () {
    this.setData({
        showLogin: false
    })
},
})