import { fhSendUserSign } from '../../api/remote/index'
import { fhGetVisitDetails,fhGetUserSig } from '../../api/newborn/index'
import { genTestUserSig } from '../utils/generateTestUserSig'
import { fhGetRemoteVisitsDetail } from '../../api/remote/index'
import { fhGetWaitSignList, fhIsVerityPatientVerty } from '../../api/sign/index'
const dayjs = require('../../src/js/dayjs/index')
const app = getApp()
Page({
  /**
   * 页面的初始数据
   */
  data: {
    rtcConfig: {
      sdkAppID: '', // 必要参数 开通实时音视频服务创建应用后分配的 sdkAppID
      userID: '', // 必要参数 用户 ID 可以由您的帐号系统指定
      userSig: '', // 必要参数 身份签名，相当于登录密码的作用
      template: '', // 必要参数 组件模版，支持的值 1v1 grid custom sign，注意：不支持动态修改, iOS 不支持 pusher 动态渲染
      localVideo: false,
      localAudio: true
    },
    showTipToast: false,
    subscribeList: {},
    remoteVisitMemberDTOList: [],
    privateName: '',
    memberType: null, // 角色
    showTips: false, // 遮罩
    remainTimes: 0,
    // privacySwitch:false
    signArr: [],  //待签署的文件列表数据
    signId: null, // 签署记录id
    payStatus: false,
    payAmount: 0,
    // 患者是否认证
    authedFlag: false,
    // 是否获取签署数据状态
    isGetWaitSign: false,
    template: null // 传入的模板
  },
  async enterRoom(params) {
    console.log(params.template, '.params🐱‍🚀🐱‍🚀🐱‍🚀🐱‍🚀🐱‍🚀🐱‍🚀🐱‍🚀🐱‍🚀🐱‍🚀💖🤣🌹')
    try {
      const { results } = params.template==='newborn' ? await fhGetUserSig({recordId : params.roomID, userId: params.userID}) :await fhSendUserSign(params.roomID, params.userID)
      params.template = params.template || '1v1'
      params.roomID = params.roomID || this.randomRoomID()
      params.userID = params.userID || this.randomUserID()
      console.log('* room enterRoom', params)

      const Signature = genTestUserSig(params.userID)
      params.sdkAppID = Signature.sdkAppID
      params.userSig = Signature.userSig
      // IM登录
      const userSig = Signature.userSig
      const userID = params.userID
      let promise = wx.TUIKit.login({ userID, userSig })
      promise
        .then(function (imResponse) {
          console.log(imResponse.data, 'success') // 登录成功
        })
        .catch(function (imError) {
          console.warn('login error:', 'erorr') // 登录失败的相关信息
        })

      this.template = params.template
      if (params.template === 'grid') {
        this.data.rtcConfig = {
          sdkAppID: params.sdkAppID, // 您的实时音视频服务创建应用后分配的 sdkAppID
          userID: params.userID,
          userSig: params.userSig,
          template: params.template, // 1v1 grid custom
          // debugMode: params.debugMode, // 非必要参数，打开组件的调试模式，开发调试时建议设置为 true
          frontCamera: 'back', // 前置摄像头
          enableEarMonitor: false,
          enableAutoFocus: true,
          localMirror: 'auto', //设置主播本地摄像头预览画面的镜像效果,auto：前置摄像头镜像，后置摄像头不镜像
          enableAgc: true, //是否开启音频自动增益
          enableAns: true, //是否开启音频噪声抑制
          videoWidth: '360', //视频宽
          videoHeight: '640', //视频高
          maxBitrate: 900, //最大码率
          minBitrate: 600, //最小码率
          beautyLevel: 9, // 开启美颜等级 0～9级美颜
          enableIM: false, // 可选，仅支持初始化设置（进房前设置），不支持动态修改
          audioVolumeType: 'auto', //声音类型
          audioQuality: 'high', //高音质（48KHz）

          // pusher URL 参数
          scene: 'rtc', // rtc live
          encsmall: false,
          cloudenv: 'PRO',
          enableBlackStream: 0,
          streamID: '',
          userDefineRecordID: '',
          privateMapKey: '',
          pureAudioMode: '',
          recvMode: ''
        }
        
      } else if(params.template === 'newborn') {
        this.data.rtcConfig = {
          sdkAppID: params.sdkAppID, // 您的实时音视频服务创建应用后分配的 sdkAppID
          userID: params.userID,
          userSig: params.userSig,
          template: params.template, // 1v1 grid custom
          // debugMode: params.debugMode, // 非必要参数，打开组件的调试模式，开发调试时建议设置为 true
          localVideo:false,
          frontCamera: 'back', // 前置摄像头
          enableEarMonitor: false,
          enableAutoFocus: true,
          localMirror: 'auto', //设置主播本地摄像头预览画面的镜像效果,auto：前置摄像头镜像，后置摄像头不镜像
          enableAgc: true, //是否开启音频自动增益
          enableAns: true, //是否开启音频噪声抑制
          videoWidth: '360', //视频宽
          videoHeight: '640', //视频高
          maxBitrate: 900, //最大码率
          minBitrate: 600, //最小码率
          beautyLevel: 9, // 开启美颜等级 0～9级美颜
          enableIM: false, // 可选，仅支持初始化设置（进房前设置），不支持动态修改
          audioVolumeType: 'auto', //声音类型
          audioQuality: 'high', //高音质（48KHz）

          // pusher URL 参数
          scene: 'rtc', // rtc live
          encsmall: false,
          cloudenv: 'PRO',
          enableBlackStream: 0,
          streamID: '',
          userDefineRecordID: '',
          privateMapKey: '',
          pureAudioMode: '',
          recvMode: ''
        }
      } 
      else {
        this.data.rtcConfig = {
          sdkAppID: params.sdkAppID, // 您的实时音视频服务创建应用后分配的 sdkAppID
          userID: params.userID,
          userSig: params.userSig,
          template: params.template, // 1v1 grid custom
          // debugMode: params.debugMode, // 非必要参数，打开组件的调试模式，开发调试时建议设置为 true
          beautyLevel: 9, // 默认开启美颜
          enableIM: false, // 可选，仅支持初始化设置（进房前设置），不支持动态修改
          audioVolumeType: 'auto'
        }
      }
      this.setData(
        {
          rtcConfig: this.data.rtcConfig
        },
        () => {
          // roomID 取值范围 1 ~ 4294967295
          this.trtcComponent
            .enterRoom({ roomID: params.roomID })
            .then(() => {
              if (this.template === 'custom') {
                // 设置推流端视窗的坐标和尺寸
                this.trtcComponent.setViewRect({
                  userID: params.userID,
                  xAxis: '480rpx',
                  yAxis: '160rpx',
                  width: '240rpx',
                  height: '320rpx'
                })
              }
            })
            .catch(res => {
              console.error('* room joinRoom 进房失败:', res)
            })
        }
      )
    } catch (error) {
      wx.showModal({
        title: '提示',
        content: '该探视已结束',
        showCancel: false,
        success: ({ confirm }) => {
          confirm && wx.navigateBack()
        }
      })
      console.log(error)
    }
  },
  bindTRTCRoomEvent: function () {
    const TRTC_EVENT = this.trtcComponent.EVENT
    this.timestamp = []
    // 初始化事件订阅
    this.trtcComponent.on(TRTC_EVENT.LOCAL_JOIN, event => {
      console.log('* room LOCAL_JOIN', event)
      // 进房成功，触发该事件后可以对本地视频和音频进行设置
      if(this.data.template !== 'newborn') this.trtcComponent.publishLocalVideo()
      this.trtcComponent.publishLocalAudio()
     
    })
    this.trtcComponent.on(TRTC_EVENT.LOCAL_LEAVE, event => {
      console.log('* room LOCAL_LEAVE', event)
    })
    this.trtcComponent.on(TRTC_EVENT.ERROR, event => {
      console.log('* room ERROR', event)
    })
    // 远端用户进房
    this.trtcComponent.on(TRTC_EVENT.REMOTE_USER_JOIN, event => {
      console.log(
        '🤷‍♀️🤷‍♀️🤷‍♀️🤷‍♀️🤷‍♀️',
        '* room REMOTE_USER_JOIN',
        event,
        this.trtcComponent.getRemoteUserList()
      )
      this.timestamp.push(new Date())
      // 1v1视频通话时限制人数为两人的简易逻辑，建议通过后端实现房间人数管理
      // 2人以上同时进行通话请选择网格布局
      if (this.template === '1v1' && this.timestamp.length > 1) {
        const interval = this.timestamp[1] - this.timestamp[0]
        if (interval < 1000) {
          // 房间里已经有两个人
          this.setData(
            {
              showTipToast: true
            },
            () => {
              setTimeout(() => {
                this.setData({
                  showTipToast: false
                })
                wx.navigateBack({
                  delta: 1
                })
              }, 4000)
            }
          )
        }
      }
    })
    // 远端用户退出
    this.trtcComponent.on(TRTC_EVENT.REMOTE_USER_LEAVE, event => {
      console.log(
        '* room REMOTE_USER_LEAVE',
        event,
        this.trtcComponent.getRemoteUserList()
      )
      if (this.template === '1v1') {
        this.timestamp = []
      }
      if (this.template === '1v1' && this.remoteUser === event.data.userID) {
        this.remoteUser = null
      }
    })
    // 远端用户推送视频
    this.trtcComponent.on(TRTC_EVENT.REMOTE_VIDEO_ADD, event => {
      console.log(
        '* room REMOTE_VIDEO_ADD',
        event,
        this.trtcComponent.getRemoteUserList()
      )
      // 订阅视频
      const userList = this.trtcComponent.getRemoteUserList()
      const data = event.data
      if (
        this.template === '1v1' &&
        (!this.remoteUser || this.remoteUser === data.userID)
      ) {
        // 1v1 只订阅第一个远端流
        this.remoteUser = data.userID
        this.trtcComponent.subscribeRemoteVideo({
          userID: data.userID,
          streamType: data.streamType
        })
      } else {
        // if (!this.data.subscribeList[data.userID + '-video']) {
        this.trtcComponent.subscribeRemoteVideo({
          userID: data.userID,
          streamType: data.streamType
        })
        // 标记该用户已首次订阅过
        this.data.subscribeList[data.userID + '-video'] = true
        // }
      }
      if (this.template === 'custom' && data.userID && data.streamType) {
        let index = userList.findIndex(item => {
          return item.userID === data.userID
        })
        index++
        const y = 320 * index + 160
        // 设置远端视图坐标和尺寸
        this.trtcComponent.setViewRect({
          userID: data.userID,
          streamType: data.streamType,
          xAxis: '480rpx',
          yAxis: y + 'rpx',
          width: '240rpx',
          height: '320rpx'
        })
      }
    })
    // 远端用户取消推送视频
    this.trtcComponent.on(TRTC_EVENT.REMOTE_VIDEO_REMOVE, event => {
      console.log(
        '* room REMOTE_VIDEO_REMOVE',
        event,
        this.trtcComponent.getRemoteUserList()
      )
    })
    // 远端用户推送音频
    this.trtcComponent.on(TRTC_EVENT.REMOTE_AUDIO_ADD, event => {
      console.log(
        '* room REMOTE_AUDIO_ADD',
        event,
        this.trtcComponent.getRemoteUserList()
      )
      // 订阅音频
      const data = event.data
      if (
        this.template === '1v1' &&
        (!this.remoteUser || this.remoteUser === data.userID)
      ) {
        this.remoteUser = data.userID
        this.trtcComponent.subscribeRemoteAudio({ userID: data.userID })
      } else {
        // if (!this.data.subscribeList[data.userID + '-audio']) {
        this.trtcComponent.subscribeRemoteAudio({
          userID: data.userID
        })
        // 标记该用户已首次订阅过
        this.data.subscribeList[data.userID + '-audio'] = true
        // }
      }
    })
    // 远端用户取消推送音频
    this.trtcComponent.on(TRTC_EVENT.REMOTE_AUDIO_REMOVE, event => {
      console.log(
        '* room REMOTE_AUDIO_REMOVE',
        event,
        this.trtcComponent.getRemoteUserList()
      )
    })
    // this.trtcComponent.on(TRTC_EVENT.LOCAL_NET_STATE_UPDATE, (event)=>{
    //   console.log('* room LOCAL_NET_STATE_UPDATE', event)
    // })
    // this.trtcComponent.on(TRTC_EVENT.REMOTE_NET_STATE_UPDATE, (event)=>{
    //   console.log('* room REMOTE_NET_STATE_UPDATE', event)
    // })
    this.trtcComponent.on(TRTC_EVENT.IM_READY, event => {
      console.log('* room IM_READY', event)
    })
    this.trtcComponent.on(TRTC_EVENT.IM_MESSAGE_RECEIVED, event => {
      console.log('* room IM_MESSAGE_RECEIVED', event)
    })
  },
  resetPrivacy() {
    const privacyList = this.data.remoteVisitMemberDTOList.filter(
      item => item.privacySwitch
    )
    const other = privacyList.find(
      item => item.memberId !== this.options.userID
    )
    if (other) {
      setTimeout(() => {
        this.openPrivacy()
      }, 1000)
    }
  },
  async init(id) {
    let list = []
    if(this.data.template === 'grid' || this.data.template === 'sign'){
      list = await this.getRemoteVisitsDetail(id)
      list.forEach(item => {
        item.role = {
          FAMILY_MEMBER: '家属',
          PATIENT: '患者',
          DOCTOR: '医生'
        }[item.memberType]
      })
      this.setData(
        {
          remoteVisitMemberDTOList: [
            ...list.filter(item => item.memberType === 'DOCTOR'),
            ...list.filter(item => item.memberType !== 'DOCTOR')
          ]
        },
        () => {
          this.resetPrivacy()
        }
      )
    } else if(this.data.template === 'newborn'){
      list = await this.getNewBornVisitDetails(id)
      list.forEach(item => {
        item.role = {
          FAMILY_MEMBER: '家属',
          PATIENT: '患者',
          DOCTOR: '护士'
        }[item.memberType]
      })
      this.setData(
        {
          remoteVisitMemberDTOList: [
            ...list.filter(item => item.memberType === 'DOCTOR'),
            ...list.filter(item => item.memberType !== 'DOCTOR')
          ]
        },
        () => {
          this.resetPrivacy()
        }
      )
    }
    
    
    console.log(this.data.remoteVisitMemberDTOList, ' console.log(this.data.remoteVisitMemberDTOList)')
  },
  // 远程探视详情
  async getRemoteVisitsDetail(id) {
    try {
      const { results } = await fhGetRemoteVisitsDetail(id)
      this.setData({
        remainTimes: dayjs(results.visitEndTime).valueOf() - dayjs().valueOf()
      })

      return results.remoteVisitMemberDTOList
    } catch (e) {
      console.log('debug axios', e)
    }
  },
  // 新生儿探视详情
  async getNewBornVisitDetails(id) {
    try {
      const { results } = await fhGetVisitDetails(id)
      this.setData({
        remainTimes: dayjs(results.visitEndTime).valueOf() - dayjs().valueOf()
      })
      return results.visitMembersList
    } catch (e) {
      console.log('debug axios', e)
    }
  },
  randomUserID: function () {
    return new Date().getTime().toString(16).split('').reverse().join('')
  },
  randomRoomID: function () {
    return parseInt(Math.random() * 9999)
  },

  // 收到的消息
  onMessageReceived(value) {
    if (this.messageLock) {
      return
    }
    this.messageLock = true
    const arry = this.trtcComponent.getRemoteUserList()
    const o = arry[0]
    const j = arry[1]
    console.log(o, j, '😘😘😘😘')
    const text = JSON.parse(value.data[0].payload.text)
    console.log(text.event, text, '11111')
    console.log(text.event === 'exitRoom', '🤷‍♀️🤷‍♀️🤷‍♀️🤷‍♀️111111')
    //  禁言
    if (text.event === 'closeChat') {
      // this.trtcComponent.unpublishLocalVideo();
      this.closeChat()
    } else if (text.event === 'openChat') {
      this.openChat()
    } else if (text.event === 'openPrivacy') {
      //  隐私模式
      console.log('111111111111111')
      this.openPrivacy()
    } else if (text.event === 'tip') {
      console.log('2222', text, text.msg)
      wx.showModal({
        title: '提示',
        content: text.msg
      })
    } else if (text.event === 'closePrivacy') {
      if (text.msg) {
        wx.showModal({
          title: '提示',
          content: text.msg,
          confirmColor: 'bule'
        })
      } else {
        this.closePrivacy()
      }
    } else if (text.event === 'exitRoom') {
      console.log('33333333')
      this.trtcComponent.exitRoom()
      this.data.template === 'newborn'? wx.showModal({
        title: '提示',
        content:
          '护士已完成探视沟通，为了不占用公共资源，远程探视会在10秒后关闭。',
        showCancel: false,
        success: function (res) {
          if (res.confirm) {
            wx.navigateBack()
          }
        }
      }): wx.showModal({
        title: '提示',
        content:
          '医生已完成探视沟通，为了不占用公共资源，远程探视会在10秒后关闭，建议使用个人微信继续与家属进行沟通。',
        showCancel: false,
        success: function (res) {
          if (res.confirm) {
            wx.navigateBack()
          }
        }
      })
    }
    setTimeout(() => {
      this.messageLock = false
    }, 1000)
  },

  closeChat() {
    this.data.template === 'newborn'? wx.showToast({ icon: 'none', title: '您已被护士禁言' }): wx.showToast({ icon: 'none', title: '您已被医生禁言' })
    this.init(this.options.roomID)
    this.trtcComponent.unpublishLocalAudio()
  },
  openChat() {
    this.data.template === 'newborn'? wx.showToast({ icon: 'none', title: '护士已解除禁言' }) : wx.showToast({ icon: 'none', title: '医生已解除禁言' })
    this.init(this.options.roomID)
    this.trtcComponent.publishLocalAudio()
  },
  openPrivacy() {
    const arry = this.trtcComponent.getRemoteUserList()
    const arry2 = this.trtcComponent.getRemoteStreamList()
    const o = arry[0] || ''
    const j = arry[1] || ''
    const othterUser = this.data.remoteVisitMemberDTOList.find(
      item =>
        item.memberType !== 'DOCTOR' &&
        item.memberId !== app.globalData.baseInfo.memberId
    )
    this.trtcComponent.unpublishLocalVideo()
    this.trtcComponent.unpublishLocalAudio()
    if (o) {
      this.trtcComponent.unsubscribeRemoteAudio(o)
    }
    if (j) {
      this.trtcComponent.unsubscribeRemoteAudio(j)
    }
    if (arry2[0]) {
      this.trtcComponent.unsubscribeRemoteVideo(arry2[0])
    }
    if (arry2[1]) {
      this.trtcComponent.unsubscribeRemoteVideo(arry2[1])
    }
    this.setData({
      privateName: othterUser ? othterUser.memberName : '',
      showTips: true
    })
  },
  closePrivacy() {
    try {
      const arry = this.trtcComponent.getRemoteUserList()
      const arry2 = this.trtcComponent.getRemoteStreamList()
      const o = arry[0]
      const j = arry[1]

      this.trtcComponent.publishLocalVideo()
      this.trtcComponent.publishLocalAudio()
      this.trtcComponent.subscribeRemoteAudio(o)
      this.trtcComponent.subscribeRemoteAudio(j)
      this.trtcComponent.subscribeRemoteVideo(arry2[0])
      this.trtcComponent.subscribeRemoteVideo(arry2[1])
      this.setData({
        showTips: false
      })
    } catch (error) {
      wx.showModal({
        title: '提示',
        content: error
      })
    }
  },
  /**
   * 打开待签署文件列表弹窗
   */
  async _openFilePanel() {
    const signData = await this.featureGetSignData();
    const sign = this.selectComponent('#sign')
    sign.handleOpen(signData);
  },
  _getSignData(e) {
    this.setData({
      isGetWaitSign: e.detail
    })
  },
  // 支付成功后,payStatus状态改变 
  _changePayStatus() {
    console.log("支付成功")
    this.setData({
      payStatus: true
    })
  },

  /***
    * 患者是否认证过
    */
  async handleAuthedIdent() {
    wx.showLoading({ title: "正在加载中", mask: true })
    try {
      const params = {
        patientId: getApp().globalData.baseInfo.memberId
      }
      const {
        results
      } = await fhIsVerityPatientVerty(params);
      wx.setStorageSync('authedFlag', results.flag)
      this.setData({
        authedFlag: results
      })
      console.log("患者是否认证",results)
      // if (!results) {
      //   wx.showModal({
      //     title: "提示",
      //     content: '您当前未实名验证,是否确认前往实名验证',
      //     success: (res) => {
      //       if (res.confirm) {
      //         this.handleToFaDaDaMini();
      //       }
      //     }
      //   })
      // }
    } catch (e) {
      console.log(e)
    } finally {
      wx.hideLoading()
    }
  },

  // 获取签署文件详情
  async featureGetSignData() {
    wx.showLoading({
      title: "正在加载中",
      mask:true
    })
    try {
      wx.hideLoading();
      const params = {
        sigId: this.data.signId,
      }
      const { results } = await fhGetWaitSignList(params)
      this.setData({
        signArr: results
      })
      console.log(results, '请求结果')
      return Promise.resolve(results)
    } catch (e) {
      wx.hideLoading();
      console.log('error', e)
    } finally {
      this.handleAuthedIdent()
    }
  },

  /**
   * 生命周期函数--监听页面加载
   * @param {*} options 配置项
   */
  onLoad: function (options) {
    if (options.template === 'sign') {
      this.setData({
        signId: options.signId,
        payStatus: JSON.parse(options.payStatus),
        payAmount: options.payAmount,
      })

      console.log("支付状态", this.data.payStatus)
    }
    this.setData({
      template: options.template
    })
    wx.setKeepScreenOn({
      keepScreenOn: true
    })
    // 获取 rtcroom 实例
    this.trtcComponent = this.selectComponent('#trtc-component')
    // 监听TRTC Room 关键事件
    this.bindTRTCRoomEvent()
    // 将String 类型的 true false 转换成 boolean
    Object.getOwnPropertyNames(options).forEach(key => {
      if (options[key] === 'true') {
        options[key] = true
      }
      if (options[key] === 'false') {
        options[key] = false
      }
    })
    this.options = options
    this.init(options.roomID)
    // querystring 只支持传递 String 类型, 注意类型转换
    this.enterRoom({
      roomID: options.roomID,
      userID: options.userID,
      template: options.template
    })
    this.setData({
      memberType: options.memberType,
      // privacySwitch: options.privacySwitch,
      signData: signData
    })
    // if (options.privacySwitch == true) {
    //   this.showPrivate();
    // }

  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    console.log('room ready')
    wx.setKeepScreenOn({
      keepScreenOn: true
    })
    wx.TUIKit.on(wx.TUIKitEvent.MESSAGE_RECEIVED, this.onMessageReceived, this)
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    console.log('room show')
    wx.setKeepScreenOn({
      keepScreenOn: true
    })
    // 页面显示就获取签署签署任务详情和是否实名认证
    if (this.data.isGetWaitSign) {
      this.featureGetSignData()
    }
    this.setData({
      authedFlag: wx.getStorageSync('authedFlag')
    })
    setTimeout(() => {
      console.log("延迟执行该函数,防止被其他函数清空loading")
      // 延迟执行该函数,防止被其他函数清空loading
      this.handleAuthedIdent()
    },800)
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    console.log('room hide')
    // onHide 后由微信接管，限制了不能退房，只能取消订阅
    // 退后台后取消发布音频
    // this.trtcComponent.unpublishLocalAudio()
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    console.log('room unload')
    wx.setKeepScreenOn({
      keepScreenOn: false
    })
  },

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

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

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () { }
})
