<script setup lang="ts">
import { useRequest, useSerialRequest } from 'alova/client';
import { getApplicationMethod } from '@/request/api';
import { getAccountInfo, login } from '@/request/api/manage';
import { useAccountStore } from '@/stores';
import { useUpdatePassword } from '@/modules/system/useUpdatePassword';

const { data } = useRequest(getApplicationMethod, { initialData: { image: { copyright: '' } } });
const title = computed(() => data.value.image.title || import.meta.env.SIX_APP_TITLE);
const copyright = computed(() => data.value.copyright);

const resetPassword = ref(false);

const router = useRouter();
const Account = useAccountStore();
const model = ref({ account: '', password: '' });
const { loading, send } = useSerialRequest([(model) => login(model), (token) => getAccountInfo(token)], { immediate: false }).onSuccess(async ({ data }) => {
  const [token, user] = data;
  resetPassword.value = user?.resetPassword ?? false;
  if (resetPassword.value) {
    while (true) {
      if (!await tips()) break;
      if (await password.open({ title: `设置一个新密码`, pid: user.id, token })) {
        resetPassword.value = false;
        return;
      }
    }
  }
  Account.login(...data);
  await router.push({ name: 'screen', replace: true });
});

const tips = () => {
  model.value.password = '';
  return showConfirmDialog({ title: '您的密码为初始密码请及时修改', confirmButtonText: '修改', cancelButtonText: '忽略', cancelButtonColor: 'red' })
    .then(() => true)
    .catch(() => false);
}

const [Password, password] = useUpdatePassword();
</script>

<template>
  <div class="page-container">
    <div class="page-content flex flex-col">
      <div class="flex-none h-[106px]">
        <div style="min-height: 68px"></div>
        <div class="h-full flex justify-center items-center text-4xl" style="letter-spacing: 0.2em">{{ title }}</div>
      </div>
      <div class="flex-auto flex justify-center items-center">
        <van-form v-if="!resetPassword" ref="form" @submit="send(model)" :readonly="loading">
          <van-cell-group inset>
            <van-field v-model="model.account" type="text" name="account" label="账号" placeholder="请输入账号" :rules="[{ required: true, message: '请输入账号' }]" />
            <van-field v-model="model.password" type="password" name="password" label="密码" placeholder="请输入密码" :rules="[{ required: true, message: '请输入密码' }]" />
          </van-cell-group>
          <div style="margin: 16px">
            <van-button round block type="primary" native-type="submit" :loading> 登录 </van-button>
          </div>
        </van-form>
      </div>
      <div class="flex-none text-xl p-2 text-center tracking-widest" v-html="copyright"></div>
    </div>
    <Password />
  </div>
</template>

<style scoped lang="scss"></style>
