<template>
  <div @keyup.enter.native="handleLogin('loginForm')" class="main-box" style="position: relative ">
    <!-- 广告弹窗（当前未启用） -->
    <div class="ad-dialog" v-if="adShow">
      <div class="showAdImg" style=""></div>
    </div>

    <!-- 页面顶部的横幅图片 -->
    <!-- <img src="" alt=""> -->
    <div class="conter">
      <div class="left">
        <p class="title">
          <span class="color" v-if="isNcmatchDomain">NCMatch
          </span>
          <span class="color" v-else>开元云</span>
          您身边的AI管家
        </p>
        <p class="text">全 球 领 先 的 AI 服 务 运 营 商</p>
      </div>
      <div class="right">
        <!-- 根据条件显示不同的Logo -->
        <img @click="goHomePage" style="cursor: pointer" class="logo-top1" :src="logoImg" alt=""
          v-if="isLogo && isShow">
        <img @click="goHomePage" style="cursor: pointer" class="logo-top" src="../../assets/kyy/LOGONew.png" alt=""
          v-else-if="isShow">

        <!-- 微信登录二维码容器 -->
        <div class="login-form" v-if="showWxCode" style="display:flex;align-items:center;justify-content:center;"
          id="login_containera"></div>

        <!-- 主登录表单 -->
        <div v-else class="login-form">
          <!-- 前置登录组件（当前未启用） -->
          <div style="width: 100% ;height: 85px;" v-if="false">
            <before-login style="margin-top: 15px;width: 100%!important;" v-if="isShowSaleProduct"></before-login>
          </div>

          <!-- 主要登录内容 -->
          <div v-if="true" class="main-content-box"
            style="display: flex;flex-direction: column;justify-content: center;align-items: center;margin-top: 25px">
            <!-- 登录标题 -->
            <span class="login-text">登录</span>

            <!-- 登录容器 -->
            <div class="login-container login-form-style">
              <el-form ref="loginForm" :model="loginForm" :rules="rules" class="login-form-l" autocomplete="on"
                label-position="left">

                <el-form-item prop="username" style="background-color: white; border: 1px solid #d9d9d9;width: 300px;">
                  <div class="user-input">
                    <span class="svg-container icon-box">
                      <img src="../../assets/kyy/用户.svg" alt="">
                    </span>
                    <el-input id="uesr-name-id" ref="username" v-model="loginForm.username" placeholder="请输入账户"
                      name="username" type="text" class="userInput" />
                  </div>
                </el-form-item>

                <el-tooltip v-model="capsTooltip" style="margin-bottom: 7px" content="Caps lock is On" placement="right"
                  manual>
                  <el-form-item prop="password" class="password-mobile"
                    style="background-color: white; border: 1px solid #d9d9d9;width: 300px;">
                    <div class="user-input">
                      <span class="svg-container icon-box" style="padding: 2px;color: #9699a0;">
                        <img src="./svg/密码.svg" style="color: #6c7079" alt="">
                      </span>
                      <el-input id="passwordId" :key="passwordType" ref="password" v-model="loginForm.password"
                        :type="passwordType" placeholder="请输入密码" name="password" @keyup.native="checkCapslock"
                        @blur="capsTooltip = false" @keyup.enter.native="handleLogin" />
                      <span class="show-pwd" @click="showPwd">
                        <svg-icon style="margin-right: 10px;cursor: pointer"
                          :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
                      </span>
                    </div>
                  </el-form-item>
                </el-tooltip>

                <el-form-item prop="mobile" style="background-color: white; border: 1px solid #d9d9d9;width: 300px;">
                  <div class="user-input">
                    <span class="svg-container icon-box">
                      <img src="../../assets/kyy/用户.svg" alt="">
                    </span>
                    <el-input v-model="loginForm.mobile" placeholder="请输入手机号" name="mobile" type="text"
                      class="userInput" />
                  </div>
                </el-form-item>

                <div style="display:flex;margin-top:20px;">
                  <el-form-item prop="vcode" class="invitecode"
                    style="background-color: white; border: 1px solid #d9d9d9;">
                    <div class="user-input">
                      <span class="svg-container icon-box">
                        <img src="./svg/密码.svg" style="color: #6c7079;width: 19px;height: 17px;" alt="">
                      </span>
                      <el-input ref="vcode" v-model="loginForm.vcode" placeholder="请输入验证码" name="vcode" type="text" />
                    </div>
                  </el-form-item>
                  <span :disabled="isDisabled || isGettingCode" class="getCodeStyleNew"
                    style="height:40px;margin-left:10px" @click="debouncedGetCode">
                    {{ SendCode_text }}
                  </span>
                </div>

                <div style="display:flex;">
                  <el-button @keyup.enter.native="handleLogin('loginForm')" :loading="loading" type="primary"
                    style="width: 300px; display: flex; align-items: center; justify-content: center;" class="login-btn"
                    @click.native.prevent="handleLogin('loginForm')">
                    立即登录
                  </el-button>
                </div>

                <div class="two-btn">
                  <i></i>
                  <span :loading="loading" type="primary" class="go-register"
                    style="width: 127px; margin-bottom: 30px; margin-left: 0px" @click.native.prevent="handleRegister"
                    @click="handleRegister">
                    没有账号？<span class="go-register-btn">去注册</span>
                  </span>
                </div>
              </el-form>

              <!-- 重置密码对话框暂时注释 -->
              <!--
              <el-dialog title="重置密码" :visible.sync="dialogVisible" width="25%" class="myDialog">
                <el-form ref="form" :model="form" label-width="100px" :rules="forms">
                  <el-form-item label="用户名:" prop="username" class="rePassword" style="background-color: white">
                    <el-input v-model="form.username" class="name-input" placeholder="请先输入用户名/手机号"
                      style="background-color: white;border:1px solid #d9d9d9;border-radius: 3px;">
                    </el-input>
                  </el-form-item>
                  <el-form-item label="密码:" prop="password" style="background-color: white">
                    <el-input v-model="form.password" style="border:1px solid #d9d9d9;border-radius: 3px"
                      placeholder="请输入新密码">
                    </el-input>
                  </el-form-item>
                  <el-form-item label="验证码:" prop="vcode" style="background-color: white">
                    <div style="display: flex; flex-direction: row">
                      <el-input style="border:1px solid #d9d9d9;border-radius: 3px" ref="vcode" v-model="form.vcode"
                        placeholder="请输入验证码" name="vcode" type="text" />
                      <el-button type="primary" size="mini" style="height: 40px; margin-left: 10px"
                        :disabled="isDisabled1 || isGettingCode1" @click="debouncedGetCode1">
                        {{ SendCode_text1 }}
                      </el-button>
                    </div>
                  </el-form-item>
                  <div class="dialog-footer">
                    <el-button size="small" @click="cancelReset">取 消</el-button>
                    <el-button type="primary" size="small" @click="handleSubmit">确 定</el-button>
                  </div>
                </el-form>
              </el-dialog>
              -->
            </div>
          </div>
        </div>

      </div>
    </div>
    <!-- 页面底部信息 -->
    <div class="message-footer">
      <div class="item">
        <span v-if="JSON.stringify(logoInfoNew) !== '{}'" class="goPAge" @click="goPloic">京公网安备：{{
          logoInfoNew.home.publicsecurity }}</span>
        <span v-if="JSON.stringify(logoInfoNew) !== '{}'" class="goPAge" @click="goIPC">京ICP备:{{logoInfoNew.home.license }}</span>
        <span v-if="JSON.stringify(logoInfoNew) !== '{}'">增值电信业务经营许可证：{{ logoInfoNew.home.businesslicense }}</span>
        <span v-if="JSON.stringify(logoInfoNew) !== '{}'">邮箱：{{ logoInfoNew.home.email }}</span>
      </div>
      <div class="item">
        <span v-if="JSON.stringify(logoInfoNew) !== '{}'">电话：{{ logoInfoNew.home.mobile }}</span>
      </div>
    </div>
  </div>
</template>

<script>
// 导入API接口
import {
  getCodeAPI,      // 获取验证码API
  getLogoAPI,      // 获取Logo信息API
  // getPasswordCodeAPI, // 重置密码API
  logintypeAPI,    // 登录类型API
  loginUserAPI,    // 用户登录API
  reqGetAppidAPI,  // 获取微信AppID API
  reqGetCodeAPI,   // 获取微信授权码API
  // retrieveCodeAPI, // 获取重置密码验证码API,
} from "@/api/login";

import store from "@/store";
import { JSEncrypt } from "jsencrypt"; // RSA加密库
import BeforeLogin from "@/views/beforeLogin/index.vue";
import promotionalInvitationCode from "@/views/customer/promotionalInvitationCode"
import { mapState } from "vuex";
import axios from "axios";
import './js/wxLogin.js' // 微信登录JS
import { Message } from "element-ui";
import router, { resetRouter } from "@/router";
import { reqNewHomeFestival } from "@/api/newHome";
import { getHomePath } from '@/views/setting/tools'

export default {
  name: "indexNew",
  components: { BeforeLogin, promotionalInvitationCode },
  data() {
    return {
      // 微信登录相关
      wechat_openid: '', // 微信OpenID
      wxState: ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c => (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)), // 微信授权state参数
      getCodeTimer: null, // 获取微信授权码的定时器

      // 显示控制
      showWxCode: false, // 是否显示微信登录二维码
      isShow: false,     // 是否显示Logo
      logoUrlOut: '',    // Logo外部链接
      loginType: '0',    // 登录类型：0-账号密码登录，1-手机号登录
      showInviteCode: false, // 是否显示邀请码对话框
      adShow: false,     // 是否显示广告弹窗
      logoImg: require("../../assets/kyy/LOGO.png"), // 默认Logo
      logoText: "开元云", // Logo文本
      photosUrl: null,   // Logo信息
      url: window.location.href, // 当前页面URL

      // 验证码相关
      SendCode_text: "获取验证码",  // 手机登录验证码按钮文本
      isDisabled: false,  // 手机登录验证码按钮是否禁用
      time_count: 60,     // 手机登录验证码倒计时
      timer: null,        // 手机登录验证码定时器

      // 防抖相关
      isGettingCode: false, // 是否正在获取验证码
      debounceTimer: null,  // 防抖定时器

      // 对话框和加载状态
      loading: false,       // 登录按钮加载状态

      // 登录表单数据
      loginForm: {
        username: "",  // 账户
        password: "",  // 密码
        mobile: "",    // 手机号
        vcode: "",     // 验证码
        codeid: ""     // 验证码ID
      },

      activeName: 'first', // 标签页激活项

      // 表单验证规则
      rules: {
        username: [{ required: true, message: "请输入账户", trigger: "blur" }],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号", trigger: "blur" }
        ],
        vcode: [{ required: true, message: "请输入验证码", trigger: "blur" }],
      },

      // 大写锁定提示
      capsTooltip: false,
      passwordType: "password", // 密码输入框类型：password或text

      // 重置密码相关暂时注释
      // form: {
      //   username: "", // 用户名
      //   vcode: "",    // 验证码
      //   password: "", // 新密码
      //   id: "",       // 用户ID
      //   codeid: "",   // 验证码ID
      // },

      // forms: {
      //   username: [{ required: true, message: "请输入姓名", trigger: "blur" }],
      //   password: [{ required: true, message: "请输入密码", trigger: "blur" }],
      //   vcode: [{ required: true, message: "请输入验证码", trigger: "blur" }],
      // },

      // Logo显示控制
      isLogo: false,
      isShowSaleProduct: false, // 是否显示销售产品
      vedioObj: {}, // 视频通话对象
      socket: null, // WebSocket连接
    }
  },

  computed: {
    // 映射Vuex状态
    ...mapState({
      isSuccessCode: state => state.login.isSuccessCode, // 邀请码是否成功
      audioElement: state => state.sales.audioElement,   // 音频元素
      logoInfoNew: state => state.product.logoInfoNew,   // Logo信息
    }),

    // 检查当前域名是否为ncmatch.cn
    isNcmatchDomain() {
      return window.location.hostname.includes('ncmatch.cn');
    }
  },

  created() {
    // 页面创建时的初始化
    this.init()
    store.commit('tagsView/resetBreadcrumbState');

    // 保存登出URL
    if (window.location.href.includes("opencomputing") && window.location.href.includes("domain_name") || !window.location.href.includes("opencomputing")) {
      this.$store.commit('setLogoutUrl', window.location.href)
    } else {
      this.$store.commit('setLogoutUrl', "")
    }

    // 从URL中提取域名参数
    let url = window.location.href
    let params = {
      domain_name: url.includes('domain_name') ? url.split('domain_name=')[1].split('#/login')[0] : ''
    }

    // 获取销售登录信息
    this.$store.dispatch('getSaleLoginMessage', params).then(res => {
      this.isShowSaleProduct = res
    })
  },

  beforeDestroy() {
    // 组件销毁前清理定时器和事件监听
    clearInterval(this.timer)
    clearInterval(this.getCodeTimer)
    window.removeEventListener('keydown', this.handleEnter);

    // 关闭WebSocket连接
    if (this.socket) {
      this.socket.close();
    }
  },

  mounted() {
    // 页面挂载后的初始化
    window.addEventListener('keydown', this.handleEnter); // Enter键登录事件

    // 监听微信登录成功消息
    window.addEventListener('message', (event) => {
      if (event.data.type === 'wx_login_success') {
        const { code } = event.data
        console.log(event.data)
        this.$message.success("code", code)
      }
    })
  },

  methods: {
    // 防抖函数
    debounce(func, wait) {
      return function () {
        const context = this;
        const args = arguments;
        clearTimeout(this.debounceTimer);
        this.debounceTimer = setTimeout(() => {
          func.apply(context, args);
        }, wait);
      };
    },

    // 防抖后的获取验证码方法
    debouncedGetCode: function () {
      if (this.isDisabled || this.isGettingCode) return;

      this.isGettingCode = true;

      // 清除之前的定时器
      clearTimeout(this.debounceTimer);

      // 设置新的定时器，300ms后执行
      this.debounceTimer = setTimeout(() => {
        this.getCode();
        this.isGettingCode = false;
      }, 300);
    },

    // 重置密码相关方法暂时注释
    // debouncedGetCode1: function () {
    //   if (this.isDisabled1 || this.isGettingCode1) return;
    //
    //   this.isGettingCode1 = true;
    //
    //   clearTimeout(this.debounceTimer1);
    //
    //   this.debounceTimer1 = setTimeout(() => {
    //     this.getCode1();
    //     this.isGettingCode1 = false;
    //   }, 300);
    // },

    // 跳转到百度产品页面
    goBaidu(listUrl, url) {
      this.$store.commit('setRedirectUrl', url)
      localStorage.setItem('redirectUrl', url)
      localStorage.setItem('userRescourseUrl', listUrl)
      this.$router.push({
        name: 'baiduProductShow',
        params: {
          listUrl: listUrl,
          url: url
        }
      })
    },

    // 跳转到阿里云活动页面
    goAliyun() {
      reqNewHomeFestival().then(res => {
        if (res.status === true) {
          window.open(res.data)
        } else {
          this.$message.warning(res.msg)
        }
      })
    },

    // 处理Enter键登录
    handleEnter(e) {
      if (e.key === 'Enter') {
        this.handleLogin('loginForm');
      }
    },

    // 显示提示信息
    open2(msg) {
      this.$notify.info({
        title: '提示',
        message: msg,
        duration: 0
      });
    },

    // 轮询获取微信登录授权码
    pollWxCode() {
      this.getCodeTimer = setInterval(async () => {
        try {
          x          // 请求微信授权码x
          const res = await reqGetCodeAPI({ state: this.wxState });
          if (!res.status) return;

          clearInterval(this.getCodeTimer); // 清理定时器
          this.showWxCode = true;

          // 使用微信授权码登录
          const response = await loginUserAPI({ wechatCode: res.code });
          console.log("response:", response);

          if (response.status) {
            this.$message.success("登录成功");

            // 处理角色信息
            if (response.roles === "None") {
              this.$message.error("请联系管理员给您配置角色哦~");
              return;
            }

            const { data, admin, user, userId, org_type } = response;

            // 存储用户信息到本地存储
            localStorage.setItem("user_info", JSON.stringify(user));
            sessionStorage.setItem("userId", userId);
            sessionStorage.setItem("user", user);
            sessionStorage.setItem("orgid", user.orgid);
            sessionStorage.setItem("org_type", org_type);
            sessionStorage.setItem("username", user.username); // 存储用户名

            // 处理用户角色
            if (admin !== 1) {
              sessionStorage.setItem("juese", response.roles[0]);
              sessionStorage.setItem("jueseNew", response.roles);
              if (response.roles.includes("销售")) {
                this.initWebSocket(userId);
              }
            } else {
              sessionStorage.setItem("juese", "admin");
              sessionStorage.setItem("jueseNew", "admin");
            }

            // 生成路由并跳转
            const accessRoutes = await this.$store.dispatch("permission/generateRoutes", {
              user: user.username,
              auths: data,
              admin: admin || "",
            });
            resetRouter();
            console.log("生成的路径是", accessRoutes);
            router.addRoutes(accessRoutes);

            // 根据角色跳转到不同页面
            if (org_type === "2" || org_type === "3") {
              this.$router.push("/product/productHome");
            } else if (response.roles.includes("运营")) {
              this.$router.push("/operation/supplierManagement");
            } else if (response.roles.includes("销售")) {
              // this.$router.push('/sales/distributorManagement');
            } else if (response.roles.includes("运维")) {
              this.$router.push("/operationAndMaintenance/workOrderProcessing");
            } else {
              this.$router.push({ path: "/" });
            }
          } else if (response.action === "redirect") {
            this.open2(response.msg)
            // 处理重定向逻辑
            localStorage.setItem("wechat_openid", response.wechat_openid);
            this.wechat_openid = response.wechat_openid;

            const domWx = document.getElementById("login_containera");
            const iframe = domWx?.querySelector("iframe");
            if (iframe) iframe.remove(); // 移除 iframe 元素

            this.loginType = "1";
            this.showWxCode = false;
          }
        } catch (error) {
          console.error("登录失败:", error);
        } finally {
          this.loading = false;
        }
      }, 800);
    },

    // 初始化微信登录二维码
    initWxCode(appid) {
      // 根据环境确定回调URL
      let origin_uri = window.location.href.includes("dev") ? "https://dev.opencomputing.cn" : "https://www.opencomputing.cn"
      let obj = new WxLogin({
        self_redirect: true,       // 登录后是否跳转到当前页面
        id: "login_containera",     // 绑定的div容器id
        appid: appid,      // 填入你的微信公众号或小程序的APPID
        scope: "snsapi_login",     // 微信登录的权限范围，snsapi_login表示微信扫码登录
        redirect_uri: encodeURIComponent(origin_uri + "/kpi/update_code_state.dspy"),  // 微信授权回调的URL
        state: this.wxState,       // 防止CSRF攻击的随机字符串
        style: "border:none;",     // 登录框样式
        href: "https://www.opencomputing.cn/"          // 点击登录按钮后的跳转链接
      });
    },

    // 微信登录按钮点击事件
    wxBtn() {
      reqGetAppidAPI().then(res => {
        if (res.status) {
          this.showWxCode = true
          this.pollWxCode()
          this.$nextTick(() => {
            this.initWxCode(res.appid)
          })
        } else {
          this.$message({
            message: res.msg,
            type: 'error'
          })
        }
      })
    },

    // 切换登录类型
    changeLoginType(loginType) {
      this.loginType = loginType
    },

    // 跳转到公安备案页面
    goPloic() {
      window.open('https://beian.mps.gov.cn/#/query/webSearch')
    },

    // 跳转到工信部备案页面
    goIPC() {
      window.open('https://beian.miit.gov.cn/')
    },

    // 初始化WebSocket（销售角色专用）
    initWebSocket(userId) {
      let webSocketUrl = 'wss://www.opencomputing.cn/pub/rtcc.ws'
      console.log(webSocketUrl)
      this.socket = new WebSocket(webSocketUrl)

      // WebSocket连接打开事件
      this.socket.onopen = (event) => {
        console.log('WebSocket连接已打开');
        this.socket.send(JSON.stringify({
          'type': 'send',
          'from': userId,
          'uuid': '',
          'content': {}
        }));
      };

      // WebSocket消息接收事件
      this.socket.onmessage = (event) => {
        this.userId = sessionStorage.getItem('userId')
        // 判断当前是否为销售角色
        if (sessionStorage.getItem('juese') === '销售') {
          let data = JSON.parse(JSON.parse(event.data).data)
          let content = JSON.stringify(data.content) !== '{}' ? JSON.parse(data.content) : {}
          if (event.data !== undefined && content.value === 'customer') {
            if (data.uuid === this.userId) {
              this.$store.commit('setShowVideo', true)
              console.log("走了if")
            }
          } else {
            console.log("走了里的else")
          }
        } else {
          console.log("websocket走了else")
        }
      };

      // WebSocket连接关闭事件
      this.socket.onclose = (event) => {
        console.log('WebSocket连接已关闭');
      };
    },

    // 密码RSA加密
    passwordEncryption(passwordUser) {
      let publicKey = "-----BEGIN PUBLIC KEY-----\n" +
        "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEApJ3ThUWT3CgvH0O8rrT6\n" +
        "qycpqX0NTq4Q3CxBrvNxo9//qX2bKvhomoLNd+vdti8xNOK6/3zuTJIVt0RoNKwE\n" +
        "0HWMR8H0jgp7ING54DtT5B8bhmUpbs/hownGzIBGOedhqeOPiv0Q5oSi9OIEE+PK\n" +
        "2L8KdgFF2Z6Q1DQdv5Y1qvD/t2mJVjR+NPTwcwBIT8UJ0Cfu8lqHjjJbNF//smTj\n" +
        "Q8v2pnqp19jItuHeD4G4u7a8fWC3/IGEv4+uc5rq5qhwdzRxHUveNmoE+nyh0T8R\n" +
        "C8Y8/XLkEiD0nMvZZjBn7Bof6f1st0aqJX8R1VGvzdTJ8eTvJuyMNsR4wLoF5Pvx\n" +
        "hQIDAQAB\n" +
        "-----END PUBLIC KEY-----" // 从后台获取公钥

      let encryptor = new JSEncrypt()  // 新建JSEncrypt对象
      encryptor.setPublicKey(publicKey)  // 设置公钥
      let passwordEncryp = encryptor.encrypt(passwordUser)  // 对密码进行加密
      return passwordEncryp
    },

    // 跳转到首页
    goHomePage() {
      this.$router.push(getHomePath())
    },

    // 初始化Logo信息
    init() {
      let remoteUrl = ''
      if (window.location.href.includes("dev")) {
        remoteUrl = 'https://www.opencomputing.cn/dev/reseller/get_ipc_logo.dspy'
      } else if (window.location.href.includes("localhost")) {
        remoteUrl = 'http://localhost:9527/'
      } else {
        remoteUrl = 'https://www.opencomputing.cn/reseller/get_ipc_logo.dspy'
      }

      let params = {
        url_link: this.GetQueryString(this.url)
      }

      getLogoAPI(params).then((res) => {
        if (res.status == true && res.data && res.data.length) {
          this.$store.commit('setLogoInfo', res.data[0]);
          this.isShow = true
          this.$store.commit('setLogoInfoNew', res.data[0].additional_msg);
          if (res.data[0].orgname == '中关村数智人工智能产业联盟') {
            this.logoUrlOut = 'https://www.ncmatch.cn'
          }

          this.photosUrl = res.data[0];
          if (this.photosUrl.orgname != '业主机构') {
            this.isLogo = true
            this.logoImg = this.photosUrl.logo;

            this.$store.commit('setLogo', this.photosUrl.logo)
            this.logoText = this.photosUrl.orgname;
          } else {
            this.$store.commit('setLogo', "")
          }
        } else {
          console.log("sdsddas@@@")
          this.$message({
            message: "获取ipc失败~",
            type: "error",
          });
        }
      });
    },

    // 获取URL查询参数
    GetQueryString(name) {
      if (name.indexOf("#") != -1) {
        const params = name.split("#")[0];
        return params;
      }
    },

    // 获取手机登录验证码
    getCode() {
      // 验证手机号格式
      if (!this.loginForm.mobile || !/^1[3-9]\d{9}$/.test(this.loginForm.mobile)) {
        this.$message.error('请输入正确的手机号');
        return;
      }

      // 使用新的API参数：mobile和action_type
      getCodeAPI({
        mobile: this.loginForm.mobile,
        action_type: 'login'
      }).then((res) => {
        console.log(res);
        if (res.status) {
          this.loginForm.codeid = res.codeid;
          let that = this;
          clearInterval(that.timer)
          this.time_count = 59
          this.SendCode_text = "重新发送" + this.time_count + "s";
          this.isDisabled = true;
          this.timer = setInterval(() => {
            if (this.time_count > 0) {
              this.time_count--;
              this.SendCode_text = "重新发送" + this.time_count + "s";
            } else {
              this.SendCode_text = "获取验证码";
              clearInterval(this.timer);
              this.timer = null;
              this.isDisabled = false;
              this.time_count = 60;
            }
          }, 1000);

          this.$message({
            message: "验证码获取成功",
            type: "success",
          });
        } else {
          if (res.action === 'redirect') {
            this.$message({
              message: res.msg,
              type: "error",
            });
          } else {
            this.$message({
              message: res.msg,
              type: "error",
            });
          }
        }
      }).catch(error => {
        this.isGettingCode = false;
        this.$message.error('验证码获取失败');
      });
    },

    // getCode1() {
    //   if (!this.form.username || !/^1[3-9]\d{9}$/.test(this.form.username)) {
    //     this.$message.error('请输入正确的手机号');
    //     return;
    //   }
    //
    //   retrieveCodeAPI({
    //     mobile: this.form.username,
    //     action_type: 'login'
    //   }).then((res) => {
    //     if (res.status == true) {
    //       this.form.id = res.userid;
    //       this.form.codeid = res.codeid;
    //       let that = this;
    //       this.time_count1 = 59;
    //       this.isDisabled1 = true;
    //       this.SendCode_text1 = "重新发送" + this.time_count1 + "s";
    //
    //       if (!that.timer1) {
    //         that.timer1 = setInterval(() => {
    //           if (that.time_count1 > 0) {
    //             that.time_count1--;
    //             that.SendCode_text1 = "重新发送" + that.time_count1 + "s";
    //           } else {
    //             that.SendCode_text1 = "获取验证码";
    //             clearInterval(that.timer1);
    //             that.timer1 = null;
    //             this.isDisabled1 = false;
    //             that.time_count1 = 60;
    //           }
    //         }, 1000);
    //       }
    //       this.$message({
    //         message: "验证码已发送，请注意查收。",
    //         type: "success",
    //       });
    //     } else {
    //       this.$message({
    //         message: res.msg,
    //         type: "error",
    //       });
    //     }
    //   }).catch(error => {
    //     this.isGettingCode1 = false;
    //     this.$message.error('验证码获取失败');
    //   });
    // },

    // 标签页点击事件
    handleClick(tab, event) {
      console.log(tab, event);
    },

    // 检查大写锁定状态
    checkCapslock(e) {
      const { key } = e;
      this.capsTooltip = key && key.length === 1 && key >= "A" && key <= "Z";
    },

    // 处理登录
    handleLogin(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const loginParams = {
            username: this.loginForm.username,
            domain_name: this.photosUrl?.domain_name ? this.photosUrl.domain_name : '',
            password: this.passwordEncryption(this.loginForm.password),
            mobile: this.loginForm.mobile,
            vcode: this.loginForm.vcode,
            codeid: this.loginForm.codeid,
            wechat_openid: this.wechat_openid
          }

          logintypeAPI(loginParams).then(res => {
            if (res.status == true) {
              this.loading = true;
              this.$store
                .dispatch("user/login", loginParams)
                .then((res) => {
                  this.loading = false;

                  localStorage.setItem("user_info", JSON.stringify(res.user));

                  // 处理用户角色
                  if (res.admin != 1) {
                    sessionStorage.setItem("juese", res.roles[0]);
                    sessionStorage.setItem("jueseNew", res.roles);
                    if (res.roles.includes('销售')) {
                      this.initWebSocket(res.userId)
                    }
                  } else {
                    sessionStorage.setItem("juese", 'admin');
                    sessionStorage.setItem("jueseNew", 'admin');
                  }

                  if (res.status == true) {
                    this.$store.commit('setLoginState', true)
                    this.loading = false;
                    sessionStorage.setItem("userId", res.userId);
                    sessionStorage.setItem("orgid", res.user.orgid);
                    sessionStorage.setItem("org_type", res.org_type);
                    sessionStorage.setItem("username", res['user'].username);

                    // 根据角色跳转到不同页面
                    if (res.admin === 1) {
                      this.$router.push({ path: "/" });
                    } else if (
                      sessionStorage.getItem("org_type") == "2" ||
                      sessionStorage.getItem("org_type") == "3"
                    ) {
                      if (this.$route.query.fromPath === 'homePage') {
                        if (this.$route.query.type === 'bd') {
                          this.goBaidu(this.$route.query.listUrl, this.$route.query.url)
                        } else if (this.$route.query.type === 'ali') {
                          this.$router.push("/homePage/index");
                          this.goAliyun()
                        } else if (this.$route.query.type === 'rqy') {
                          this.$router.push("/product/productHome/k8s/createK8s");
                        } else {
                          this.$router.push(getHomePath());
                        }
                      } else {
                        this.$router.push(getHomePath());
                      } ``
                    } else if (res.roles.includes('运营')) {
                      this.$router.push('/operation/supplierManagement');
                    } else if (res.roles.includes('销售')) {
                      this.$router.push('/sales/distributorManagement');
                    } else if (res.roles.includes('运维')) {
                      this.$router.push('/operationAndMaintenance/workOrderProcessing');
                    } else {
                      this.$router.push({ path: "/" });
                    }

                    this.$message({
                      message: res.msg,
                      type: "success",
                    });
                  } else {
                    this.loading = false
                    this.$message({
                      message: res.msg,
                      type: "error",
                    });
                  }
                })
                .catch((res) => {
                  this.$message({
                    message: res.msg,
                    type: "error",
                  });
                  this.loading = false;
                });
            } else {
              this.$message({
                message: res.msg,

                type: "error",
              });
            }
          })
        } else {
          this.$message({
            message: res.msg,

            type: "error",
          });
          this.$refs.loginForm.resetFields();
          return false;
        }
      });
    },

    // 显示/隐藏密码
    showPwd() {
      if (this.passwordType === "password") {
        this.passwordType = "";
      } else {
        this.passwordType = "password";
      }
      this.$nextTick(() => {
        this.$refs.password.focus();
      });
    },

    // resetPassword() {
    //   this.dialogVisible = true;
    //   this.$refs.loginForm.resetFields();
    // },

    // 跳转到注册页面
    handleRegister() {
      console.log("注册按钮被点击了")
      this.$router.push({ name: "registrationPage" });
    },

    // cancelReset() {
    //   this.dialogVisible = false;
    //   this.$refs.form.resetFields();
    // },

    // handleSubmit() {
    //   let parmas = {
    //     id: this.form.id,
    //     password: this.form.password,
    //     codeid: this.form.codeid,
    //     vcode: this.form.vcode,
    //   };
    //   getPasswordCodeAPI(parmas).then((res) => {
    //     if (res.status == true) {
    //       this.$message({
    //         message: "密码重置成功",
    //         type: "success",
    //       });
    //       this.isDisabled1 = false;
    //       this.dialogVisible = false;
    //       this.SendCode_text1 = "获取验证码";
    //       clearInterval(this.timer1);
    //       this.timer1 = null;
    //       this.time_count1 = 60;
    //       this.$refs.form.resetFields();
    //     } else {
    //       this.$message({
    //         message: res.msg,
    //         type: "error",
    //       });
    //     }
    //   });
    // },
  }
}
</script>
<style scoped lang="scss">
$cursor: black;
$light_gray: #eee;
$dark_gray: #889aa4;

.main-box {
  background: url('/static/img/banner.0798e703.png') no-repeat center center;
  background-size: cover;
  width: 100vw;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;

  img {
    width: 100%;
    height: 100%;
  }
}

.conter {
  display: flex;
  width: 1400px;
  justify-content: space-around;
  align-items: center;
  margin-top: -60px;

  .left {
    .title {
      color: #222f60;
      font-size: 64px;
      text-align: center;

      .color {
        background: linear-gradient(to right, #0066FF, #66CCFF);
        -webkit-background-clip: text;
        background-clip: text;
        color: transparent;
        display: inline-block;
      }
    }

    .text {
      font-size: 32px;
      text-align: center;
      margin-top: 25px;
    }
  }
}

/* 统一登录表单容器 */
.login-form {
  padding: 40px 50px;
  mix-blend-mode: normal;
  background-color: white;
  border-radius: 24px;
  box-sizing: border-box;
}

/* 登录标题统一间距 */
.login-text {
  display: block;
  text-align: center;
  margin-bottom: 30px;
  font-family: PingFang SC;
  font-size: 24px;
  font-weight: 500;
  color: #333;
}

/* 统一输入框容器样式 */
.user-input {
  display: flex;
  align-items: center;
  width: 100%;
  height: 40px;
}

/* 统一图标容器 */
.icon-box {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 24px;
  height: 24px;
  margin: 0 8px;
  flex-shrink: 0;
}

/* 统一表单项目样式 + 边距 */
::v-deep .el-form-item {
  margin-bottom: 24px !important;
  /* 给错误提示预留空间 */
}

/* 统一输入框外框 */
::v-deep .el-input,
::v-deep .el-input__inner {
  width: 100%;
  height: 40px;
  line-height: 40px;
  border: none;
  background: transparent;
  padding: 0 10px !important;
  box-sizing: border-box;
  font-size: 14px;
}

/* 统一表单输入框外层容器 */
.login-form-style {
  .el-form-item {
    border: 1px solid #d9d9d9;
    background: #fff;
    border-radius: 4px;
    min-height: 40px;
    overflow: visible;
    position: relative;
  }

  /* 密码框提示样式 */
  .el-tooltip {
    display: block;
  }

  /* 验证码输入框宽度 */
  .invitecode {
    width: 180px !important;
  }
}

::v-deep .el-form-item__error {
  padding-top: 6px;
  font-size: 12px;
  line-height: 1.4;
}

/* 自动填充背景色覆盖 */
::v-deep .el-input__inner:-webkit-autofill {
  -webkit-box-shadow: 0 0 0 1000px #fff inset !important;
  -webkit-text-fill-color: #333 !important;
}

/* 密码显示隐藏按钮 */
.show-pwd {
  display: flex;
  align-items: center;
  padding-right: 10px;
  cursor: pointer;
}

/* 验证码按钮统一样式 */
.getCodeStyleNew {
  width: 110px;
  height: 40px;
  font-size: 13px;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #41464f;
  border: 1px solid #dde2e9;
  background: #f6f8fa;
  border-radius: 4px;
  transition: all 0.2s;

  &:hover {
    cursor: pointer;
    border-color: #4281ff;
    background: #fafbfc;
  }
}

/* 登录按钮统一间距 */
.login-btn {
  height: 42px;
  line-height: 42px;
  font-size: 16px;
  margin-top: 10px !important;
  margin-bottom: 20px !important;
}

/* 底部按钮区域统一 */
.two-btn {
  width: 300px;
  display: flex;
  justify-content: center;
  margin-top: 0;
}

.go-register {
  font-size: 14px;
  color: #333;

  .go-register-btn {
    color: #409eff;
    border-bottom: 1px solid #409eff;
    cursor: pointer;
    margin-left: 4px;
  }
}

/* 弹窗样式统一 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  padding-top: 10px;
}

/* Logo 定位统一 */
.logo-top {
  width: 200px !important;
  height: 70px !important;
  position: absolute;
  top: 20px;
  left: 20px;
}

.logo-top1 {
  width: 260px !important;
  height: 80px !important;
  position: absolute;
  top: 20px;
  left: 20px;
}

/* 底部信息 */
.message-footer {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  align-items: center;
  height: 50px;
  position: absolute;
  width: 100%;
  bottom: 0;
  z-index: 10;
  color: #000;
  font-size: 12px;

  .item {
    display: flex;
    align-items: center;
    margin-bottom: 5px;
  }

  span {
    margin: 0 10px;
  }
}

.goPAge {
  cursor: pointer;
  transition: color 0.3s;

  &:hover {
    color: #409eff;
  }
}

/* 隐藏不需要的下划线 */
::v-deep .el-tabs__nav-wrap::after {
  display: none;
}

/* 响应式 */
@media screen and (max-width: 760px) {
  .login-form {
    width: 90% !important;
    padding: 30px 20px;
  }
}
</style>
