<template>
  <div class="login-style">
    <div class="box-vessel">
      <div class="vessel-title">
        账号登录
      </div>
      <el-form
          :model="data"
          :rules="rules"
          ref="form"
          label-width="0"
      >
        <el-form-item prop="account">
          <el-input
              v-model="data.account"
              placeholder="请输入账号"
          />
        </el-form-item>
        <el-form-item prop="password">
            <el-input
                v-model="data.password"
                placeholder="请输入密码"
                show-password
            />
        </el-form-item>
        <el-form-item>
          <el-button class="login-button" @click="handleLogin">登录</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
  import "@/views/LoginPage/component/index.scss"
  import {reactive} from "vue";
  import router from "@/router";
  import {ElMessage} from "element-plus";
  import {useStore} from "@/store";
  import useApis from "@/apis";

  const store = useStore();
  const apis = useApis();

  const data = reactive({
    account: '',
    password: '',
  });

  const rules = reactive({
    account: [
      { required: true, message: '账号不能为空', trigger: 'blur' },
    ],
    password: [
      { required: true, message: '密码不能为空', trigger: 'blur' },
    ],
  });

  const handleLogin = () => {

    //1.判断是不是管理员账号
    if(data.account != "ADMIN"){
      ElMessage({
        message: '用户名或密码错误',
        type: 'error',
      })
      return;
    }

    // 2.登录
    apis.login({officialNumber: data.account, password: data.password})
        .then((_res:any) => {
          const data = _res.data.data
          if (_res.data.code === 200) {
            store.setUser(data);
            store.setToken(data?.token)
            localStorage.setItem('Authorization', data?.token);
            localStorage.setItem('User', data);
            // router.push("/")
            ElMessage({
              message: '登录成功',
              type: 'success',
            })
            router.push(`/manager/course`)
          } else if(_res.data.code === 400){
            ElMessage({
              message: '用户名或密码错误',
              type: 'error',
            })
          }
        })
        .catch((_err:any) => {
          ElMessage({
            message: '网络错误',
            type: 'error',
          })
          console.log("登陆失败", _err)
        })
      };

</script>

<script lang="ts">
export default {
  name: "AdminLoginForm"
}
</script>
