<template>
  <div class="page_user">
    <div class="page_jg_20"></div>
    <div class="user_title">
      <span >我的资料</span>
    </div>
    <div class="user_module">
      <div class="user_img">
        <el-avatar
          shape="circle"
          :size="80"
          :src="headImage"
          :key="headImage"
        >
          头像
        </el-avatar>
      </div>
      <div class="user_info">
        <div class="info_item" >
          <div class="item_row">
            <span class="span_label">账号：</span>
            <span class="span_value">{{ userInfo.loginName }}</span>
          </div>
          <div  class="item_row">
            <span class="span_label">姓名：</span>
            <span class="span_value">{{ userInfo.userName }}</span>
          </div>
          
          
        </div>
        <div class="info_item">
          <div  class="item_row">
            <span class="span_label">学校：</span>
            <span class="span_value">{{ userInfo.schoolName }}</span>
          </div>
          <div  class="item_row">
            <span class="span_label">班级：</span>
            <span class="span_value">{{roleNames || '-'}}</span>
          </div>
        </div>
        <div class="info_item">
          <div  class="item_row">
            <span class="span_label">手机号：</span>
            <span class="span_value">{{userInfo.phone || '未绑定'}}</span>
            <span class="span_blue" @click="OpenPhoneDialog" v-if="!userInfo.phone">绑定手机号</span>
            <span class="span_blue" @click="OpenPhoneDialog" v-else>更换手机号</span>
          </div>
          <div  class="item_row">
            <span class="span_label">微信：</span>
            <span class="span_value">{{ userInfo.wxName || '未绑定'}}</span>
            <span class="span_blue" v-if="userInfo.wxName" @click="WechatUnBind">解除绑定</span>
            <span class="span_blue" v-else @click="OpenWeChartDialog">绑定微信</span>
          </div>
        </div>
      </div>
      
    </div>
    <div class="page_jg_20"></div>
    <div class="page_dialog">
      <el-dialog title="绑定手机号(用于找回密码)" center :visible.sync="bindingPhoneData.showDialog" width="400px">
        <div class="dialog_center padding_20">
          <div class="bingding_center">
            <div class="bingding_input">
              <el-input v-model="bindingPhoneData.phone" placeholder="请输入手机号" maxlength="11"  prefix-icon="iconfont icon_shoujihao" />
            </div>
            <div class="bingding_input">
              <el-input v-model="bindingPhoneData.code" placeholder="请输入验证码" prefix-icon="iconfont icon_yanzhengma">
                <template slot="suffix">
                  <span :class="isCount?'code_gray':'get_code'" @click="GetCode">{{ codeText }}</span>
                </template>
              </el-input>
            </div>
            <div class="bingding_button" :disabled="!bindingPhoneData.phone || !bindingPhoneData.code" @click="EnterBingdingPhone" v-loading="bindPhoneLoading">绑定手机号</div>
          </div>
        </div>
       
      </el-dialog>
      <el-dialog title="绑定微信(快捷登录)" center :visible.sync="showWeChartDialog" width="400px" @close="CloseWeChartDialog">
        <div class="dialog_center padding_20">
          <div class="bingding_center wechar_qr" id="wechat-qr-container" v-loading="qrLoading"></div>
          <div class="wechart_img">
            <img src="@/assets/login/login_wechat.webp" alt="" />
            <p class="wechar_text">微信扫描</p>
          </div>
          
        </div>
      </el-dialog>
      <SlideCode  v-model="showSlideCode"  title="安全验证" :sliderUUID="sliderUUID" :sliderBgUrl="sliderBgUrl" :sliderPositionY="sliderPositionY" :sliderImgUrl="sliderImgUrl" @close="CloseSlideCode" @refresh="ObtainSliderImg" />
    </div>

  </div>
</template>
<script>
import { mapGetters } from "vuex";

import heada_Image from "../../assets/user_img.png";
import SlideCode from "@/views/login/components/SlideCode.vue";//滑动验证码组件

export default {
  computed: {
    ...mapGetters(["userInfo"]),
  },
  components: {
    SlideCode
  },
  data() {
    return {
      // userInfo: {},
      tableData: [],
      teacherClassData: [],
      teacherManaData: [],
      checkedRenKe: true,//是否有效任课信息
      checkedMana: true,//是否有效管理权限
      rowsData: {},
      bindEmailData: { dialogShow: false },
      headImage: heada_Image,
      roleNames:'',//用户角色

      userWidth:'100px',

      showWeChartDialog:false,//是否显示微信绑定弹窗


      bindingPhoneData: { 
        showDialog: false,
        phone: "",//手机号
        code: "",//验证码
      },
      bindPhoneLoading: false, // 绑定手机号loading
      codeText: '获取验证码', // 获取验证码按钮文字 
      count: 60, // 倒数秒数
      isCount: false, // 是否倒计时
      wechatUrl: '', // 获取微信二维码返回地址
      qrLoading: false, // 二维码加载loading
      wechatCode: '', // 扫码获取code

      timer:null,//定时器
      showSlideCode:false,//是否显示滑动验证码
      sliderUUID:'',//图片唯一凭证
      sliderBgUrl:'',//画框背景图片
      sliderImgUrl:'',//滑块图片
      sliderPositionY:0,//滑块y轴位置
    };
  },
  mounted() {
    console.log("打印userInfo",this.userInfo);
    if(this.userInfo.roleNames)
    {
      this.roleNames=this.userInfo.roleNames.join("、");
    }

    //判断是否绑定了手机号
    if(this.userInfo.phone)
    {

    }
    else
    {
      this.OpenPhoneDialog();
    }
   
   
    this.LoadSdk() //加载微信sdk
    // 监听微信中间页面传递参数
    window.addEventListener('message', this.WechatBind);

  },
  beforeDestroy() {
    window.removeEventListener('message', this.WechatBind);
    if (this.timer) {
      clearInterval(this.timer);
      this.timer = null;
    }

    // 【新增】清理微信二维码定时器
    if (this.resizeTimer) {
      clearInterval(this.resizeTimer);
      this.resizeTimer = null;
    }
    
    // 清理微信 DOM
    const container = document.getElementById("wechat-qr-container");
    if (container) {
      container.innerHTML = '';
    }
  },
  methods: {






    //打开绑定手机号弹窗
    OpenPhoneDialog() 
    {
      this.bindingPhoneData.showDialog = true;
    },

    //确定绑定手机号
    EnterBingdingPhone()
    {

      console.log("绑定手机号",this.bindingPhoneData);
      if(!this.bindingPhoneData.phone) {
        this.$message.warning('请输入手机号！')
        return
      }
      if(!this.bindingPhoneData.code){
        this.$message.warning('请输入验证码！')
        return
      }
      try {
        this.bindPhoneLoading = true
        this.$api.user.bindPhoneNumber({
          phone: this.bindingPhoneData.phone,
          verificationCode: this.bindingPhoneData.code,
        }).then(res => {
          if(res.code == 200) {
            this.$message.success(res.msg)
            this.$store.dispatch("user/getUserInfoByToken");//获取用户登录信息
            this.bindingPhoneData.showDialog = false
            this.bindingPhoneData.phone = ''
            this.bindingPhoneData.code = ''
            this.codeText = '获取验证码'
            this.isCount = false
            this.count = 60;
            if(this.userInfo.wxName)
            {

            }
            else
            {
              this.OpenWeChartDialog();
            }
          } 
          else 
          {
            this.$message.error(res.msg)
          }
        })
        this.bindPhoneLoading = false
      } catch {
        this.bindPhoneLoading = false
      }
    },

    //关闭滑块验证码弹窗
    CloseSlideCode(sliderVerified,phoneNumber)
    {
      console.log("关闭滑动验证码弹窗",sliderVerified);
      this.sliderVerified=sliderVerified;
      
      if(sliderVerified==1)
      {
        //绑定手机验证
        this.StartCountdown();//启动倒计时
      }
      this.showSlideCode=false;
    },

    //h获取滑动验证码返回
    ObtainSliderImg()
    {
      let param={
        sliderUUID:this.sliderUUID,//图片唯一凭证
      };
      this.$api.user.obtainSliderImg(param).then(res => {
        console.log("打印重新获取滑动验证码结果", res);
        if(res.code == 200) 
        {
          this.sliderUUID = res.data.sliderUUID
          this.sliderBgUrl = res.data.backgroundBase64;
          this.sliderImgUrl = res.data.blockBase64;
          this.sliderPositionY = res.data.y;//验证码的y坐标
        }
        else
        {
          this.$message.error(res.msg);
        }
      })
    },

    //启动全局倒计时定时器
    StartCountdown() 
    {
      // 先清除已存在的定时器
      if (this.timer) {
        clearInterval(this.timer);
        this.timer = null;
      }
      
      this.isCount = true;
      this.count = 300;
      this.codeText = '300 秒';
      this.timer = setInterval(() => {
        this.count--;
        this.codeText = `${this.count} 秒`;
        if (this.count <= 0) {
          this.StopCountdown();
        }
      }, 1000);
    },
    //停止全局倒计时定时器
    StopCountdown() 
    {
      if (this.timer) {
        clearInterval(this.timer);
        this.timer = null;
      }
      this.isCount = false;
      this.count = 300;
      this.codeText = '重新获取';
    },
    // 获取手机验证码
    GetCode() 
    {
      // 如果已经有定时器在运行，先清除它，防止叠加
      if (this.timer) {
        clearInterval(this.timer);
        this.timer = null;
      }
      if(!this.bindingPhoneData.phone) {
        this.$message.warning('请输入手机号码');
        return
      }
      // 验证手机号格式和位数
      const phoneRegex = /^1[3-9]\d{9}$/;
      if (!phoneRegex.test(this.bindingPhoneData.phone)) {
        this.$message.warning('请输入正确的手机号码');
        return;
      }
      if(this.isCount) return
      this.$api.user.getBindPhoneSlider({
        phoneNumber: this.bindingPhoneData.phone
      }).then(res => {
        if(res.code == 200) 
        {
          this.sliderUUID = res.data.sliderUUID;
          this.sliderBgUrl = res.data.backgroundBase64;
          this.sliderImgUrl = res.data.blockBase64;
          this.sliderPositionY=res.data.y;
          this.showSlideCode=true;
          
        }else {
          this.$message.error(res.msg)
        }
      })
    },



    //打开绑定微信弹窗
    OpenWeChartDialog()
    {
      this.showWeChartDialog = true;
      try {
        this.qrLoading = true
        this.$api.user.getWechatCode().then(res => {
          if(res.code == 200 && res.data) {
            this.wechatUrl = res.data
            if(window.WxLogin) {
              this.RenderWechatQRCode()
            }
          }
        })
        this.qrLoading = false
      } catch {
        this.qrLoading = false
      }
    },
    // 动态加载微信SDK
    LoadSdk() {
      const script = document.createElement('script');
      script.src = 'https://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js';
      document.body.appendChild(script);
    },
    // 微信二维码内置到弹窗内
    RenderWechatQRCode() {
        const container = document.getElementById("wechat-qr-container");
        console.log(container)
        if (!container || container.children.length > 0) return; // 防止重复渲染

       
        const queryString = this.wechatUrl.split('?')[1]?.split('#')[0];
        const urlParams = new URLSearchParams(queryString)
        const appid = urlParams.get('appid')
        
        new window.WxLogin({
          self_redirect: true,
          id: "wechat-qr-container",   // 容器 ID
          appid: appid,           // 替换为你的微信开放平台 AppID
          scope: "snsapi_login",        // 授权作用域
          redirect_uri: encodeURIComponent(process.env.VUE_APP_BASE+"/#/wechatLogin"), // 回调 URL
          state: "STATE",               // 可选状态值
          style: "black",               // 样式风格
          stylelite: 1 ,               // 新版二维码样式
        });

        // 定时调整 iframe 大小
        const resizeInterval = setInterval(() => {
          const iframe = container.querySelector('iframe');
          if (iframe) {
            iframe.style.width = '250px';
            iframe.style.height = '160px';
            iframe.style.border = 'none';
            clearInterval(resizeInterval);
          }
        }, 100);
        
        // 设置超时防止无限循环
        setTimeout(() => {
          clearInterval(resizeInterval);
        }, 3000);
    },
    // 扫码绑定微信
    WechatBind(event) {
      let param = event.data
      if (param.type === 'wechatLoginSuccess') {
        this.wechatCode = param.data.code
        this.$api.user.bindWechat({
          code: param.data.code
        }).then(res => {
          if(res.code == 200) {
            this.$message.success('绑定成功！')
            this.$store.dispatch("user/getUserInfoByToken");//获取用户登录信息
            this.showWeChartDialog = false
          }
        }) 
      }
    }, 
    // 解除微信绑定
    WechatUnBind() {
      this.$confirm('确认解绑微信？', '提示', {
        type: 'warning',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        customClass: "page_dialog",
      }).then(() => {
        this.$api.user.unBindWechat({}).then(res => {
          if(res.code == 200) {
            this.$message.success(res.msg)
            this.$store.dispatch("user/getUserInfoByToken");//获取用户登录信息
          }
        })
      })
    },
    CloseWeChartDialog() {
      console.log("关闭微信弹窗")
      const container = document.getElementById("wechat-qr-container");
      if (container) {
          container.innerHTML = ''; // 清空容器内容
      }
      window.removeEventListener('message', this.WechatBind);
    }
  },
};
</script>
<style lang="scss" scoped>
.wechart_img
{
  margin: auto;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 40px;
  img
  {
    width: 32px;
    height: 32px;
    
  }
  .wechar_text
  {
    text-align: center;
    margin-left: 5px;
  }
  
}

#wechat-qr-container {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  min-height: 160px;
  
  iframe {
    width: 250px !important;
    height: 250px !important;
    border: none;
  }
}

</style>
