<script setup lang="ts">
import { ref } from 'vue';
import { useRouter } from 'vue-router';

import SvgIcon from '@/components/SvgIcon.vue';
import { useRequest } from '@/hooks/request';
import { useUserInfoStore } from '@/stores/user-info';
import { t } from '@/i18n';
import { getLoginData, getPermIdsByCurrentUser, loginUser } from '@/api';

import { setPermission, setToken } from '../../utils/auth';

import type { FormInstance, Rule } from 'ant-design-vue/es/form';
import type { LoginUser } from '@/types';

const formRef = ref<FormInstance>();
const router = useRouter();
const { saveToken, savePermission } = useUserInfoStore();
const { handleRequest } = useRequest();
const loginForm = ref<LoginUser>({
  mobile: '',
  password: '',
});
const rules: Record<string, Rule[]> = {
  password: [{ required: true, message: t('common.cannotEmpty'), trigger: 'change' }],
  mobile: [
    {
      validator: (_rule: unknown, value: string) => {
        if (!isValidPhone(value)) {
          return Promise.reject(t('logView.invalidPhoneNumberFormat'));
        }
        return Promise.resolve();
      },
    },
  ],
};
// 手机号校验函数
const isValidPhone = (phone: string): boolean => {
  return /^1[3-9]\d{9}$/.test(phone);
};
const addLog = () => {
  formRef.value?.validate().then(() => {
    handleRequest(async () => {
      const { access_token } = await loginUser({
        grant_type: 'mobile_password',
        ...loginForm.value,
      });
      if (access_token) {
        saveToken(access_token);
        setToken(access_token);
        const data = await getPermIdsByCurrentUser();
        if (data.length) {
          setPermission(data);
          savePermission(data);
        }
        const { needFirstWizard } = await getLoginData();
        if (needFirstWizard) {
          router.push('/first-usage');
        } else {
          router.push('/env-monitor/index');
        }
      }
    });
  });
};

const clickReturn = () => {
  router.push('/index');
};
</script>

<template>
  <div>
    <AFlex>
      <div class="login-bgc">
        <AButton type="text" @click="clickReturn">
          <AFlex align="center"> <SvgIcon class="icon-left" name="left" /> {{ t('common.return') }} </AFlex>
        </AButton>
      </div>

      <AFlex class="login-div" align="center">
        <div>
          <div class="login-title">{{ t('logView.hvacIntelligentControlPlatform') }}</div>
          <AForm
            ref="formRef"
            :colon="false"
            layout="vertical"
            :model="loginForm"
            :rules="rules"
            :hide-required-mark="true"
          >
            <AFormItem :label="t('logView.account')" name="mobile">
              <AInput
                class="input-width"
                v-model:value="loginForm.mobile"
                :placeholder="t('logView.pleaseEnterMobileNumber')"
              >
                <template #prefix>
                  <SvgIcon name="a-accountnumber" class="icon-style" />
                </template>
              </AInput>
            </AFormItem>
            <AFormItem :label="t('userManage.password')" name="password">
              <AInputPassword
                class="input-width"
                v-model:value="loginForm.password"
                :placeholder="t('registerGateway.pleasePassword')"
              >
                <template #prefix>
                  <SvgIcon name="password" class="icon-style" />
                </template>
              </AInputPassword>
            </AFormItem>
          </AForm>
          <AButton type="primary" class="button-style" @click="addLog">{{ t('logView.login') }}</AButton>
        </div>
      </AFlex>
    </AFlex>
  </div>
</template>

<style lang="scss" scoped>
.icon-left {
  margin-right: 12px;
  font-size: 14px;
  color: #999;
}

.icon-style {
  margin-right: 10px;
  font-size: 24px;
  color: #999;
}

.button-style {
  width: 422px;
  height: 56px;
  margin-top: 32px;
  border-radius: 28px;
}

.input-width {
  width: 422px;
  height: 56px;
}

.login-title {
  margin-bottom: 80px;
  font-size: 32px;
  font-style: normal;
  font-weight: 500;
  line-height: 44px;
  color: #333;
  text-align: left;
}

.login-bgc {
  width: 710px;
  height: 100vh;
  padding-top: 32px;
  padding-left: 30px;
  zoom: 1;
  background: url('../../assets/img/login-view.png') no-repeat center 0;
  background-repeat: no-repeat;
  background-attachment: fixed;
  background-position: 0, 0;
  background-size: 710px 100vh;
}

.login-div {
  width: calc(100vw - 710px);
  height: 100vh;
  padding-left: 154px;
}
</style>
