// pages/webview/index.js
const api = require('../../config/api.js');
const util = require('../../utils/util.js');
import socketApi from '../../socket'

const URL = 'https://www.4dkankan.com/mallscene.html?m='

Page({

  ...socketApi,
  /**
   * 页面的初始数据
   */
  data: {
    sendShare: false,
    loadUrl: false,
    goodsCount: 0,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    rnd: '',
    temp: '',
    live_base_url: 'rtmp://120.24.85.77:1935/hls',
    peopleCount: 5,
    surplus: 50,
    type: '',
    shareStatus: 0,
    showInvitation: false,
    roomMaximum: false,
    roomDisMiss: false,
    unKnowError: false, // 未知错误重进
    // url: 'https://www.4dkankan.com/showProPC.html?m=vroMUXdx&origin=4Dplaza&sid=1046051&room_id=1596785144930&user_id=44'
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function (options) {
    // console.log(this.options.a)
    if (options.scene) {
      // [id_type_join_roomId_many]
      const scene = decodeURIComponent(options.scene)

      let arr = scene.split('_')
      this.options.id = options.id
      this.options.type = options.type
      this.options.join = "true"
      this.options.roomId = options.roomId
      this.options.many = "true"
    }
    // debugger
    console.log(this.options)
    getApp().checkNetStatu();


    // setTimeout(() => this.login(), 3000)
    this.setData({
      type: options.type || this.options.type,
      join: false,
      imgServer: util.imgServer,
      showGuide: false,
      showCommodity: false,
      showInvitation: false,
      showEnd: false,
      showAlert: false,
      sendShare: false,
      showPacked: false,
      showIsEnd: false,
      showCoupon: false,
      showContact: false,
      showCommodityCtrl: false,
      recordStatus: 0,
      commoditys: [],
      coupons: [],
      userAuth: false,
      count: 0,
      goodsList: [],
      page: 1,
      size: 1000
    })

    // console.log(options)
    // options.id = '1046098'

    if (this.options.roomId) {
      this.data.join = true
    }

    if (this.data.join) {
      this.role = 'customer'
    } else {
      this.role = 'leader'
    }

    if (options.many !== void 0) {
      this.data.many = options.many
    }
    if (this.options.many) {
      this.data.many = this.options.many
    }
    console.log(this.options.many)

    console.log(this.data.many)
    socketApi.onShow.call(this)
    this.urlPj = '&brandId=' + this.options.id
  },
  // copy() {
  //   var dataT =this.data.webviewUrl
  //   wx.setClipboardData({
  //     data: dataT,
  //     success: function (res) {
  //       wx.getClipboardData({
  //         success: function (res) {
  //           console.log(res.data) // data
  //         }
  //       })
  //     }
  //   })
  // },
  async init() {
    let options = this.options
    console.log('webview-option', options)

    let {
      url: base,
      obj: m
    } = await new Promise(r => this.getBrandDetail(options.id, options.type, (url, obj) => r({
      url,
      obj
    })))

    this.getBrand(options.id, m)
    this.mcode = m
    //TODO 有问题， 其他模式的房间号如何处理？
    let socketOptions = await this.socketStart({
      sceneId: this.mcode,
      roomId: options.roomId || '888888'
    })

    let url = this.getUrl(base, socketOptions, this.data.join) + this.urlPj

    this.base = base
    // socketOptions.nickname = socketOptions.nickname.replace(/[^\u4E00-\u9FA5A-Za-z0-9]/g, '')
    this.setData({
      urlTemp: url.split('').join(' ')
    })
    this.setData({
      url,
      loadUrl: true,
      socketOptions,
      reload: true,
      hideWebView: false,
      debugerInfo: JSON.stringify({
        userId: socketOptions.userId,
        roomId: socketOptions.roomId,
        num: socketOptions.sceneNumber,
        userLimitNum: socketOptions.userLimitNum,
        isAssistant: socketOptions.isAssistant,
        role: socketOptions.role,
        assistantId: socketOptions.assistantId
      })
    })
    this.recorderManager = wx.getRecorderManager()

    this.brandId = options.id
    this.joinUrl()
    // this.mic()
  },

  hideInvitation() {
    this.setData({
      showInvitation: false
    })
    this.exit()
  },

  hideGuide() {
    this.setData({
      showGuide: false
    })
  },

  hideEnd() {
    this.setData({
      showEnd: false
    })
  },

  hideAlert() {
    this.setData({
      showAlert: false
    })
  },

  // exit() {
  //   this.stopCall()
  //   this.socketStop && this.socketStop()
  //   wx.navigateBack()
  // },

  hidePacked() {
    this.setData({
      showPacked: false
    })
  },
  handleRoomMaximum() {
    wx.switchTab({
      url: '/pages/index/index',
    })
  },

  hideIsEnd() {
    this.setData({
      showIsEnd: false
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },




  /**
   * 生命周期函数--监听页面显示
   */
  onShow: async function () {

    getApp().updateCardCount()



    // this.options.join = true
    // this.getCartList()

    let userInfo = wx.getStorageSync('userInfo');
    let token = wx.getStorageSync('token');

    if (!(userInfo && userInfo.userId && token)) {
      return;
      // return wx.navigateTo({
      //   url: '/pages/auth/btnAuth/btnAuth',
      // })
      if (this.options.join) {
        getApp().setLoginProps(false)
      } else {
        this.socketStop && this.socketStop()
        this.init()
      }
    } else if (this.token !== wx.getStorageSync('token')) {
      if (this.data.join) {
        let res = await util.request(api.UserInfo)
        if (res.errno === 401) {
          return getApp().setLoginProps(false)
        }
      }
      this.token = wx.getStorageSync('token')

      if (this.socketStop) {
        this.socketStop()
        this.setData({
          hideWebView: true,
          webviewUrl: null
        })
        setTimeout(() => {
          this.setData({
            hideWebView: false
          })
          this.init()
        }, 500)
      } else {
        this.init()
      }
    } else {
      socketApi.onShow.call(this)
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    socketApi.onHide.call(this)
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    getApp().onPullDownRefresh()
  },


  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  }
})