<template>
  <div class="login-container">
    <div class="gradient-background"></div>
    <canvas id="canvas1"></canvas>
    <div class="form-content">
      <!-- <div class="title-container">
        <img src="../../assets/images/login-head.png" class="images" />
      </div> -->
      <div class="login_form" v-if="loginOrRetrieve == 'login'">
        <h2>AI知识库管理</h2>
        <el-form
          ref="loginForm"
          :model="loginForm"
          :rules="loginRules"
          class="login-form"
          autocomplete="on"
          label-position="left"
        >
          <el-form-item prop="username">
            <span class="svg-container">
              <svg-icon icon-class="user" />
            </span>
            <el-input
              ref="username"
              v-model="loginForm.username"
              placeholder="登录用户名"
              name="username"
              type="text"
              tabindex="1"
              autocomplete="on"
            />
          </el-form-item>

          <el-tooltip
            v-model="capsTooltip"
            content="Caps lock is On"
            placement="right"
            manual
          >
            <el-form-item prop="password">
              <span class="svg-container">
                <svg-icon icon-class="password" />
              </span>
              <el-input
                :key="passwordType"
                ref="password"
                v-model="loginForm.password"
                :type="passwordType"
                placeholder="登录密码"
                name="password"
                tabindex="2"
                autocomplete="on"
                @keyup.native="checkCapslock"
                @blur="capsTooltip = false"
                @keyup.enter.native="handleLogin"
              />
              <span class="show-pwd" @click="showPwd">
                <svg-icon
                  :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'"
                />
              </span>
            </el-form-item>
          </el-tooltip>
          <div class="tips">
            <div @click="Retrieve('retrieve')" style="cursor: pointer">
              找回密码？
            </div>
          </div>
          <el-button
            :loading="loading"
            class="login_btns"
            type="primary"
            style="width: 100%; margin-bottom: 30px"
            @click="handleLogin"
            >立即登录</el-button
          >
        </el-form>
      </div>
      <div class="login_form" v-if="loginOrRetrieve == 'retrieve'">
        <h2>AI知识库管理</h2>
        <el-form
          ref="RetrieveForm"
          :model="RetrieveForm"
          :rules="RetrieveRules"
          class="login-form"
          autocomplete="on"
          label-position="left"
        >
          <el-form-item prop="phone">
            <el-input
              ref="phone"
              v-model="RetrieveForm.phone"
              placeholder="请输入手机号"
              name="phone"
              type="text"
              tabindex="1"
              autocomplete="on"
            />
          </el-form-item>
          <el-tooltip
            v-model="capsTooltip"
            content="Caps lock is On"
            placement="right"
            manual
          >
            <el-form-item prop="verification_code">
              <el-input
                ref="verification_code"
                v-model="RetrieveForm.verification_code"
                type="text"
                placeholder="请输入验证码"
                name="text"
                tabindex="2"
                autocomplete="on"
              />
              <span class="show-pwd">
                <el-button
                  type="primary"
                  :disabled="isDisabled"
                  @click="getCode"
                >
                  {{ buttonText }}
                </el-button>
              </span>
            </el-form-item>
          </el-tooltip>

          <el-tooltip
            v-model="capsTooltip"
            content="Caps lock is On"
            placement="right"
            manual
          >
            <el-form-item prop="new_password1">
              <span class="svg-container">
                <svg-icon icon-class="password" />
              </span>
              <el-input
                :key="passwordType"
                ref="password"
                v-model="RetrieveForm.new_password1"
                :type="passwordType"
                placeholder="请输入新密码"
                name="password"
                tabindex="2"
                autocomplete="on"
                @keyup.native="checkCapslock"
                @blur="capsTooltip = false"
              />
              <span class="show-pwd" @click="showPwd">
                <svg-icon
                  :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'"
                />
              </span>
            </el-form-item>
          </el-tooltip>
          <el-tooltip
            v-model="capsTooltip"
            content="Caps lock is On"
            placement="right"
            manual
          >
            <el-form-item prop="new_password2">
              <span class="svg-container">
                <svg-icon icon-class="password" />
              </span>
              <el-input
                :key="passwordType"
                ref="passwords"
                v-model="RetrieveForm.new_password2"
                :type="passwordTypes"
                placeholder="确认新密码"
                name="password"
                tabindex="2"
                autocomplete="on"
                @keyup.native="checkCapslock"
                @blur="capsTooltips = false"
              />
              <span class="show-pwd" @click="showPwds">
                <svg-icon
                  :icon-class="
                    passwordTypes === 'password' ? 'eye' : 'eye-open'
                  "
                />
              </span>
            </el-form-item>
          </el-tooltip>
          <div class="tips">
            <div @click="Retrieve('login')" style="cursor: pointer">
              返回登录
            </div>
          </div>
          <el-button
            :loading="loading"
            type="primary"
            class="login_btns"
            style="width: 100%; margin-bottom: 30px"
            @click="retPass"
            >重置密码</el-button
          >
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import { validUsername } from "@/utils/validate";
import { tailPhone, codeCheckout, updatePassword, login } from "@/api/user";
import SocialSign from "./components/SocialSignin";

export default {
  name: "Login",
  components: { SocialSign },
  data() {
    const validateUsername = (rule, value, callback) => {
      if (value.length < 3) {
        callback(new Error("请填写正确的登录用户名"));
      } else {
        callback();
      }
    };
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error("请填写正确的密码,密码不得小于6位"));
      } else {
        callback();
      }
    };
    const validatePhone = (rule, value, callback) => {
      const phoneRegex = /^1[3-9]\d{9}$/;
      if (value === "") {
        callback(new Error("请输入手机号码"));
      } else if (!phoneRegex.test(value)) {
        callback(new Error("请输入正确的手机号码"));
      } else {
        callback();
      }
    };

    const validateNewPassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error("新密码不能少于6个字符"));
      } else {
        if (this.RetrieveForm.new_password2 !== "") {
          this.$refs.RetrieveForm.validateField("new_password2");
        }
        callback();
      }
    };

    const validateConfirmPassword = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.RetrieveForm.new_password1) {
        callback(new Error("两次输入的密码不一致"));
      } else {
        callback();
      }
    };
    return {
      loginForm: {
        username: "",
        password: "",
      },
      loginRules: {
        username: [
          { required: true, trigger: "blur", validator: validateUsername },
        ],
        password: [
          { required: true, trigger: "blur", validator: validatePassword },
        ],
      },
      passwordType: "password",
      passwordTypes: "password",
      capsTooltip: false,
      loading: false,
      showDialog: false,
      redirect: undefined,
      otherQuery: {},
      loginOrRetrieve: "login",
      RetrieveForm: {
        phone: "",
        verification_code: "",
        new_password1: "",
        new_password2: "",
      },
      RetrieveRules: {
        phone: [{ required: true, trigger: "blur", validator: validatePhone }],
        verification_code: [
          { required: true, message: "请输入验证码", trigger: "blur" },
        ],
        new_password1: [
          { required: true, trigger: "blur", validator: validateNewPassword },
        ],
        new_password2: [
          {
            required: true,
            trigger: "blur",
            validator: validateConfirmPassword,
          },
        ],
      },
      countdown: 60,
      isDisabled: false,
      buttonText: "获取验证码",
    };
  },
  watch: {
    $route: {
      handler: function (route) {
        const query = route.query;
        if (query) {
          this.redirect = query.redirect;
          this.otherQuery = this.getOtherQuery(query);
        }
      },
      immediate: true,
    },
  },
  created() {
    // window.addEventListener('storage', this.afterQRScan)
  },
  mounted() {
    if (this.loginForm.username === "") {
      this.$refs.username.focus();
    } else if (this.loginForm.password === "") {
      this.$refs.password.focus();
    }
    this.initParticles();
  },
  destroyed() {
    // window.removeEventListener('storage', this.afterQRScan)
  },
  methods: {
    /* 找回密码 */
    retPass() {
      this.$refs.RetrieveForm.validate((valid) => {
        if (valid) {
          codeCheckout({
            phone: this.RetrieveForm.phone,
            verification_code: this.RetrieveForm.verification_code,
          })
            .then((response) => {
              if (response.status !== 200) return;
              updatePassword(this.RetrieveForm).then((res) => {
                this.loginOrRetrieve = "login";
                this.$message.success("密码已成功重置");
              });
            })
            .catch((error) => {
              this.$message.error("验证码校验失败");
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    /* 获取验证码 */
    getCode() {
      this.$refs.RetrieveForm.validateField("phone", (errorMessage) => {
        if (errorMessage) {
          this.$message.warning(errorMessage);
        } else {
          this.isDisabled = true;
          this.buttonText = `${this.countdown}s`;
          const timer = setInterval(() => {
            if (this.countdown > 0) {
              this.countdown--;
              this.buttonText = `${this.countdown}s`;
            } else {
              clearInterval(timer);
              this.isDisabled = false;
              this.buttonText = "获取验证码";
              this.countdown = 60;
            }
          }, 1000);

          tailPhone({ phone: this.RetrieveForm.phone }).then((res) => {
            console.log(res);
          });
        }
      });
    },
    showPwds() {
      if (this.passwordTypes === "password") {
        this.passwordTypes = "";
      } else {
        this.passwordTypes = "password";
      }
      this.$nextTick(() => {
        this.$refs.passwords.focus();
      });
    },
    checkCapslock(e) {
      const { key } = e;
      this.capsTooltip = key && key.length === 1 && key >= "A" && key <= "Z";
    },
    showPwd() {
      if (this.passwordType === "password") {
        this.passwordType = "";
      } else {
        this.passwordType = "password";
      }
      this.$nextTick(() => {
        this.$refs.password.focus();
      });
    },
    handleLogin() {
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          this.loading = true;
          this.$store
            .dispatch("user/login", this.loginForm)
            .then(() => {
              this.$router.push({
                path: this.redirect || "/",
                query: this.otherQuery,
              });
              this.loading = false;
            })
            .catch(() => {
              this.loading = false;
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== "redirect") {
          acc[cur] = query[cur];
        }
        return acc;
      }, {});
    },
    // afterQRScan() {
    //   if (e.key === 'x-admin-oauth-code') {
    //     const code = getQueryObject(e.newValue)
    //     const codeMap = {
    //       wechat: 'code',
    //       tencent: 'code'
    //     }
    //     const type = codeMap[this.auth_type]
    //     const codeName = code[type]
    //     if (codeName) {
    //       this.$store.dispatch('LoginByThirdparty', codeName).then(() => {
    //         this.$router.push({ path: this.redirect || '/' })
    //       })
    //     } else {
    //       alert('第三方登录失败')
    //     }
    //   }
    // }
    /* 找回密码 */
    Retrieve(val) {
      this.loginOrRetrieve = val;
    },
    /* 粒子动画 */
    initParticles() {
      const canvas = document.getElementById("canvas1");
      const ctx = canvas.getContext("2d");
      canvas.width = window.innerWidth;
      canvas.height = window.innerHeight;

      let mouse = {
        x: null,
        y: null,
        radius: 150, // 可以调整鼠标影响范围
      };

      canvas.addEventListener("mousemove", function (event) {
        mouse.x = event.x;
        mouse.y = event.y;
      });

      canvas.addEventListener("mouseout", function () {
        mouse.x = undefined;
        mouse.y = undefined;
      });

      class Particle {
        constructor() {
          this.x = Math.random() * canvas.width;
          this.y = Math.random() * canvas.height;
          this.size = Math.random() * 3 + 1;
          this.baseX = this.x;
          this.baseY = this.y;
          this.density = Math.random() * 30 + 1;
          // 增加速度范围到 -2 到 2
          this.speedX = (Math.random() - 0.5) * 3.5; // 从2改为4
          this.speedY = (Math.random() - 0.5) * 3.5; // 从2改为4
          // 添加额外的动画参数
          this.angle = Math.random() * 360;
          this.angleSpeed = (Math.random() - 0.5) * 2; // 旋转速度
          this.oscillationRadius = Math.random() * 5; // 振荡幅度
        }

        draw() {
          ctx.beginPath();
          ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
          ctx.fillStyle = "#ffffff";
          ctx.fill();
        }

        update() {
          // 优化计算，减少三角函数计算频率
          if (this.angle > 360) this.angle -= 360;
          const angleRad = (this.angle * Math.PI) / 180;
          const oscillation = Math.sin(angleRad) * this.oscillationRadius * 0.1;

          this.baseX += this.speedX + oscillation;
          this.baseY += this.speedY + oscillation;

          // 边界检查 - 添加随机性
          if (this.baseX > canvas.width || this.baseX < 0) {
            this.speedX *= -1;
            //this.speedX += (Math.random() - 0.5) * 0.5; // 添加随机速度变化
          }
          if (this.baseY > canvas.height || this.baseY < 0) {
            this.speedY *= -1;
            // this.speedY += (Math.random() - 0.5) * 0.5; // 添加随机速度变化
          }

          // 限制最大速度
          const maxSpeed = 5;
          this.speedX = Math.max(Math.min(this.speedX, maxSpeed), -maxSpeed);
          this.speedY = Math.max(Math.min(this.speedY, maxSpeed), -maxSpeed);

          // 鼠标交互
          let dx = mouse.x - this.x;
          let dy = mouse.y - this.y;
          let distance = Math.sqrt(dx * dx + dy * dy);
          let forceDirectionX = dx / distance;
          let forceDirectionY = dy / distance;
          let maxDistance = mouse.radius;
          let force = (maxDistance - distance) / maxDistance;
          let directionX = forceDirectionX * force * this.density;
          let directionY = forceDirectionY * force * this.density;

          if (distance < mouse.radius && mouse.x != undefined) {
            // 增加鼠标排斥力
            this.x -= directionX * 2; // 增加排斥力度
            this.y -= directionY * 2;
          } else {
            // 更快地回到基准位置
            if (this.x !== this.baseX) {
              let dx = this.x - this.baseX;
              this.x -= dx / 5; // 从10改为5，使回归更快
            }
            if (this.y !== this.baseY) {
              let dy = this.y - this.baseY;
              this.y -= dy / 5;
            }
          }
        }
      }

      let particlesArray = [];

      function init() {
        particlesArray = [];
        // 增加粒子数量
        const numberOfParticles = (canvas.width * canvas.height) / 7000; // 从9000改为7000
        for (let i = 0; i < numberOfParticles; i++) {
          particlesArray.push(new Particle());
        }
      }

      function connect() {
        let opacityValue = 1;
        for (let a = 0; a < particlesArray.length; a++) {
          for (let b = a; b < particlesArray.length; b++) {
            let distance =
              (particlesArray[a].x - particlesArray[b].x) *
                (particlesArray[a].x - particlesArray[b].x) +
              (particlesArray[a].y - particlesArray[b].y) *
                (particlesArray[a].y - particlesArray[b].y);

            // 增加连线距离和可见度
            if (distance < (canvas.width / 6) * (canvas.height / 6)) {
              // 从7改为6
              opacityValue = 1 - distance / 15000; // 从20000改为15000，使线条更明显
              ctx.strokeStyle = `rgba(255,255,255,${opacityValue})`;
              ctx.lineWidth = 1;
              ctx.beginPath();
              ctx.moveTo(particlesArray[a].x, particlesArray[a].y);
              ctx.lineTo(particlesArray[b].x, particlesArray[b].y);
              ctx.stroke();
            }
          }
        }
      }

      function animate() {
        ctx.clearRect(0, 0, canvas.width, canvas.height);

        for (let i = 0; i < particlesArray.length; i++) {
          particlesArray[i].update();
          particlesArray[i].draw();
        }
        connect();
        requestAnimationFrame(animate);
      }

      window.addEventListener("resize", function () {
        canvas.width = window.innerWidth;
        canvas.height = window.innerHeight;
        init();
      });

      init();
      animate();
    },
  },
};
</script>

<style lang="scss" >
/* 修复input 背景不协调 和光标变色 */
/* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */

.login_btns {
  width: 100%;
  font-size: 16px;
  display: flex;
  justify-content: center;
  background-image: linear-gradient(to right, #6366f1, #2563eb);
  color: #f3f4f6;
  padding: 1rem;
  border-radius: 9999px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.5s ease-in;
}
.el-button {
  border: none;
  box-shadow: none;
}
.login_btns:hover {
  background-image: linear-gradient(to left, #3b82f6, #6366f1) !important;
}
.login_btns:focus {
  border-color: #3b82f6 !important;
  background-image: linear-gradient(to left, #3b82f6, #6366f1) !important;
}
.login-container {
  position: relative;
  overflow: hidden;
}

#canvas1 {
  position: absolute;
  top: 0;
  left: 0;
  z-index: 1;
  width: 100%;
  height: 100%;
}
@import "./index.scss";
</style>
