<!-- 登录页面 -->
<template>
  <div class="page page-login flex h-full w-full items-center justify-center">
    <div class="flex min-w-[450px] flex-col justify-center bg-white p-[25px]">
      <h1 class="mb-4 text-center text-[24px] font-[500]">{{ systemName }}</h1>
      <el-form class="w-full" ref="form" :model="form" :rules="rules" hide-required-asterisk>
        <el-form-item prop="loginName">
          <el-input
            clearable
            prefix-icon="el-icon-user"
            placeholder="请输入用户名"
            v-model="form.loginName"
          >
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            clearable
            prefix-icon="el-icon-lock"
            placeholder="请输入密码"
            show-password
            v-model="form.password"
            type="password"
            @keyup.enter="onSubmit"
          ></el-input>
        </el-form-item>
        <el-form-item prop="securityCode">
          <div class="code flex gap-2">
            <el-input
              clearable
              placeholder="请输入验证码"
              v-model="form.securityCode"
              @keyup.enter="onSubmit"
            ></el-input>
            <div class="code-box h-[40px] cursor-pointer overflow-hidden rounded-[4px]">
              <img
                v-show="securityUrl"
                class="h-full w-full"
                :src="securityUrl"
                @click="createCode"
              />
            </div>
          </div>
        </el-form-item>
        <el-form-item>
          <div>
            <el-button
              class="w-full"
              type="primary"
              native-type="submit"
              :loading="loading"
              @click="onSubmit"
              >登录</el-button
            >
          </div>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import storage from '@/utils/storage';
import { mapMutations } from 'vuex';
import { getHomeData } from '@/api/home';
import { generateRoutes, filterBtn } from '@/utils';
import { calcMenu } from '@/router';
import { login, loginCode } from '@/api/login';
import { systemName } from '@/config';
export default {
  name: 'login',
  data() {
    return {
      systemName,
      // api: process.env.VUE_APP_API_BASE_URL,
      securityUrl: '',
      loading: false,
      form: {
        loginName: '',
        password: '',
        securityCode: ''
      },
      rules: {
        loginName: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        securityCode: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
      }
    };
  },
  created() {
    this.createCode();
  },
  methods: {
    ...mapMutations('user', [
      'SET_token',
      'SET_sysName',
      'SET_sysLogo',
      'SET_path',
      'SET_userInfo',
      'SET_permissions',
      'SET_routes',
      'SET_menusList'
    ]),

    // 获取验证码
    async createCode() {
      let mark = new Date().getTime();
      let res = await loginCode({
        t: mark
      });
      if (res.data) {
        let url = URL.createObjectURL(res.data);
        this.securityUrl = url;
      }
    },

    onSubmit() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          this.loading = true;
          let res = await login(this.form);
          if (res.data.code == 1) {
            let {
              token,
              user: { id, loginName, siteIds }
            } = res.data.data;
            let form = {
              token,
              userInfo: {
                id,
                name: loginName
              }
            };
            if (siteIds) {
              let siteid = siteIds.split(',')[0];
              form.siteid = siteid;
            }
            await this.getToken(form);
          }
          this.loading = false;
        }
      });
    },
    // 获取token
    async getToken(info) {
      let { token, userInfo, siteid } = info;
      if (token && userInfo) {
        this.SET_userInfo(userInfo);
        this.SET_token(token);
        storage.set(2, 'siteId', siteid);
        // storage.set(2, "siteName", siteName);
        await this.getIndixData();
      } else {
        this.$message.warning('登录失败,请稍后再试');
      }
    },
    // 获取菜单列表
    async getIndixData() {
      let res = await getHomeData();
      if (res.data.code == 1) {
        let { menuList } = res.data.data;
        // 过滤掉按钮
        let menus = filterBtn(menuList, false);
        let routes = generateRoutes(menus);
        // this.SET_routes(routes);
        this.SET_menusList(menus);
        this.setBtnPermissions(menuList);
        calcMenu();
        if (routes.length) {
          let path = routes[0].path;
          this.$router.push(path);
        } else {
          this.$message.warning('暂无权限，请联系管理员！');
        }
      }
    },

    // 添加按钮权限字符
    setBtnPermissions(menuList) {
      let btnPermissions = filterBtn(menuList)
        .filter((v) => v.perms)
        .map((v) => v.perms);
      this.SET_permissions(btnPermissions);
    }
  },
  beforeDestroy() {
    if (this.securityUrl) {
      URL.revokeObjectURL(this.securityUrl);
    }
  }
};
</script>

<style lang="less" scoped>
.page-login {
  background-image: linear-gradient(45deg, #333, #111);
  background-size: 40px 40px;
  .code-box {
    border: 1px solid #dcdfe6;
  }
}
</style>
