<template>
  <el-dialog
    title="登录"
    :visible.sync="visible"
    :close-on-click-modal="false"
    width="360px"
    custom-class="login-dialog"
    @close="$emit('close')"
  >
    <el-form :model="form" :rules="rules" ref="loginForm" class="login-form">
      <el-form-item prop="phone">
        <el-input v-model="form.phone" placeholder="请输入手机号">
          <template slot="prepend">
            <i class="el-icon-mobile-phone"></i>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item prop="code">
        <el-input v-model="form.code" placeholder="请输入验证码">
          <el-button
            slot="append"
            @click="sendCode"
            :disabled="countdown > 0"
            class="send-code-btn"
          >
            {{ countdown > 0 ? `${countdown}s` : "发送验证码" }}
          </el-button>
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="login" class="login-btn"
          >登录</el-button
        >
      </el-form-item>
    </el-form>
  </el-dialog>
</template>
  
  <script>
import { pcLoging, pcSMS, codeCheckout } from "@/api/api";

export default {
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    const validatePhone = (rule, value, callback) => {
      if (!/^1[3-9]\d{9}$/.test(value)) {
        callback(new Error("请输入正确的手机号"));
      } else {
        callback();
      }
    };
    return {
      form: {
        phone: "",
        code: "",
      },
      rules: {
        phone: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: validatePhone, trigger: "blur" },
        ],
        code: [
          { required: true, message: "请输入验证码", trigger: "blur" },
          { len: 6, message: "验证码长度应为6位", trigger: "blur" },
        ],
      },
      countdown: 0,
    };
  },
  methods: {
    async sendCode() {
      if (!this.form.phone) {
        this.$message.error("请先输入手机号");
        return;
      }

      try {
        await pcSMS({ phone: this.form.phone });
        this.$message.success("验证码已发送");
        this.countdown = 60;
        const timer = setInterval(() => {
          this.countdown--;
          if (this.countdown === 0) {
            clearInterval(timer);
          }
        }, 1000);
      } catch (error) {
        this.$message.error("发送验证码失败：" + error.message);
      }
    },

    async login() {
      this.$refs.loginForm.validate(async (valid) => {
        if (valid) {
          try {
            // 先验证验证码
            const checkoutResult = await codeCheckout({
              phone: this.form.phone,
              verification_code: this.form.code,
            });

            // 检查验证码是否正确
            if (checkoutResult.status==200) {
              // 验证码正确，进行登录
              const loginResult = await pcLoging({
                phone: this.form.phone,
                code: this.form.code,
              });
              loginResult.data.phone=this.form.phone
              // 保存用户数据到本地存储
              this.saveUserData(loginResult);

              this.$message.success("登录成功");
              this.$emit("login-success");
              this.$emit("close");
            } else {
              // 验证码不正确，显示错误消息
              this.$message.error("验证码不正确");
            }
          } catch (error) {
            this.$message.error("操作失败：" + error.message);
          }
        } else {
          return false;
        }
      });
    },
    saveUserData(userData) {
      // 将用户数据保存到本地存储
      localStorage.setItem("AIData", JSON.stringify(userData));
      // 如果有token，单独保存token
    },
  },
};
</script>
  <style scoped>
.login-dialog {
  border-radius: 8px;
}

.login-form {
  padding: 0 20px;
}

.el-form-item {
  margin-bottom: 20px;
}

.login-btn {
  width: 100%;
}

.send-code-btn {
  width: 110px;
}

/* 添加一些过渡效果 */
.el-input-group__prepend,
.el-input-group__append,
.el-input__inner {
  transition: all 0.3s ease;
}

.el-input:hover .el-input__inner,
.el-input:hover .el-input-group__prepend,
.el-input:hover .el-input-group__append {
  border-color: #409eff;
}
</style>