<template>
  <div class="auth-wrap">
    <div v-if="!getIsAuthed">
      <div
        v-if="!isUsePopup"
        class="auth-logo-wrap"
      >
        <img
          :src="configApp.logoDark"
          class="auth-logo"
          alt="AutoShopee"
        >
      </div>

      <Card
        dis-hover
        class="auth-card"
      >
        <p
          slot="title"
          class="auth-card__title"
        >
          {{ $t('LOGIN_USER') }}
        </p>

        <Form
          ref="loginForm"
          :model="form"
          :rules="rules"
        >
          <FormItem prop="username">
            <Input
              v-model="form.username"
              :placeholder="$t('USERNAME')"
              prefix="ios-person"
              size="large"
              @keyup.enter.native="loginSubmit"
            />
          </FormItem>
          <FormItem prop="password">
            <Input
              v-model="form.password"
              type="password"
              :placeholder="$t('PASSWORD')"
              prefix="ios-lock"
              size="large"
              password
              @keyup.enter.native="loginSubmit"
            />
          </FormItem>
          <FormItem class="mb-0">
            <Button
              type="primary"
              long
              size="large"
              :loading="loading"
              @click="loginSubmit"
            >
              {{ $t('BTN_LOGIN') }}
            </Button>
          </FormItem>
        </Form>

        <Divider plain>
          {{ $t('REGISTER_OR') }}
        </Divider>

        <Button
          long
          @click="openPageRegister"
        >
          {{ $t('BTN_REGISTER') }}
        </Button>

        <p class="auth-note">
          {{ $t('LOGIN_PAGE_NOTE') }}
        </p>
      </Card>
    </div>

    <Alert
      v-else
      type="success"
      show-icon
      class="mt-10"
    >
      {{ $t('USER_WAS_LOGGED') }}
    </Alert>
  </div>
</template>

<script>
import { mapActions } from 'vuex';
import delay from 'delay';
import { loggerVue } from '@/plugins/logger';

export default {
  name: 'LoginIndex',
  data() {
    return {
      loading: false,
      form: {
        username: '',
        password: '',
      },
      returnUrl: '',
    };
  },
  computed: {
    rules() {
      return {
        username: [
          { required: true, message: this.$t('VALIDATE_FIELD_REQUIRED'), trigger: 'blur' },
        ],
        password: [
          { required: true, message: this.$t('VALIDATE_FIELD_REQUIRED'), trigger: 'blur' },
          { min: 6, message: this.$t('VALIDATE_PASSWORD_MIN'), trigger: 'blur' },
        ],
      };
    },
  },
  methods: {
    ...mapActions(['SetToken', 'SetUser', 'SetLogin', 'Logout']),
    openPageRegister() {
      this.RouterPath('/register');
    },
    async loginSubmit() {
      const valid = await new Promise((resolve) => {
        this.$refs.loginForm.validate((result) => resolve(result));
      });

      if (!valid) {
        return;
      }

      this.loading = true;

      try {
        const result = await this.UserLogin(this.form);

        if (!(result.success && result.token)) {
          this.$Message.error(result.msg || this.$t('LOGIN_ERROR'));

          throw {
            msg: 'LOGIN_ERROR',
            result,
          };
        }

        this.$Message.success(this.$t('LOGIN_SUCCESS'));

        await delay(500);

        if (this.returnUrl) {
          return this.RouterPath(this.returnUrl);
        }

        this.RouterTo('root');
      } catch (error) {
        loggerVue.error({
          msg: 'LOGIN_ERROR',
          error,
        });
      }

      this.loading = false;
    },
    autoLogin() {
      const { username, password, ref } = this.$route.query;

      if (!(username && password)) {
        return false;
      }

      this.form.username = username;
      this.form.password = password;

      if (ref === 'shop-manager') {
        this.SetUseShopManager(true);
      }

      delete this.$route.params.username;
      delete this.$route.params.password;

      this.$router.replace({
        name: this.$route.name,
        params: this.$route.params,
        query: {},
      });

      const loginMethod = this.loginSubmit;
      return setTimeout(loginMethod, 200);
    },
  },
  created() {
    this.returnUrl = this.$route.query.returnUrl;
    this.form.username = this.getUsername;
    this.form.password = this.getPassword;
    this.autoLogin();
  },
};
</script>

<style scoped>
.auth-wrap {
  padding: 16px 0;
}
.auth-logo-wrap {
  text-align: center;
  margin-bottom: 16px;
}
.auth-logo {
  height: 36px;
  object-fit: contain;
}
.auth-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}
.auth-card__title {
  font-size: 16px;
  font-weight: 600;
  text-align: center;
  color: #1a1a1a;
  margin: 0;
}
.auth-note {
  margin: 12px 0 0;
  text-align: center;
  font-size: 12px;
  color: #aaa;
}
</style>
