// components/answer/answer.js
const Util = require('../../utils/util.js');
var Tim = require('../../utils/tim.js');
import TIM from 'tim-wx-sdk';
const audioContext = wx.createInnerAudioContext();
Component({
  /**
   * 组件的属性列表
   */
  properties: { //对外属性，即如果外部的wxml文件传入数据时，会把数据设置成properties的属性
    //判断是否是TabBar页
    'TabBar': {
      type: String,
      value: 'hide',
      observer: function (newVal, oldVal) {
        this.setData({
          TabBar: newVal
        });
      }
    },
  },
  /**
   * 组件的初始数据
   */
  data: {
    roomID: '',
    template: '1v1',
    debugMode: false,
    cloudenv: 'PRO',
    answerText: ' · · ·',
    text: [' ·', ' · ·', ' · · ·'],
    index: 0,
    videocall: false, //是否有存在的请求
    roomFile: {}, //房间信息
    TabBar: 'hide'//如果是show就隐藏TabBar栏
  },

  /**
   * 组件的方法列表
   */
  methods: {
    //展示弹框
    showAnswer: function () {
      this.setData({
        isShow: true,
      })
      if (this.data.TabBar == 'show') {
        wx.hideTabBar({
          animation: true
        })
      }
      this.openAudio(1);
      this.setData({
        textTime: setInterval(() => {
          var answerText = this.data.text[this.data.index];
          this.setData({
            answerText: answerText,
            index: this.data.index == 2 ? 0 : this.data.index + 1
          })
        }, 500)
      })
    },
    //隐藏弹框
    hideAnswer: function () {
      this.setData({
        isShow: false
      })
      this.openAudio(0);
      clearInterval(this.data.textTime);
      //判断是否是TabBar页
      if (this.data.TabBar == 'show') {
        wx.showTabBar({
          animation: true
        });
      }
    },
    //挂断
    hangUp() {
      let that = this;
      that.setData({
        videocall: false
      })
      Tim.sendRejectVideocall(that.data.roomFile.to);
      wx.showToast({
        title: '已拒接',
        icon: 'none',
        duration: 2000
      })
      that.hideAnswer();
    },
    //接听
    connect() {
      wx.showToast({
        title: '正在连接中',
        icon: 'loading'
      })
      this.enterRoom();
      this.hideAnswer();
    },
    //准备进房视频
    enterRoom: function () {
      let that = this;
      const roomID = that.data.roomID
      const nowTime = new Date()
      if (nowTime - that.tapTime < 1000) {
        return
      }
      if (!roomID) {
        wx.showToast({
          title: '请输入房间号',
          icon: 'none',
          duration: 2000,
        })
        return
      }
      if (roomID > 4294967295 || roomID < 1) {
        wx.showToast({
          title: '房间号取值范围为 1~4294967295',
          icon: 'none',
          duration: 2000,
        })
        return
      }
      let userID = wx.getStorageSync('data').account_number;
      if(!userID){
        wx.showToast({
          title: '当前用户ID异常，请重启小程序',
        })
        return
      }
      let url = `/packageA/room/room?roomID=${roomID}&template=${that.data.template}&debugMode=${that.data.debugMode}&cloudenv=${that.data.cloudenv}&userID=${userID}&roomFile=${JSON.stringify(that.data.roomFile)}`
      that.tapTime = nowTime
      that.checkDeviceAuthorize().then((result) => {
        console.log('授权成功', result)
        that.setData({
          videocall: false
        })
        wx.navigateTo({
          url: url
        })
      }).catch((error) => {
        console.log('没有授权', error)
      })
    },
    //查看授权
    checkDeviceAuthorize: function () {
      this.hasOpenDeviceAuthorizeModal = false
      return new Promise((resolve, reject) => {
        if (!wx.getSetting || !wx.getSetting()) {
          // 微信测试版 获取授权API异常，目前只能即使没授权也可以通过
          resolve()
        }
        wx.getSetting().then((result) => {
          console.log('getSetting', result)
          this.authorizeMic = result.authSetting['scope.record']
          this.authorizeCamera = result.authSetting['scope.camera']
          if (result.authSetting['scope.camera'] && result.authSetting['scope.record']) {
            // 授权成功
            resolve()
          } else {
            // 没有授权，弹出授权窗口
            // 注意： wx.authorize 只有首次调用会弹框，之后调用只返回结果，如果没有授权需要自行弹框提示处理
            console.log('getSetting 没有授权，弹出授权窗口', result)
            wx.authorize({
              scope: 'scope.record',
            }).then((res) => {
              console.log('authorize mic', res)
              this.authorizeMic = true
              if (this.authorizeCamera) {
                resolve()
              }
            }).catch((error) => {
              console.log('authorize mic error', error)
              this.authorizeMic = false
            })
            wx.authorize({
              scope: 'scope.camera',
            }).then((res) => {
              console.log('authorize camera', res)
              this.authorizeCamera = true
              if (this.authorizeMic) {
                resolve()
              } else {
                this.openConfirm()
                reject(new Error('authorize fail'))
              }
            }).catch((error) => {
              console.log('authorize camera error', error)
              this.authorizeCamera = false
              this.openConfirm()
              reject(new Error('authorize fail'))
            })
          }
        })
      })
    },
    //打开授权设置
    openConfirm: function () {
      if (this.hasOpenDeviceAuthorizeModal) {
        return
      }
      this.hasOpenDeviceAuthorizeModal = true
      return wx.showModal({
        content: '您没有打开麦克风和摄像头的权限，是否去设置打开？',
        confirmText: '确认',
        cancelText: '取消',
        success: (res) => {
          this.hasOpenDeviceAuthorizeModal = false
          console.log(res)
          // 点击“确认”时打开设置页面
          if (res.confirm) {
            console.log('用户点击确认')
            wx.openSetting({
              success: (res) => {},
            })
          } else {
            console.log('用户点击取消')
          }
        },
      })
    },
    /**
     * 播放铃声
     * @param {type}  1为播放 0为停止
     */
    openAudio(type) {
      wx.stopVoice();
      console.log("openAudio");
      audioContext.autoplay = true;
      audioContext.loop = true;
      audioContext.startTime = 0;
      audioContext.src = "https://www.xiaodongai.com/xiaodongai/kongtian/Public/Wechat/inquiry/ring_tone.mp3";
      if (type == 1) {
        audioContext.play();
      } else {
        audioContext.stop();
      }
    },
  },
  pageLifetimes: {
    // 组件所在页面的生命周期函数
    /**组件调用时监听im视频通话消息 */
    show: function () {
      let that = this;
      let onMessageReceived = function (event) {
        // console.log("%c收到推送的单聊", "color:#04BE02", event, that.data.videocall)
        let index = Number(event.data.length - 1);
        let data = JSON.parse(event.data[index].payload.data);
        //判断当前消息为视频通话并且无正在进行中的视频请求时弹出
        let videocall = that.data.videocall;
        if (data.type == "LaunchVideo" && !videocall) {
          that.setData({
            roomID: data.content,
            roomFile: {
              to: event.data[index].to,
              doctorName: event.data[index].nick,
              doctorheadimg: event.data[index].avatar
            },
            videocall: true
          })
          that.showAnswer();
        }
        //判断当前消息为挂断视频通话并且有正在进行中的视频请求时隐藏
        if (data.type == "closeVideo" && event.data[index].to == that.data.roomFile.to && videocall) {
          that.setData({
            videocall: false,
            roomID: '',
          })
          wx.showToast({
            title: '对方已取消视频通话',
            icon: 'none',
            duration: 2000
          })
          that.hideAnswer();
        }
        // 收到推送的单聊、群聊、群提示、群系统通知的新消息，可通过遍历 event.data 获取消息列表数据并渲染到页面
        // event.name - TIM.EVENT.MESSAGE_RECEIVED
        // event.data - 存储 Message 对象的数组 - [Message]
      };
      this.setData({
        onMessageReceived: onMessageReceived
      })
      Tim.tim.on(TIM.EVENT.MESSAGE_RECEIVED, this.data.onMessageReceived);

    },
    // hide: function () {
    // console.log('hide')
    // },
    hide: function () {
      // console.log('hide');
      // console.log('this.data.onMessageReceived',this.data.onMessageReceived)
      wx.stopVoice();
      Tim.tim.off(TIM.EVENT.MESSAGE_RECEIVED, this.data.onMessageReceived);
      //有视频请求的时候退出当前页挂断
      if(this.data.videocall){
        this.hangUp();
      }
    },
    resize: function () {},
  },
})