
<template>
  <div class="login-wrapper">
    <img class="logo" :src="logo" />

    <el-button
      type="primary"
      @click="submit"
      style="width:100%; margin-top: 6px;"
      :loading="loading"
    >登录问诊平台</el-button>
  </div>
</template>


<script>
  import logo from '../../assets/image/logo.png'
  import { getOpenIM,getCbEvents } from '@/utils/openIM';
  import { imConfig } from '@/utils/im' // 引入配置
  import { accountCheck } from '@/api/doctor';
  export default {
    name: 'Login',
    data() {
      return {
        hasBindReadyEvent : false,
        logo: logo,
        loading: false,
        OpenIM: null
      }
    },
    created() {
      if (process.env.IS_OPENIM){
        this.OpenIM = getOpenIM();
        this.initListener()
      }
    },
    methods: {
      submit() {
        this.login()
      },
      initListener() {
        // 登录成功后会触发 SDK_READY 事件，该事件触发后，可正常使用 SDK 接口
        this.OpenIM.on(getCbEvents().OnConnectSuccess, () => {
          console.log("OnConnectSuccess 事件触发！"); // 调试日志
          this.$store.commit('toggleIsSDKReady', true);
        });
        this.OpenIM.on(getCbEvents().OnConnectFailed, this.onError);
        this.OpenIM.on(getCbEvents().OnKickedOffline, this.onKickOut);
        this.OpenIM.on(getCbEvents().OnSelfInfoUpdated, this.onSelfInfoUpdated);
        /*this.OpenIM.on(getCbEvents().OnRecvNewMessage, (message) => {
          console.log("收到单条消息", message);
          this.onReceiveMessage({data: [message]}); // 包装成数组形式
        });*/

        this.OpenIM.on(getCbEvents().OnRecvNewMessages, (data) => {
          console.log("收到多条消息", data);
          const msgList = []
          data.data.forEach(msg =>{
            if (msg.contentType!==113){
              msgList.push(msg)
            }
          })
          if (msgList.length>0){
            this.onReceiveMessage({data: msgList});

          }
        });
        /*this.OpenIM.on(getCbEvents().OnConversationChanged, (updatedConversations) => {
          console.log("触发OnConversationChanged事件")
          //console.log(updatedConversations)
          updatedConversations.data.forEach(conv => {
            if (conv.conversationID === this.currentConversation.conversationID) {
              context.commit('updateCurrentConversation', conv);
            }
          });
        });*/
        // SDK NOT READT
        /*this.OpenIM.on(this.OpenIM.EVENT.SDK_NOT_READY, this.onReadyStateUpdate, this)
        // 被踢出
        this.OpenIM.on(this.OpenIM.EVENT.KICKED_OUT, this.onKickOut)
        // SDK内部出错
        this.OpenIM.on(this.OpenIM.EVENT.ERROR, this.onError)
        // 收到新消息
        this.OpenIM.on(this.OpenIM.EVENT.MESSAGE_RECEIVED, this.onReceiveMessage)
        // 会话列表更新
        this.OpenIM.on(this.OpenIM.EVENT.CONVERSATION_LIST_UPDATED, this.onUpdateConversationList)
        // 群组列表更新
        this.OpenIM.on(this.OpenIM.EVENT.GROUP_LIST_UPDATED, this.onUpdateGroupList)
        // 网络监测
        this.OpenIM.on(this.OpenIM.EVENT.NET_STATE_CHANGE, this.onNetStateChange)
        // 已读回执
        this.OpenIM.on(this.OpenIM.EVENT.MESSAGE_READ_BY_PEER, this.onMessageReadByPeer)
        // 黑名单更新
        this.OpenIM.on(this.OpenIM.EVENT.FRIEND_LIST_UPDATED, this.onFriendListUpdated)

        this.OpenIM.on(this.OpenIM.EVENT.FRIEND_APPLICATION_LIST_UPDATED, this.onFriendApplicationListUpdated)

        this.OpenIM.on(this.OpenIM.EVENT.FRIEND_GROUP_LIST_UPDATED, this.onFriendGroupListUpdated)*/

      },
      login() {
        accountCheck(this.$store.getters.userID).then(response => {
          console.log("response",response)
          this.userToken = response.token
          console.log("this.userToken",this.userToken)
          console.log(this.$store.getters.userID);
          const config = {
            userID: this.$store.getters.userID,
            token: this.userToken,
            logLevel:6,
            platformID: 5, // 使用配置的平台ID
            apiAddr: process.env.VUE_APP_API_ADDR,
            wsAddr: process.env.VUE_APP_WS_ADDR,
            dataDir: '/imdata' // 添加数据存储目录
          }
          console.log("config",config)
          console.log("userToken",this.userToken)
          this.checkSDKReadyState();
          this.OpenIM.login(config).then(() => {
            this.$store.commit('toggleIsLogin', true);
            this.$store.commit('startComputeCurrent');
            this.$store.commit('showMessage', {
              type: 'success',
              message: 'IM 登录成功'
            });
          })
            .catch((error) => {
              this.loading = false;
              console.error('登录失败:', error);
              this.$store.commit('showMessage', {
                message: `IM 登录失败：${error.message || error.errMsg || '未知错误'}`,
                type: 'error',
              });
            });
        });
      },
      // 添加SDK就绪状态检查
      checkSDKReadyState() {
        if (this.hasBindReadyEvent) return;
        this.hasBindReadyEvent = true;

        let isReady = false;

        const timeout = setTimeout(() => {
          if (!isReady) {
            this.$store.commit('toggleIsSDKReady', false);
            this.$store.commit('showMessage', {
              message: 'SDK初始化超时',
              type: 'error'
            });
          }
        }, 10000);

        this.OpenIM.on(getCbEvents().OnConnectSuccess, () => {
          console.log("WebSocket连接成功");
          clearTimeout(timeout);
          isReady = true;
          this.OpenIM.getSelfUserInfo().then(({ data }) => {
            console.log("当前登录用户基本信息",data)
            this.$store.commit('updateCurrentUserProfile', data)
          })
          this.$store.commit('toggleIsSDKReady', true);
          this.$store.commit('showMessage', {
            type: 'success',
            message: 'SDK 初始化成功'
          });
          // 触发获取用户信息等操作
          console.log("开始加载用户数据，获取会话列表")
          console.log(this.OpenIM)
          this.loadUserData();
          console.log("结束加载用户数据，获取会话列表")
        });

        this.OpenIM.on(getCbEvents().OnConnectFailed, (error) => {
          clearTimeout(timeout);
          this.$store.commit('toggleIsSDKReady', false);
          this.$store.commit('showMessage', {
            message: `SDK 连接失败: ${error.message}`,
            type: 'error'
          });
        });
      },
      onReceiveMessage({ data: messageList }) {
        // let totalUnreadCount = this.tim.getTotalUnreadMessageCount();

        messageList.forEach(element => {
          //过滤掉正在输入状态
          if(element.sendID!=this.$store.getters.userID&&element.contentType!==113){
            this.$notify({
              title: '消息提示',
              message: '您有一条新的消息',
              type: 'success'
            });
          }
        });
        this.OpenIM.getAllConversationList()
          .then(({ data }) => {
            // 调用成功
            this.$store.commit('updateConversationList', data)
          })
          .catch(({ errCode, errMsg }) => {
            // 调用失败
          })
        console.log(messageList)
        //this.handleVideoMessage(messageList)
        this.handleQuitGroupTip(messageList)
        this.handleCloseGroupLive(messageList)
        this.$store.commit('pushCurrentMessageList', messageList)
        this.$store.commit('pushAvChatRoomMessageList', messageList)
      },

      // 添加加载用户数据方法
      loadUserData() {
        //查询会话列表
        this.OpenIM.getAllConversationList()
          .then(({ data }) => {
            // 调用成功
            console.log("获取到会话列表",data)
            this.conversationList= data
            this.$store.commit('updateConversationList', data)
          })
          .catch(({ errCode, errMsg }) => {
            // 调用失败
          })
        //查询好友列表
        this.OpenIM.getFriendListPage({ offset:0, count:100 })
          .then(({ data }) => {
            // 调用成功
            console.log("获取到好友列表",data)
            //this.conversationList= data
            this.$store.commit('updateFriendList', data)
          })
          .catch(({ errCode, errMsg }) => {
            // 调用失败
          })
      },
    }
  }
</script>

<style lang="stylus" scoped>
.login-wrapper
  display flex
  align-items center
  flex-direction column
  width 450px
  background $white
  color $black
  border-radius 5px
  box-shadow: 0 11px 20px 0 rgba(0,0,0,0.3)
  .row-div
    display flex
    justify-content center
    align-items center
    flex-direction row
  .logo
    width 80px;
    height 80px;
    border-radius:15rpx;
    margin-bottom:20px;
  .loginBox
    width 320px
    margin 0 0 20px 0
    .send-code
      width 112px
    .login-im-btn
      width 100%
  .loginFooter
    color: #8c8a8ac7
    text-align: center
    padding: 0 0 20px 0
    cursor: pointer
.login-wrapper {
  display: flex;
  align-items: center;
  flex-direction: column;
  width: 400px;
  padding: 20px 80px 50px;
  background: $white;
  color: $black;
  border-radius: 5px;
  box-shadow: 0 11px 20px 0 rgba(0, 0, 0, 0.3);

  .register-button {
    width: 100%;
    margin: 6px 0 0 0;
  }

  .user-selector {
    width: 100%;
  }
}
</style>
