import * as SocketHandle from '../../utils/socket-handle'
import { getQueryString } from './../../utils/tools'
import HouseApi from './../../apis/house'
// 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: 'test1',
    trtcConfig: {
      scene: 'rtc',
      // sdkAppID: '1400433526', // 开通实时音视频服务创建应用后分配的 SDKAppID
      sdkAppID: '1400537003', // 开通实时音视频服务创建应用后分配的 SDKAppID
      userID: '', // 用户 ID，可以由您的帐号系统指定
      userSig: '', // 身份签名，相当于登录密码的作用
      template: 'custom', // 画面排版模式
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let { vr_link } = options
    vr_link = decodeURIComponent(vr_link)
    this.scene = getQueryString(vr_link, 'm')
    let opts = {
      roomId: options.room_id || getQueryString(vr_link, 'room_id') || randomString(18),
      userId: getApp().globalData.userinfo.user_id,
      customerId: getApp().globalData.userinfo.user_id,
      // nickname: getApp().globalData.userinfo.name,
      nickname: getApp().globalData.userinfo.nickname,
      role: 'agent',
      scene_num: this.scene
    }
    this.setData({
      socketOpts: opts,
      url: `${vr_link}&room_id=${opts.roomId}`,
      room_id: opts.roomId,
      house_id: options.house_id
    })
    this.roomId = opts.roomId
    console.log(this.data.url)
    this.getHouseDetail()
    this.socket = SocketHandle.initSocket(this, opts)
  },

  onShow() {
    if (app.globalData.token && !getQueryString(this.data.url, 'user_id')) {
      this.setData({
        url: `${this.data.url}&role=agent&user_id=${app.globalData.userinfo.user_id}&house_id=${this.data.house_id}`
      })
    }
  },
  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: '未登录',
      })
      wx.navigateTo({
        url: '/pages/login/login',
      })
      return
    }
    // const {
    //   roomId
    // } = data
    // console.log(this.countLiveUrl(getApp().globalData.userinfo.user_id), 'this.countLiveUrl(getApp().globalData.userinfo.user_id)')
    // this.setData({
    //   pushUrl: this.countLiveUrl(getApp().globalData.userinfo.user_id)
    // })
  },
  createLivePull({persons, roomId}) {
    let arr = []
    console.log(persons, 'persons')
    persons.forEach(item => {
      console.log(item)
      arr.push(this.countLiveUrl(item.userId))
    })
    console.log(persons)
    // const pullUrl = this.countLiveUrl(roomId)
    this.setData({
      pullUrl: arr
    })
  },
  someoneLeave() {
    this.trtcRoomContext && this.trtcRoomContext.exitRoom()
  },
  getHouseDetail () {
    if (!this.data.house_id) {
      return
    }
    HouseApi.houseDetail(this.data.house_id).then(res => {
      let house = res.data
      house.detail_images = JSON.parse(house.detail_images)
      this.setData({
        house
      })
    })
  },
  onShareAppMessage: function (res) {
    var path =`/pages/web/web?house_id=${this.data.house_id}&vr_link=${this.data.house.vrLink}`;
    var arr = this.data.house.detail_images;
    var imageurl = arr[0];
    console.log(path)
    return {
      title: this.data.house.title,
      path: path,
      imageUrl: imageurl, // 分享的封面图
      success: () => {
        
        // 转发成功
      },
      fail: function(err) {
        console.log(err)
        app.ShowModel('网络错误', '转发失败~');
        // 转发失败
      }
    }
    
  },
  enterAudioRoom(user, noEnter) {
    this.hasEnter = true
    getApp().globalData.audioUser = user
    console.log(user, 'user')
    this.setData({
      trtcConfig: {
        scene: 'rtc',
        // sdkAppID: '1400433526', // 开通实时音视频服务创建应用后分配的 SDKAppID
        sdkAppID: '1400537003', // 开通实时音视频服务创建应用后分配的 SDKAppID
        userID: user.userId, // 用户 ID，可以由您的帐号系统指定
        userSig: user.sig, // 身份签名，相当于登录密码的作用
        template: 'custom', // 画面排版模式
        debugMode:true,
      }
    }, () => {
      this.trtcRoomContext = this.selectComponent('#trtcroom')
      let EVENT =this.trtcRoomContext.EVENT
    
      if (this.trtcRoomContext) {
        // this.publishLocalAudio()
        this.trtcRoomContext.on(EVENT.LOCAL_JOIN, (event) => {
          this.publishLocalAudio()
          // wx.showToast({
          //   title: '进房',
          // })
        })

        // 监听远端用户的音频流的变更事件
       this.trtcRoomContext.on(EVENT.REMOTE_AUDIO_ADD, (event) => {
          // 订阅（即播放）远端用户的音频流
          let userID = event.data.userID
          // wx.showToast({
          //   title: '订阅',
          // })
         this.trtcRoomContext.subscribeRemoteAudio({
            userID: userID
          })
        })
        // this.trtcRoomContext.on(EVENT.LOCAL_AUDIO_VOLUME_UPDATE, event => {
        //   console.log(event)
        // })
       this.trtcRoomContext.enterRoom({
          roomID: this.roomId
        }).then(() => {
         
          console.log('成功进入房间')
          console.log(this.roomId)
        }).catch((res) => {
         
          console.error('room joinRoom 进房失败:', res)
        })
      }
    })
  },
  unpublishLocalAudio () {
    this.trtcRoomContext && this.trtcRoomContext.unpublishLocalAudio()
  },
  publishLocalAudio () {
    this.trtcRoomContext && this.trtcRoomContext.publishLocalAudio()
    // wx.showToast({
    //   title: '推流',
    // })
  }
})