<template>
  <div class="login flex justify-center items-center h-full">
    <div class="login-box">
      <t-form
        ref="form"
        :data="formData"
        :label-width="0"
        class="login-form"
        :rules="rules"
      >
        <t-form-item name="loginName">
          <t-input
            v-model="formData.loginName"
            clearable
            placeholder="账号"
            size="large"
          >
            <template #prefix-icon>
              <desktop-icon />
            </template>
          </t-input>
        </t-form-item>

        <t-form-item name="password">
          <t-input
            v-model="formData.password"
            type="password"
            clearable
            placeholder="密码"
            size="large"
          >
            <template #prefix-icon>
              <lock-on-icon />
            </template>
          </t-input>
        </t-form-item>
      </t-form>
      <t-button
        block
        class="m-t-30px"
        @click="loginHandle"
        size="large"
        theme="success"
        >登 录</t-button
      >
    </div>
  </div>
  <!-- <button @click="loginHandle" class="m-t-10px">登录！</button> -->
</template>

<script setup name="Login">
import { ref, reactive, computed, watch } from 'vue';
import { DesktopIcon, LockOnIcon } from 'tdesign-icons-vue-next';
import { useRoute, useRouter } from 'vue-router';
import { useUserStore } from '@/store';
import { MessagePlugin } from 'tdesign-vue-next';
import { getBase64 } from '@/utils/crypto';

const form = ref(null);

const route = useRoute();
const router = useRouter();

const formData = reactive({
  loginName: 'sysadmin',
  password: '123456',
});
const rules = {
  loginName: [
    { required: true, message: '请输入账号', type: 'error', trigger: 'change' },
  ],
  password: [
    { required: true, message: '请输入密码', type: 'error', trigger: 'change' },
  ],
};

const userStore = useUserStore();

const loginHandle = () => {
  form.value.validate().then(async (result) => {
    const redirect = route.query.redirect;
    // ? route.query.redirect
    // : '/my-workbenches';
    if (result === true) {
      await userStore.login({
        loginName: formData.loginName,
        password: getBase64(formData.password),
        type: 'ACCOUNT',
      });
      await userStore.requestUserMenu();
      if (redirect) {
        router.push(redirect);
      } else {
        router.push({ name: userStore.menus[0].name });
      }
    }
  });
};
</script>
<style lang="less" scoped>
.login {
  background: rgba(26, 188, 156, 1);
  .login-box {
    width: 350px;
    background: #fff;
    box-shadow: rgba(0, 0, 0, 0.35) 0px 0px 10px;
    border-radius: 10px;
    padding: 24px;
  }
}
</style>
