<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_jg_20"></div>
    <div class="user_title">
        <span>我的任课关系</span>
        <el-checkbox v-model="checkedRenKe"  @change="CheckedRenKeChange">仅显示有效任课信息</el-checkbox>
    </div>
    <div class="page_table">
        <el-table :data="teacherClassData" border>
          <el-table-column prop="schoolYearName" label="学年" align="center">
          </el-table-column>
          <el-table-column prop="gradeName" label="年级" align="center">
          </el-table-column>
          <el-table-column prop="className" label="班级" align="center">
          </el-table-column>
          <el-table-column prop="courseName" label="科目" align="center">
          </el-table-column>
          <el-table-column
            prop="classManager"
            label="是否班主任"
            align="center"
          >
            <template slot-scope="scope">
              <div>
                {{ scope.row.roleName=='班主任' ? "是" : "否" }}
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="gradeStartDate"
            label="开始时间"
            align="center"
          >
          </el-table-column>
          <el-table-column
            prop="gradeEndDate"
            label="结束时间"
            align="center"
          >
          </el-table-column>
          
          
        </el-table>
    </div>
    <div class="page_jg_20"></div>
    <div class="page_jg_20"></div>
    <div class="user_title" >
        <span class="cardName">我的管理权限</span>
        <el-checkbox v-model="checkedMana"  @change="CheckedManaChange">仅显示有效管理权限</el-checkbox>
    </div>
    <div class="page_table">
        <el-table  :data="teacherManaData"  border >
          <el-table-column prop="schoolYearName" label="学年" align="center">
          </el-table-column>
          <el-table-column prop="roleName" label="角色" align="center">
          </el-table-column>
          <el-table-column prop="gradeName" label="年级" align="center">
          </el-table-column>
          <el-table-column prop="courseName" label="科目" align="center">
          </el-table-column>
          <el-table-column prop="gradeStartDate" label="开始时间" align="center">
          </el-table-column>
          <el-table-column prop="gradeEndDate" label="结束时间" align="center">
          </el-table-column>
        </el-table>
    </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="请输入手机号"  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="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>
          <p class="wechar_text"><img src="@/assets/login/login_wechat.webp" alt="" />微信扫描</p>
        </div>
      </el-dialog>
    </div>

  </div>
</template>
<script>
import { mapGetters } from "vuex";
import bindEmail from "./components/userSetting/bindEmail.vue";
import heada_Image from "../../assets/user_img.png";

export default {
  computed: {
    ...mapGetters(["userInfo"]),
  },
  components: {
    bindEmail,
  },
  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
    };
  },
  mounted() {
    console.log("打印userinfo",this.userInfo);
    if(this.userInfo.roleNames)
    {
      this.roleNames=this.userInfo.roleNames.join("、");
    }
   
    this.GetUserCourse();//获取任课关系
    this.GetUserPersonal();//获取权限管理
    this.LoadSdk() //加载微信sdk
    // 监听微信中间页面传递参数
    window.addEventListener('message', this.WechatBind);

  },
  beforeDestroy() {
    window.removeEventListener('message', this.WechatBind);
  },
  methods: {

    // 我的任课关系
    GetUserCourse() {
      let param = {
        dataType: 0,// 0-任课关系 1-管理权限
        effective:this.checkedRenKe,//是否有效学年
        pageNum:'1',
        pageSize:'1000',
      };
      this.$api.user.getUserCoursePersonal(param).then((res) => {
        console.log("打印我的任课关系", res);
        if (res.code == 200) {
          this.teacherClassData = res.data.records || [] ;
          console.log("打印我的任课关系", this.teacherClassData);
        }
      });
    },
    // 我的管理权限
    GetUserPersonal() {
      let param = {
        dataType: 1,// 0-任课关系 1-管理权限
        effective:this.checkedMana,//是否有效学年
        pageNum:'1',
        pageSize:'1000',
      };
      this.$api.user.getUserCoursePersonal(param).then((res) => {
        console.log("打印我的管理权限", res);
        if (res.code == 200) {
          this.teacherManaData = res.data.records || [] ;
         
        }
      });
    },

    //是否显示有效任课信息
    CheckedRenKeChange() {
      this.GetUserCourse();
    },

    //是否显示有效管理权限
    CheckedManaChange() 
    {
      this.GetUserPersonal();
    },

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

    //确定绑定手机号
    EnterBingdingPhone()
    {
      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
          } else {
            this.$message.error(res.msg)
          }
        })
        this.bindPhoneLoading = false
      } catch {
        this.bindPhoneLoading = false
      }
    },
    // 获取手机验证码
    GetCode() {
      if(!this.bindingPhoneData.phone) {
        this.$message.warning('请输入手机号码');
        return
      }
      if(this.isCount) return
      this.$api.user.getBindPhoneValidCode({
        phoneNumber: this.bindingPhoneData.phone
      }).then(res => {
        if(res.code == 200) {
          this.isCount = true
          this.codeText = `${this.count} 秒`
          const timer = setInterval(() => {
            this.count--;
            this.codeText = `${this.count} 秒`;
            if (this.count <= 0) {
              clearInterval(timer);
              this.isCount = false;
              this.count = 60;
              this.codeText = '重新获取'
            }
          }, 1000);
        }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                 // 新版二维码样式
        });
    },
    // 扫码绑定微信
    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>

</style>
