<template>
  <div class="login-box" v-if="isVisible">
    <div class="login-container">
      <div class="login-close" @click="closeLoginForm">
        <el-icon color="#333" size="24" class="btn_close"><Close /></el-icon>
      </div>
      <h4>欢迎登录</h4>
      <el-form
        :model="formData"
        :rules="rules"
        ref="formRef"
        label-width="88px"
        :hide-required-asterisk="true"
      >
        <el-form-item label="账号" prop="phoneNumber">
          <el-input
            size="large"
            v-model="formData.phoneNumber"
            placeholder="请输入账号"
          />
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input
            size="large"
            type="password"
            v-model="formData.password"
            placeholder="请输入密码"
          />
        </el-form-item>

        <el-form-item label="验证码" prop="captchaCode">
          <el-input
            size="large"
            type="text"
            v-model="formData.captchaCode"
            placeholder="请输入验证码"
            maxlength="4"
          >
            <template #append>
              <img
                class="captcha"
                :src="captchaUrl"
                alt="验证码"
                @click="refreshCaptcha"
              />
            </template>
          </el-input>
        </el-form-item>
      </el-form>

      <div class="foot">
        <el-button
          color="#ea4322"
          class="btn_sumit"
          size="large"
          round
          @click="handleLogin"
          :disabled="
            !formData.phoneNumber || !formData.password || !formData.captchaCode
          "
          >登录</el-button
        >
      </div>
      <div class="tool">
        没有账号？
        <el-button
          class="btn_sumit"
          type="danger"
          text
          @click="openRegisterForm"
          >立即入驻</el-button
        >
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import {
  ref,
  defineProps,
  defineEmits,
  watch,
  onMounted,
  onUnmounted,
} from "vue";
import { useUserStore } from "@/stores/userStore";
import { useRouter } from "vue-router";
import {
  GetLogin,
  GetSmsCode,
  GetVerifyCode,
  GetAccountLogin,
} from "@/api/login";
import { ElMessage } from "element-plus/es";
import { Close } from "@element-plus/icons-vue";

const props = defineProps({
  isVisible: {
    type: Boolean,
    default: false,
  },
});
const emits = defineEmits(["open-register-form", "close-login-form"]);

const formData = ref({
  phoneNumber: "",
  password: "",
  captchaCode: "",
});

const router = useRouter();
const userStore = useUserStore();
const verify_token = ref();
const captchaUrl = ref("");
const formRef = ref<InstanceType<typeof import("element-plus/es")["ElForm"]>>();

const closeLoginForm = () => {
  emits("close-login-form");
};

const openRegisterForm = () => {
  closeLoginForm();
  emits("open-register-form");
};

const refreshCaptcha = async () => {
  verify_token.value = new Date().getTime();
  const res = await GetVerifyCode({ verify_token: verify_token.value });

  if (res) {
    captchaUrl.value = `https://mall.gpxscs.cn/api/admin/shop/shop-base-config/image?verify_token=${verify_token.value}`;
  }
};

const initCaptcha = async () => {
  await refreshCaptcha();
};

initCaptcha();

watch(
  () => props.isVisible,
  (newValue) => {
    if (newValue) {
      refreshCaptcha();
    }
  }
);

const rules = ref({
  phoneNumber: [{ required: true, message: "请输入账号", trigger: "blur" }],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }],
  captchaCode: [{ required: true, message: "请输入验证码", trigger: "blur" }],
});

const handleLogin = async () => {
  formRef.value?.validate(async (valid) => {
    if (valid) {
      const params = {
        user_account: formData.value.phoneNumber,
        user_password: formData.value.password,
        verify_code: formData.value.captchaCode,
        verify_token: verify_token.value,
      };
      const res = await GetAccountLogin(params);
      if (res && res.status === 200) {
        console.log("登录成功", res);
        userStore.setToken(res.data.token);
        userStore.setMobilePhone(formData.value.phoneNumber);
        window.open(
          `https://mall.gpxscs.cn/admin/#/login?loginInfo=${JSON.parse(
            JSON.stringify(res.data)
          )}`,
          "_self"
        );
        formData.value.phoneNumber = "";
        formData.value.password = "";
        formData.value.captchaCode = "";
        console.log(res.data);
        closeLoginForm();
      } else if (
        res &&
        res.status === 250 &&
        res.data.msg == "用户名或密码错误!"
      ) {
        ElMessage.error("用户名或密码错误!");
        console.log("操作失败", res.msg);
      } else if (res && res.status === 250 && res.data.msg == "验证码错误") {
        ElMessage.error("验证码错误");
      }
    } else {
      ElMessage.error("请正确填写登录信息");
    }
  });
};

onMounted(() => {
  // 可以在这里添加一些初始化的逻辑
});

onUnmounted(() => {
  // 可以在这里添加一些清理的逻辑
});
</script>

<style lang="scss" scoped>
.login-box {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: rgba(0, 0, 0, 0.75);
  z-index: 1000101;
}
.el-message {
  z-index: 1000102 !important;
}
.login-container {
  padding: 25px;
  border-radius: 10px;
  background-color: #fff;
  width: 500px;
  position: relative;

  h4 {
    color: #666;
    text-align: center;
    margin-bottom: 30px;
    font-size: 24px;
  }

  .el-input {
    width: 100%;
  }

  .login-close {
    position: absolute;
    top: 10px;
    right: 10px;
    .btn_close {
      cursor: pointer;
      &:hover {
        color: #409efc;
      }
    }
  }

  .foot {
    padding-top: 20px;
    .btn_sumit {
      display: block;
      width: 100%;
    }

    .btn_code {
      display: block;
      width: 60px;
    }
  }

  :deep(.el-input-group__append) {
    padding: 0 !important;
  }

  .captcha {
    cursor: pointer;
    border: 1px solid #dcdfe6;
    border-left: none;
  }

  .tool {
    padding-top: 25px;
    display: flex;
    justify-content: center;
    align-items: center;
    text-align: center;
    font-size: 14px;
    color: #666;
  }
}
</style>
