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://8.129.178.48:1935/hls",
    socketOpts: {},
    room_id: '',
    hasBeLogin: false,
    vr_link: '',
    showWebView: true,
    trtcConfig: {}
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function (options) {
    let {
      vr_link
    } = options
    console.log(options)
    vr_link = decodeURIComponent(vr_link)
    this.vrLink = vr_link
    this.isGuide = false
    this.scene = getQueryString(vr_link, 'm')
    this.role = 'customer'
    if (this.scene) {
      await this.getHouseDetail(this.scene)
      this.role = this.companyDetail.guideId === (getApp().globalData.userinfo ? getApp().globalData.userinfo.viewerId : null) ? 'agent' : 'customer'
    }

    let opts = {
      roomId: options.room_id || getQueryString(vr_link, 'room_id') || randomString(18),
      userId: getApp().globalData.userinfo.viewerId,
      role: this.role,
      scene_num: getQueryString(vr_link, 'm')
    }
    this.roomId = opts.roomId
    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}&role=${this.role}&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) {
    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
    }
  },
  createLivePull({
    persons,
    roomId
  }) {
    let arr = []
    persons.forEach(item => {
      if (item.userId !== getApp().globalData.userinfo.viewerId) {
        arr.push(this.countLiveUrl(item.userId))
      }
    })
    this.enterAudioRoom()
  },
  someoneLeave() {
    this.setData({
      pullUrl: [],
      pushUrl: ''
    })
    this.trtcRoomContext && this.trtcRoomContext.exitRoom()
  },
  sendVrCard() {
    if (this.companyDetail.guideId === getApp().globalData.userinfo.viewerId) {
      return
    }
    ImApi.addFriend(this.companyDetail.guideId).finally(() => {
      ImSend.sendVrMsg({
        title: `${this.companyDetail.companyName}`,
        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 => {
      console.log(JSON.parse(res.data.introduceImage), 'JSON.parse(res.data.introduceImage)[')
      res.data.vrImg = JSON.parse(res.data.introduceImage)[0].img
      this.companyDetail = res.data
    })
  },
  onShareAppMessage: function (res) {
    var path = `/pages/web/web?vr_link=${encodeURIComponent(this.data.vr_link)}`;
    var imageurl = this.companyDetail.vrImg;
    return {
      title: this.companyDetail.companyName,
      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
  },
  loginSuccess() {
    this.onShow()
    this.hideLogin()
  },
  hideLogin() {
    this.setData({
      showLogin: false
    })
  },
  enterAudioRoom(user) {
    this.hasEnter = true
    getApp().globalData.audioUser = user
    console.log(user, 'user')
    this.setData({
      trtcConfig: {
        scene: 'rtc',
        sdkAppID: '1400433526', // 开通实时音视频服务创建应用后分配的 SDKAppID
        userID: user.userId, // 用户 ID，可以由您的帐号系统指定
        userSig: user.sig, // 身份签名，相当于登录密码的作用
        template: 'custom', // 画面排版模式
      }
    }, () => {
      this.trtcRoomContext = this.selectComponent('#trtcroom')
      let EVENT =this.trtcRoomContext.EVENT

      if (this.trtcRoomContext) {
        this.trtcRoomContext.on(EVENT.LOCAL_JOIN, (event) => {
          this.publishLocalAudio()
        })

        // 监听远端用户的音频流的变更事件
       this.trtcRoomContext.on(EVENT.REMOTE_AUDIO_ADD, (event) => {
          // 订阅（即播放）远端用户的音频流
          let userID = event.data.userID
         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('成功进入房间')
        }).catch((res) => {
          console.error('room joinRoom 进房失败:', res)
        })
      }
    })
  },
  unpublishLocalAudio () {
    this.trtcRoomContext && this.trtcRoomContext.unpublishLocalAudio()
  },
  publishLocalAudio () {
    this.trtcRoomContext && this.trtcRoomContext.publishLocalAudio()
  }
})