import * as SocketHandle from '../../utils/socket-handle'
import {
  getQueryString
} from './../../utils/tools'
import HouseApi from './../../apis/house'
import ImSend from './../../utils/imSend'
import ImApi from './../../apis/im'
import UserApi from './../../apis/user'
// 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",
    // live_base_url: "rtmp://47.254.126.142:1935/hls",
    socketOpts: {},
    room_id: 'test',
    hasBeLogin: false,
    vr_link: '',
    showLogin: false,
    delegationShow: false,
    trtcConfig: {
      scene: 'rtc',
      // sdkAppID: '1400433526', // 开通实时音视频服务创建应用后分配的 SDKAppID
      sdkAppID: '1400537003', // 开通实时音视频服务创建应用后分配的 SDKAppID
      userID: '', // 用户 ID，可以由您的帐号系统指定
      userSig: '', // 身份签名，相当于登录密码的作用
      template: 'custom', // 画面排版模式
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    let {
      vr_link
    } = options
    vr_link = decodeURIComponent(vr_link)
    // vr_link = vr_link.replace('https://test.4dkankan.com', 'http://127.0.0.1:8081')
    // console.log(vr_link)
    // vr_link = 'http://192.168.0.98:8080/kanzhan.html?m=t-spWjHa6&role=customer&room_id=F8Q1AAC&user_id=10025977ff1f3bd36b51591351274151&test&vlog'
    let opts = {
      roomId: options.room_id || getQueryString(vr_link, 'room_id') || randomString(18),
      userId: getApp().globalData.userinfo.user_id,
      role: 'customer',
      scene_num: getQueryString(vr_link, 'm')
    }
    this.setData({
      socketOpts: opts,
      house_id: options.house_id || '',
      
      url: `${vr_link}&room_id=${opts.roomId}${options.is_auto? `&vr=1` : ''}&house_id=${options.house_id}`,
      // url: `http://192.168.0.77:8080/realtor-easier.html?m=t-lB3Dg4N&appname=realtor-easier&room_id=10508354bb8bbe62ad21624264392186&room_id=10508354bb8bbe62ad21624264392186&vr=1&role=customer&user_id=100269d2526bdb38c9d1623317318008`,
      room_id: opts.roomId,
      vr_link: vr_link,

    })
    console.log(this.data.url)
    this.scene = getQueryString(vr_link, 'm')
    // this.getHouseDetail(this.scene)
    this.getHouseDetail(this.data.house_id)
    this.socket = SocketHandle.initSocket(this, opts)
    HouseApi.getAgencyByScene(this.scene,this.data.house_id).then(agency => {
      this.agency = agency.data
    })
    this.roomId = opts.roomId
  },

  onShow() {
    if (app.globalData.token && !getQueryString(this.data.url, 'user_id')) {
      this.setData({
        url: `${this.data.url}&role=customer&user_id=${app.globalData.userinfo.user_id}${this.data.hasBeLogin ? `&vr=1` : ''}`
      })
    }
    wx.login().then(res => {
      this.code = res.code
    })
  },
  loginSuccess() {
    console.log('success')
    this.setData({
      showLogin: false
    })
    this.onShow()
  },
  // onHide () {
  //   this.setData({
  //     url: `${this.data.url}&role=customer&user_id=${app.globalData.userinfo.user_id}${this.hasSend ? `&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 => {
      arr.push(this.countLiveUrl(item.userId))
      console.log(this.countLiveUrl(item.userId))
    })

    this.setData({
      pullUrl: arr
    })
  },
  someoneLeave() {
    this.trtcRoomContext && this.trtcRoomContext.exitRoom()
  },
  sendVrCard() {
    
    HouseApi.getAgencyByScene(this.scene,this.data.house_id).then(agency => {
      // this.getHouseDetail(this.scene).then(house => { //原来是传scene
      this.getHouseDetail(this.data.house_id).then(house => {
        ImApi.addFriend(agency.data.agency_user_id).finally(() => {
          ImSend.sendVrMsg(this.data.house, this.data.room_id, agency.data.agency_user_id, true)
        })
      })

    })
  },
  // getHouseDetail (scene) { //原来是传scene
  getHouseDetail(house_id) {
    // return HouseApi.getHouseByScene(scene).then(res => {
      console.log()
    return HouseApi.getHouseByScene(house_id).then(res => {
      let house = res.data
      try {
        house.detail_images = JSON.parse(house.detail_images)
        this.setData({
          house
        })
        return res
      } catch (err) {

      }

    })
  },
  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
  },
  hideLogin() {
    this.setData({
      showLogin: false
    })
  },
  changeDelegetionStatus() {
    this.setData({
      delegationShow: !this.data.delegationShow
    })
  },
  bindgetphonenumber(e) {
    e.detail.wx_code = this.code
    e.detail.user_id = getApp().globalData.userinfo.user_id
    e.detail.agency_user_id = this.agency.agency_user_id

    UserApi.delegation(e.detail).then(res => {
      console.log(res, res.code == 0, 'res')
      if (res.code == 0) {
        this.socket.emit('getJson', {
          content: {
            action: {
              name: 'delegation',
              role: 'customer'
            }
          }
        })
        this.changeDelegetionStatus()
      } else {
        wx.login().then(res => {
          this.code = res.code
          e.detail.wx_code = this.code
          UserApi.delegation(e.detail).then(res => {
            this.socket.emit('getJson', {
              content: {
                action: {
                  name: 'delegation',
                  role: 'customer'
                }
              }
            })
            this.changeDelegetionStatus()
          })
        })
      }
    }).catch(err => {
      wx.login().then(res => {
        this.code = res.code
        e.detail.wx_code = this.code
        UserApi.delegation(e.detail).then(res => {
          this.socket.emit('getJson', {
            content: {
              action: {
                name: 'delegation',
                role: 'customer'
              }
            }
          })
          this.changeDelegetionStatus()
        })
      })
    })
  },
  enterAudioRoom(user) {
    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
      console.log(EVENT)
      if (this.trtcRoomContext) {
        this.publishLocalAudio()
        console.log(EVENT.LOCAL_JOIN)
        this.trtcRoomContext.on(EVENT.LOCAL_JOIN, (event) => {
          // wx.showToast({
          //   title: '进房',
          // })
          this.publishLocalAudio()
        })

        // 监听远端用户的音频流的变更事件
        this.trtcRoomContext.on(EVENT.REMOTE_AUDIO_ADD, (event) => {
          // 订阅（即播放）远端用户的音频流
          let userID = event.data.userID
          // console.log('&&&&&&&&&&&')
          // console.log(event)
          // 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: '推流',
    // })
  }
})