<template>
  <div class="navbar">
    <hamburger id="hamburger-container" :is-active="sidebar.opened" class="hamburger-container"
      @toggleClick="toggleSideBar" />

    <breadcrumb id="breadcrumb-container" class="breadcrumb-container" v-if="!topNav" />
    <top-nav id="topmenu-container" class="topmenu-container" v-if="topNav" />

    <div class="right-menu">

      <el-dropdown class="avatar-container right-menu-item hover-effect" trigger="click">
        <div class="avatar-wrapper">
          <div class="dot" :class="{ 'active': isActive }"></div>
          <img :src="avatar" class="user-avatar">
          <!-- <i class="el-icon-caret-bottom" /> -->
        </div>
        <el-dropdown-menu slot="dropdown">
          <router-link to="/user/profile">
            <el-dropdown-item>个人中心</el-dropdown-item>
          </router-link>
          <el-dropdown-item
            :style="{ 'background-color': isActive ? 'rgb(38, 255, 31)' : '', 'color': isActive ? '#FFF' : '' }"
            @click.native="handelLogin">在线</el-dropdown-item>
          <el-dropdown-item :style="{ 'background-color': !isActive ? '#a0a0a0' : '', 'color': !isActive ? '#FFF' : '' }"
            @click.native="handellogout">离线</el-dropdown-item>

          <el-dropdown-item 
            ref="qrTrigger"
            @mouseenter.native="initQRCode"
            @mouseleave.native="destroyQRCode"
            @click.native="handleDownloadClick"
          >
            <span>二维码</span>
          </el-dropdown-item>

          <el-dropdown-item divided @click.native="logout">
            <span>退出登录</span>
          </el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
    </div>

     <div 
      v-show="showQR" 
      ref="qrPopup" 
      class="qr-popup"
      @mouseenter="showQR = true"
      @mouseleave="destroyQRCode"
    ></div>

  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import Breadcrumb from '@/components/Breadcrumb'
import TopNav from '@/components/TopNav'
import Hamburger from '@/components/Hamburger'
import { getUserSign, } from '@/api/onLineChat/index'
import { getInfo } from '@/api/login'
import QRCode from 'qrcodejs2';
import { getUserProfile } from "@/api/system/user";
export default {
  components: {
    Breadcrumb,
    TopNav,
    Hamburger,
  },
  data() {
    return {
      isActive: false,  // 根据状态设置 isActive 的值
      showQR: false,
      qrcodeInstance: null,
      triggerRect: null,
      doctorId: "",
    };
  },
  computed: {
    ...mapGetters([
      'sidebar',
      'avatar',
      'device'
    ]),
    topNav: {
      get() {
        return this.$store.state.settings.topNav
      }
    },
    
  },
  created() {
    this.isActive = this.$store.getters.info.isOnline == 0
    this.getUser()
  },
  beforeDestroy() {
    this.destroyQRCode();
  },
  methods: {
    async handleDownloadClick(event) {
      try {
        await this.$nextTick() // 确保二维码渲染完成
        this.downloadQRCode()
      } catch (error) {
        console.error('下载失败:', error)
        this.$message.error('二维码生成失败，请重试')
      }
    },

    downloadQRCode() {
      const container = this.$refs.qrPopup
      const canvas = container.querySelector('canvas')
      
      if (!canvas) {
        throw new Error('二维码未找到')
      }

      // 添加白色边距（在生成时设置margin参数）
      const margin = 4; // 边距模块数（建议4-6）
      
      // 创建下载链接
      const link = document.createElement('a')
      link.href = canvas.toDataURL('image/png')
      
      // 添加白色边框（备用方案）
      const ctx = canvas.getContext('2d')
      const padding = margin * 4; // 每个模块的像素数（通常4px/模块）
      
      // 获取原始图像数据
      const imgData = ctx.getImageData(0, 0, canvas.width, canvas.height)
      
      // 创建带边距的新画布
      const paddedCanvas = document.createElement('canvas')
      const newWidth = canvas.width + padding * 2
      const newHeight = canvas.height + padding * 2
      paddedCanvas.width = newWidth
      paddedCanvas.height = newHeight
      const paddedCtx = paddedCanvas.getContext('2d')
      
      // 填充白色背景
      paddedCtx.fillStyle = 'white'
      paddedCtx.fillRect(0, 0, newWidth, newHeight)
      
      // 绘制原始二维码（带边距）
      paddedCtx.drawImage(
        canvas,
        padding, padding,  // x/y 偏移
        canvas.width, canvas.height
      )
      
      // 更新下载链接
      link.href = paddedCanvas.toDataURL('image/png')
      link.download = `qrcode_doctor_${this.doctorId}_${Date.now()}.png`
      
      // 触发下载
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      
      this.$message.success('二维码下载成功')
    },
    getUser() {
      getUserProfile().then(response => {
        this.doctorId = response.data.userId;
      });
    },
    initQRCode(e) {
      // 1. 获取触发元素位置
      this.triggerRect = e.currentTarget.getBoundingClientRect();
      this.showQR = true;

      // 2. 创建二维码实例
      this.$nextTick(() => {
        const container = this.$refs.qrPopup;
        
        // 清空容器
        container.innerHTML = '';

        var url = ""

        if (process.env.NODE_ENV == 'production') {
            url ='https://yaorong.yaorongmedical.com/hcp/officialAccounts/pay?doctorId='+this.doctorId;
          } else {
            url = 'http://yaorongtest.yaorongmedical.com/hcp/officialAccounts/pay?doctorId='+this.doctorId;
          }
        
        // 生成二维码
        this.qrcodeInstance = new QRCode(container, {
          text: url,
          width: 150,
          height: 150,
          colorDark: '#000000',
          colorLight: '#ffffff',
          correctLevel: QRCode.CorrectLevel.H
        });

        // 3. 动态定位
        this.adjustPosition();
      });
    },

    adjustPosition() {
      if (!this.triggerRect || !this.qrcodeInstance) return;

      const container = this.$refs.qrPopup;
      const popupWidth = 170;
      const popupHeight = 170;

      // 计算最佳显示位置（左侧弹出）
      let left = this.triggerRect.left - popupWidth - 10;
      let top = this.triggerRect.top + (this.triggerRect.height - popupHeight) / 2;

      // 边界检测
      if (left < 0) left = this.triggerRect.right + 10;
      if (top < 0) top = 0;
      if (top + popupHeight > window.innerHeight) top = window.innerHeight - popupHeight;

      Object.assign(container.style, {
        left: `${left}px`,
        top: `${top}px`
      });
    },

    destroyQRCode() {
      this.showQR = false;
      if (this.qrcodeInstance) {
        this.qrcodeInstance.clear(); // 清理二维码
        this.qrcodeInstance = null;
      }
    },
    toggleSideBar() {
      this.$store.dispatch('app/toggleSideBar')
    },
    async logout() {
      this.$confirm('确定注销并退出系统吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$store.dispatch('LogOut').then(() => {
          if (process.env.NODE_ENV == 'production' || process.env.NODE_ENV == 'staging') {
            location.href = '/hcp';
          } else {
            location.href = '/hcp-dev';
          }
        })
      }).catch(() => { });
    },
    // Im
    handelLogin() {
      console.log(this.$store.getters.info, 'this.$store.getters.info.')
      let userId = this.$store.getters.info.userId
      getUserSign({ id: userId }).then(res => {
        this.imLogin(userId, res.data)
      })
    },
    // IM登录
    imLogin(userId, userSig) {
      let promise = this.tim.login({
        userID: userId,
        userSig: userSig
      });
      promise.then((imResponse) => {
        console.log(imResponse.data.repeatLogin);
        this.$nextTick(() => {
          if (imResponse.data.repeatLogin === true) {
            this.$modal.msgSuccess('登录成功')
            setTimeout(() => {
              this.$store.dispatch("GetInfo").then((res) => {
                this.isActive = res.data.isOnline == 0
              });
            }, 5000);
          } else {
            this.handelLogin()
          }
        })
      }).catch(function (imError) {
        console.warn('login error:', imError); // 登录失败的相关信息
      });
    },
    // 退出Im
    handellogout() {
      let that = this
      let promise = this.tim.logout();
      promise.then((imResponse) => {
        console.log(imResponse); // 登出成功
        this.$modal.msgSuccess('已离线')
        this.isActive = false
        // this.tim.destroy();//销毁 SDK 实例。SDK 会先 logout，然后断开 WebSocket 长连接，并释放资源
      }).catch(function (imError) {
        that.isActive = false
        console.warn('logout error:', imError);
      });
    }
  }
}
</script>

<style lang="scss" scoped>
.qr-popup {
  position: fixed;
  width: 170px;
  height: 170px;
  padding: 10px;
  background: white;
  border-radius: 4px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.15);
  z-index: 2000; /* 确保高于Element UI下拉菜单的2000 */
  display: flex;
  align-items: center;
  justify-content: center;
  pointer-events: none; /* 防止遮挡下层元素 */
}

.qr-popup:hover {
  pointer-events: auto; /* 允许内部交互 */
}


.navbar {
  height: 50px;
  overflow: hidden;
  position: relative;
  background: #fff;
  box-shadow: 0 1px 4px rgba(0, 21, 41, .08);

  .hamburger-container {
    line-height: 46px;
    height: 100%;
    float: left;
    cursor: pointer;
    transition: background .3s;
    -webkit-tap-highlight-color: transparent;

    &:hover {
      background: rgba(0, 0, 0, .025)
    }
  }

  .breadcrumb-container {
    float: left;
  }

  .topmenu-container {
    position: absolute;
    left: 50px;
  }

  .errLog-container {
    display: inline-block;
    vertical-align: top;
  }

  .right-menu {
    float: right;
    height: 100%;
    line-height: 50px;

    &:focus {
      outline: none;
    }

    .right-menu-item {
      display: inline-block;
      padding: 0 8px;
      height: 100%;
      font-size: 18px;
      color: #5a5e66;
      vertical-align: text-bottom;

      &.hover-effect {
        cursor: pointer;
        transition: background .3s;

        &:hover {
          background: rgba(0, 0, 0, .025)
        }
      }
    }

    .avatar-container {
      margin-right: 30px;

      .avatar-wrapper {
        margin-top: 5px;
        position: relative;

        .user-avatar {
          cursor: pointer;
          width: 40px;
          height: 40px;
          border-radius: 10px;
        }

        .el-icon-caret-bottom {
          cursor: pointer;
          position: absolute;
          right: -20px;
          top: 25px;
          font-size: 12px;
        }
      }
    }
  }
}

.dot {
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background-color: #a0a0a0;
  position: absolute;
  bottom: 18px;
}

.active {
  background-color: rgb(38, 255, 31);
  /* 假设激活状态下的颜色为红色 */
}
</style>
