<template>
  <div class="body" ref="bg" :style="{ backgroundImage: `url(https://www.hxyouzi.com/blog/bg/bg-l.webp)` }">
    <n-card class="box" v-if="!isPass">
      <n-tabs class="card-tabs" ref="tabsInstRef" v-model:value="value" size="large" animated default-value="signin" justify-content="space-evenly">
        <n-tab-pane name="signin" tab="登录">
          <n-form :model="loginInfo" :rules="rules" ref="loginForm">
            <n-form-item-row label="用户名" path="username">
              <n-input :readonly="readonly" @blur="readonly = true" @focus="readonly = false" v-model:value="loginInfo.username" placeholder="请填写邮箱 | 手机号" />
            </n-form-item-row>
            <n-form-item-row label="密码" path="password">
              <n-input :readonly="readonly" @blur="readonly = true" @focus="readonly = false" @keyup.enter="userLogin" v-model:value="loginInfo.password" type="password" show-password-on="mousedown" placeholder="请输入密码" />
            </n-form-item-row>
          </n-form>
          <div @click="isPass = true" class="text-right text-[12px] mr-1 mb-2 text-pp-500 underline italic">忘记密码？去找回</div>
          <n-button type="info" :loading="loading" block @click="userLogin">登录</n-button>
        </n-tab-pane>
        <n-tab-pane name="signup" tab="注册">
          <n-form :model="regInfo" :rules="regRules" ref="regForm">
            <n-form-item-row label="昵称" path="nickname">
              <n-input v-model:value="regInfo.nickname" @keydown.enter.prevent placeholder="请输入昵称" />
            </n-form-item-row>
            <n-form-item-row label="邮箱" path="username">
              <n-input :readonly="readonly" @blur="readonly = true" @focus="readonly = false" v-model:value="regInfo.username" @keydown.enter.prevent placeholder="请填写邮箱" />
            </n-form-item-row>
            <n-form-item-row path="code" label="验证码">
              <n-input-group>
                <n-input :readonly="readonly" @blur="readonly = true" @focus="readonly = false" v-model:value="regInfo.code" placeholder="请填写验证码" />
                <n-button type="info" @click="getCode">获取验证码</n-button>
              </n-input-group>
            </n-form-item-row>
            <n-form-item-row label="密码" path="password">
              <n-input :readonly="readonly" @blur="readonly = true" @focus="readonly = false" v-model:value="regInfo.password" type="password" show-password-on="mousedown" @input="handlePasswordInput" placeholder="请输入密码" @keydown.enter.prevent />
            </n-form-item-row>
            <n-form-item-row label="重复密码" path="repassword">
              <n-input :readonly="readonly" @blur="readonly = true" @focus="readonly = false" ref="reInput" type="password" show-password-on="mousedown" v-model:value="regInfo.repassword" placeholder="请再次输入密码" @keyup.enter="register" />
            </n-form-item-row>
          </n-form>
          <n-button type="info" :loading="loading" block @click="register">注册</n-button>
        </n-tab-pane>
      </n-tabs>
    </n-card>
    <n-card class="box" v-else>
      <pass @back="stepBack" />
    </n-card>
    <div class="p">
      <p>{{ p.content }}</p>
      <p class="p-title">—— {{ p.author ? p.author : "佚名" }}</p>
    </div>
  </div>
</template>

<script setup>
import pass from "@/components/pass.vue";
import { loginStore } from "@/stores/login.js";
import { onMounted, reactive, ref } from "vue";
import cookie from "vue-cookies";
import { useRoute, useRouter } from "vue-router";

const logx = loginStore();
const isPass = ref(false);
const loginInfo = reactive({
  username: "",
  password: "",
});
const regInfo = reactive({
  nickname: "",
  code: "",
  username: "",
  password: "",
  repassword: "",
});
const p = ref({});
const value = ref("signin");
const loginForm = ref(null);
const regForm = ref(null);
const reInput = ref(null);
const bg = ref(null);
const loading = ref(false);
const router = useRouter();
const route = useRoute();
let readonly = ref(true);
const rules = {
  username: [
    { required: true, message: "邮箱不能为空", trigger: "blur" },
    { validator: validateUsername, message: "请填写有效格式的邮箱或者手机号", trigger: "blur" },
  ],
  password: [
    { required: true, message: "密码不能为空", trigger: "blur" },
    { validator: validatePassword, message: "请填写正确格式的密码", trigger: "blur" },
  ],
};
const regRules = {
  nickname: [{ required: true, message: "昵称不能为空", trigger: "blur" }],
  code: [
    { required: true, message: "验证码不能为空", trigger: "blur" },
    { len: 6, message: "验证码长度为6", trigger: "blur" },
  ],
  username: [
    { required: true, message: "邮箱不能为空", trigger: "blur" },
    { validator: validateMail, message: "请填写有效格式的邮箱", trigger: "blur" },
  ],
  password: [
    { required: true, message: "密码不能为空", trigger: "blur" },
    { validator: validatePassword, message: "必须是含有数字，字母的6-12位密码", trigger: "blur" },
  ],
  repassword: [
    { required: true, message: "密码不能为空", trigger: "blur" },
    { validator: validatePassword, message: "必须是含有数字，字母的6-12位密码", trigger: "blur" },
    { validator: validatePasswordStartWith, message: "两次密码输入不一致", trigger: "input" },
    { validator: validatePasswordSame, message: "两次密码输入不一致", trigger: ["blur", "password-input"] },
  ],
};
// poetry();
onMounted(async () => {
  const res = await $http.mix.poetry();
  console.log(res);
  p.value = res.data[0];
});

function userLogin() {
  loading.value = true;
  loginForm.value?.validate(async err => {
    if (!err) {
      const res = await $http.user.login(loginInfo);
      if (res.code == 1) {
        cookie.set("token", res.token, "7d");
        cookie.set("userinfo", res.data, "7d");
        $msg.success(res.msg);
        logx.setLoginStatus(true);
        if (route.query.redirect) {
          router.push({
            path: route.query.redirect.toString(),
          });
        } else {
          router.push("/home");
        }
      } else {
        $msg.error(res.msg);
      }
      loading.value = false;
    } else {
      $msg.error(err[0][0].message)
      loading.value = false;
    }
  });
}
function handlePasswordInput() {
  if (regInfo.repassword) {
    reInput?.validate({ trigger: "password-input" });
  }
}
async function getCode() {
  if (!regInfo.username) {
    $msg.error("请输入邮箱");
    return;
  }
  const res = await $http.addr.sendMail({ mail: regInfo.username });
  if (res.code == "1") $msg.success(res.msg);
  else if (res.code == "0") $msg.error(res.msg);
}

function register(e) {
  e.preventDefault();
  loading.value = true;
  regForm.value?.validate(async errors => {
    if (!errors) {
      const res = await $http.user.regis(regInfo);
      if (res.code == 1) {
        value.value = "signin";
        $msg.success(res.msg);
      } else {
        $msg.error(res.msg);
      }
      loading.value = false;
    } else {
      $msg.error(errors[0][0].message)
      loading.value = false;
    }
  });
}
function validatePasswordStartWith(rule, value) {
  return !!regInfo.password && regInfo.password.startsWith(value) && regInfo.password.length >= value.length;
}
function validatePasswordSame(rule, value) {
  return value === regInfo.password;
}
function validateUsername(rule, value) {
  return /^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$/.test(value) || /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/.test(value)
  
}
function validateMail(rule, value) {
  return /^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$/.test(value);
}
function validatePassword(r, v) {
  return /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,12}$/.test(v);
}

function stepBack() {
  // console.log(99999999);
  isPass.value = false;
}
// bg.value.style.backgroundImage = theme.theme == null ? "url(../assets/bg/bg-l.webp)" : "url(../assets/bg/bg-d.webp)"
</script>

<style scoped lang="less">
:deep(.n-card.n-card--bordered ){
  border: none !important;
}
:deep(.n-tabs-bar) {
  display: none;
}
:deep(.n-tabs-tab__label) {
  color: @blue;
}
:deep(.n-tabs-tab--active .n-tabs-tab__label) {
  color: @purple;
}
:deep(.n-form-item-label__text) {
  color: @purple;
}

.p {
  position: absolute;
  bottom: 20px;
  width: 100%;
  text-align: center;
  font-size: 16px;
  font-weight: 500;
  p {
    padding: 0;
    margin: 0;
  }
  .p-title {
    text-align: right;
    padding-right: 10%;
  }
}
.box {
  width: 400px;
  position: absolute;
  right: 4%;
  top: 12%;
  background-color: #aaaaaa90;
  color: @purple;
  border-radius: 8px;
}
.body {
  width: 100vw;
  height: 100vh;
  // background-image: url(../assets/bg/bg-d.webp);
  background-repeat: no-repeat;
  background-size: cover;
  position: relative;
}
@media screen and (max-width: 800px) {
  .box {
    width: 90%;
    right: 5%;
  }
}
:deep(.n-form-item-feedback__line) {
  font-size: 12px;
  display: none;
  margin-right: 6px;
}
:deep(.n-form-item-feedback__line:first-child) {
  font-size: 12px;
  display: inline-block;
  margin-right: 6px;
}
</style>
