import { GetCheckoutRoomNum, PostAnonLogin, GetAgoraConf, GetRoomRtcToken, GetOpenId, PostHomeVerLog } from '../../api/form/index'
import { Message } from 'tdesign-miniprogram';
import { startSignalr, onStop } from '../../utils/singlr';
import { agora } from '../../utils/agora'
Page({
  data: {
    meetingForm: {
      roomNum: '',
      roomName: '',
    },
    isRecord: false,
    isCamera: false,
    netWorkErrorDialog: false,
    historicalList: [],
    isJoin: false,
    code: ''
  },
  onShow() {
    const that = this;
    onStop()
    this.setData({
      isJoin: false
    })
    wx.getStorage({
      key: 'isConnected',
      success(res: any) {
        if (res.data) {
          that.setData({
            isJoin: false
          })
          that.setData({
            netWorkErrorDialog: true,
          })
          wx.setStorage({
            key: "isConnected",
            data: false
          })
        }
      },
    })
    wx.getStorage({
      key: 'isAllLeave',
      success(res: any) {
        if (res.data) {
          Message.success({
            context: that,
            offset: [20, 32],
            duration: 2000,
            content: '管理员已结束会议!',
          });
          wx.setStorage({
            key: "isAllLeave",
            data: false
          })
        }
      },
    })
    wx.getStorage({
      key: 'isForceExitRoom',
      success(res: any) {
        if (res.data) {
          Message.success({
            context: that,
            offset: [20, 32],
            duration: 2000,
            content: '管理员已将你移出会议!',
          });
          wx.setStorage({
            key: "isForceExitRoom",
            data: false
          })
        }
      },
    })
    wx.getStorage({
      key: 'historicalList',
      success(res: any) {
        that.setData({
          historicalList: res.data
        })
        if (that.data.meetingForm.roomNum) {
          that.setData({
            meetingForm: {
              roomNum: that.data.meetingForm.roomNum,
              roomName: res.data[res.data.length - 1].nickName
            },
          })
        } else {
          that.setData({
            meetingForm: {
              roomNum: res.data[res.data.length - 1].roomNum,
              roomName: res.data[res.data.length - 1].nickName
            },
          })
        }
      },
    })
  },
  onLoad(option) {
    if (!this.data.code) {
      this.getCode()
    }
    if (option.scene) {
      const scene = decodeURIComponent(option.scene)
      const room = scene.split('r=')[1];
      this.setData({
        meetingForm: {
          roomNum: room,
        },
      }, () => {
        this.joinMeeting()
      })
    }
    wx.authorize({
      scope: 'scope.record',
      success: () => {
        this.setData({
          isRecord: true,
        })
      },
      fail: () => {
        this.setData({
          isRecord: false,
        })
      }
    });
    wx.authorize({
      scope: 'scope.camera',
      success: () => {
        this.setData({
          isCamera: true,
        })
      },
      fail: () => {
        this.setData({
          isCamera: false,
        })
      }
    });
  },
  async getRoomRtcToken(roomNum: string, callBack: Function): Promise<void> {
    Promise.all([GetRoomRtcToken(roomNum), GetAgoraConf()]).then(res => {
      if (res[0].code === 200 && res[1].code === 200) {
        callBack({
          token: res[0].data,
          appid: res[1].data
        })
      }
    })
  },
  getCode(callBack?) {
    wx.login({
      success: (res) => {
        const { code } = res
        GetOpenId(code).then(res => {
          if (res.code === 200) {
            this.setData({
              code: res.data,
            })
            callBack?.(true)
          }
        })
      },
      fail: () => {
        callBack?.(false)
      }
    })
  },
  closeDialog() {
    wx.setStorage({
      key: "isConnected",
      data: false
    })
    wx.setStorage({
      key: "isAllLeave",
      data: false
    })
    wx.setStorage({
      key: "isForceExitRoom",
      data: false
    })
    this.setData({
      netWorkErrorDialog: false
    })
  },
  joinMeeting() {
    this.closeDialog()
    if (this.data.isJoin) {
      return
    }
    this.setData({
      isJoin: true
    })
    const navigateToMeeting = async (deviceId: string): Promise<void> => {
      await PostAnonLogin({
        deviceId,
        nickName: this.data.meetingForm.roomName,
        roomNum: this.data.meetingForm.roomNum,
      }).then(res => {
        if (res.code === 200) {
          wx.setStorage({
            key: "user",
            data: res.data
          })
          setTimeout(() => {
            startSignalr((str) => {
              if (str) {
                this.setData({
                  isJoin: false
                })
                Message.error({
                  context: this,
                  offset: [90, 32],
                  duration: 3000,
                  content: str,
                });
              } else {
                this.getRoomRtcToken(this.data.meetingForm.roomNum, (option) => {
                  agora.setOption({
                    token: option.token,
                    channelId: this.data.meetingForm.roomNum,
                    appId: option.appid,
                    uid: res.data.uid,
                    screenShareId: res.data.screenShareId,
                  })
                  const accountInfo = wx.getAccountInfoSync()
                  PostHomeVerLog({
                    version: accountInfo?.miniProgram?.envVersion + '-' + accountInfo?.miniProgram?.version,
                    platformType: 2,
                    roomNum: this.data.meetingForm.roomNum,
                  })
                  wx.navigateTo({
                    url: `/pages/meeting/index?roomNum=${this.data.meetingForm.roomNum}&nickName=${this.data.meetingForm.roomName}`
                  })
                })
              }
            })
          }, 1000);
        } else {
          this.setData({
            isJoin: false
          })
        }
      }).catch(() => {
        this.setData({
          isJoin: false
        })
      })
    }
    if (!this.data.meetingForm.roomNum) {
      Message.error({
        context: this,
        offset: [90, 32],
        duration: 3000,
        content: '请输入会议号！',
      });
      this.setData({
        isJoin: false
      })
      return
    }
    if (!this.data.meetingForm.roomName) {
      Message.error({
        context: this,
        offset: [90, 32],
        duration: 3000,
        content: '请输入入会名称！',
      });
      this.setData({
        isJoin: false
      })
      return
    }
    if (this.data.meetingForm.roomName.length > 10) {
      Message.error({
        context: this,
        offset: [90, 32],
        duration: 3000,
        content: '入会名称最多10个字！',
      });
      this.setData({
        isJoin: false
      })
      return
    }
    GetCheckoutRoomNum(this.data.meetingForm.roomNum).then(async res => {
      if (res.code === 200) {
        if (res.data) {
          if (this.data.code) {
            navigateToMeeting(this.data.code)
          } else {
            this.getCode((bool) => {
              if (bool) {
                navigateToMeeting(this.data.code)
              } else {
                Message.error({
                  context: this,
                  offset: [90, 32],
                  duration: 3000,
                  content: '登录失败，请重试。',
                });
                this.setData({
                  isJoin: false
                })
              }
            })
          }
        } else {
          this.setData({
            isJoin: false
          })
          Message.error({
            context: this,
            offset: [90, 32],
            duration: 3000,
            content: '房间号不存在！',
          });
        }
      } else {
        Message.error({
          context: this,
          offset: [90, 32],
          duration: 3000,
          content: res.message,
        });
        this.setData({
          isJoin: false
        })
      }
    }).catch(() => {
      this.setData({
        isJoin: false
      })
    })
  },
  setting() {
    wx.openSetting({
      success: (res) => {
        this.setData({
          isCamera: res.authSetting['scope.camera'],
          isRecord: res.authSetting['scope.record'],
        })
      }
    })
  },
  changeMeetingForm(e) {
    switch (e.target.dataset.type) {
      case 'roomNum':
        this.setData({
          meetingForm: {
            roomNum: e.type === 'clear' ? '' : e.detail.value,
            roomName: this.data.meetingForm.roomName,
          }
        })
        break;
      case 'roomName':
        this.setData({
          meetingForm: {
            roomNum: this.data.meetingForm.roomNum,
            roomName: e.type === 'clear' ? '' : e.detail.value,
          }
        })
        break;
    }
  },
  setForm(e) {
    const { item } = e.currentTarget.dataset;
    this.setData({
      meetingForm: {
        roomNum: item.roomNum,
        roomName: item.nickName
      },
    })
    this.joinMeeting()
  }
})