import * as SocketHandle from '../../utils/socket-handle'
import { getQueryString } from './../../utils/tools'
import ImSend from './../../utils/imSend'
import ImApi from './../../apis/im'
// 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: 'test',
    hasBeLogin: false,
    vr_link: '',
    showWebView: true
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let { vr_link } = options
    vr_link = decodeURIComponent(vr_link)
    this.vrLink = vr_link
    let room_id = 'test'
    let opts = {
      roomId: room_id || options.room_id || getQueryString(vr_link, 'room_id') || randomString(18),
      userId: getApp().globalData.userinfo.viewerId,
      role: 'customer',
      scene_num: getQueryString(vr_link, 'm')
    }
    this.setData({
      socketOpts: opts,
      url: `${vr_link}&room_id=${room_id || opts.roomId}${options.is_auto? `&vr=1` : ''}`,
      room_id: opts.roomId,
      house_id: options.house_id || '',
      vr_link: vr_link
    })
    this.scene = getQueryString(vr_link, 'm')
    this.getHouseDetail(this.scene)
    this.socket = SocketHandle.initSocket(this, opts)
  },

  onShow() {
    if (app.globalData.token && !getQueryString(this.data.url, 'user_id')) {
      this.setData({
        url: `${this.data.url}&role=${app.globalData.userinfo.type === 'guide' ? 'agent' : 'customer'}&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) {
    if (!app.globalData.token) {
      wx.showToast({
        title: '未登录',
      })
      this.setData({
        hasBeLogin: true
      })
      wx.navigateTo({
        url: '/pages/login/login',
      })
      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 () {
    ImApi.addFriend('1000fe7fc7dfd202f9c1594690399935').finally(() => {
      ImSend.sendVrMsg({title: '带看', detail_images: ['https://houseoss.4dkankan.com/4dHouse/admin/upload/20200721936_406.jpg'], vrLink: encodeURIComponent(this.vrLink)}, this.data.room_id, '1000fe7fc7dfd202f9c1594690399935', true)
    })
  },
  getHouseDetail (scene) {
    // return HouseApi.getHouseByScene(scene).then(res => {
    //   let house = res.data
    //   house.detail_images = JSON.parse(house.detail_images)
    //   this.setData({
    //     house
    //   })
    //   return res
    // })
  },
  onShareAppMessage: function (res) {
    var path =`/pages/web/web?house_id=${this.data.house_id}&vr_link=${encodeURIComponent(this.data.vr_link)}`;
    var arr = this.data.house.detail_images;
    var imageurl = arr[0];
    return {
      title: this.data.house.title,
      path: path,
      imageUrl: imageurl, // 分享的封面图
      success: () => {
        
        // 转发成功
      },
      fail: function(err) {
        console.log(err)
        app.ShowModel('网络错误', '转发失败~');
        // 转发失败
      }
    }
  },
  bindmessage (e) {
    const img_url = e.detail.data[0]
    getApp().globalData.shared_img = img_url
  }
})