<script lang="ts" setup>
import type { AuthApi } from '#/api/core/auth';

import { ref } from 'vue';

import { Modal } from 'ant-design-vue';

import AccountOptionList from './AccountOptionList.vue';

defineOptions({ name: 'AccountSelectModal' });

const props = defineProps<{
  accounts: AuthApi.AccountOption[];
}>();

const emit = defineEmits<{
  confirm: [account: AuthApi.AccountOption];
  cancel: [];
}>();

const visible = defineModel<boolean>('open', { default: false });

const selectedKey = ref<string | null>(null);

function accountKey(item: AuthApi.AccountOption): string {
  return `${item.account_type || 'admin'}-${item.id}-${item.store_name || ''}`;
}

function resolveInitialKey(
  accounts: AuthApi.AccountOption[],
  options: {
    initialAdminId?: number | null;
    defaultAccountId?: number | null;
    defaultAccountType?: string | null;
  } = {},
): string | null {
  if (!accounts.length) {
    return null;
  }

  const { initialAdminId, defaultAccountId, defaultAccountType } = options;

  if (initialAdminId != null) {
    const byId = accounts.find((item) => item.id === initialAdminId);
    if (byId) {
      return accountKey(byId);
    }
  }

  if (defaultAccountId != null && defaultAccountType) {
    const byDefault = accounts.find(
      (item) =>
        item.account_type === defaultAccountType &&
        item.id === defaultAccountId,
    );
    if (byDefault) {
      return accountKey(byDefault);
    }
  }

  const matched = accounts.find((item) => item.password_matched);
  if (matched) {
    return accountKey(matched);
  }

  return accountKey(accounts[0]);
}

function handleOk() {
  const account = props.accounts.find(
    (item) => accountKey(item) === selectedKey.value,
  );
  if (!account) {
    return;
  }
  emit('confirm', account);
  visible.value = false;
}

function handleCancel() {
  emit('cancel');
  visible.value = false;
}

function openWithAccounts(
  accounts: AuthApi.AccountOption[],
  options: {
    initialAdminId?: number | null;
    defaultAccountId?: number | null;
    defaultAccountType?: string | null;
  } = {},
) {
  selectedKey.value = resolveInitialKey(accounts, options);
  visible.value = true;
}

defineExpose({ openWithAccounts });
</script>

<template>
  <Modal
    v-model:open="visible"
    title="选择登录账号"
    ok-text="确认"
    cancel-text="取消"
    :mask-closable="false"
    :keyboard="false"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <AccountOptionList
      :accounts="accounts"
      :selected-key="selectedKey"
      @select="selectedKey = $event"
    />
  </Modal>
</template>
