<script setup lang="ts">
import { onMounted, ref, useTemplateRef } from 'vue';

import ConfirmModal from '@/components/ConfirmModal.vue';
import { useRequest } from '@/hooks/request';
import { t } from '@/i18n';
import { addAccount, getFindRolesByOrgIds } from '@/api';

import AddAccount from './AddAccount.vue';

import type {
  AccountForm,
  CharacterPageItem,
  CreateCustomer,
  UseGuideStepItemExpose,
  UseGuideStepItemProps,
} from '@/types';

const addAccountRef = ref<InstanceType<typeof AddAccount>[]>([]);
const props = defineProps<UseGuideStepItemProps<CreateCustomer>>();
const characterList = ref<CharacterPageItem[]>([]);
const accountList = ref<AccountForm[]>([]);
const accountIndex = ref<number>(0);

const { handleRequest } = useRequest();
const addAccountForm = () => {
  accountList.value.push({
    userName: '',
    mobile: '',
    password: '00000000',
    enabled: true,
    roleId: undefined,
    accountTerm: undefined,
  });
};
const modalComponentRef = useTemplateRef('modalComponent');
const deleteClick = (index: number) => {
  modalComponentRef.value?.showView();
  accountIndex.value = index;
};
const confirm = () => {
  modalComponentRef.value?.hideView();
  accountList.value.splice(accountIndex.value, 1);
};

const finish = async () => {
  if (!accountList.value.length) {
    throw new Error(t('userManage.pleaseAddAccount'));
  }
  // eslint-disable-next-line no-useless-catch
  try {
    const allTasks = [...addAccountRef.value.map((c) => c.formRefSubmit())];
    await Promise.all(allTasks);

    for (const item of accountList.value) {
      const { userName, mobile, password, enabled, roleId, accountTerm } = item;

      await addAccount({
        userName,
        mobile,
        password,
        roleId: roleId as number,
        enabled: enabled ? '1' : '0',
        startTenancy: accountTerm![0].format('YYYY-MM-DD'),
        endTenancy: accountTerm![1].format('YYYY-MM-DD'),
        orgId: props.form.id as number,
      });
    }
  } catch (err) {
    throw err;
  }
};
defineExpose<UseGuideStepItemExpose>({
  finish,
});
onMounted(() => {
  handleRequest(async () => {
    if (props.form.id) {
      characterList.value = await getFindRolesByOrgIds([props.form.id]);
    }
  });
});
</script>

<template>
  <div>
    <div class="account"><span class="account-text">*</span>{{ t('createCustomer.createAccount') }}</div>
    <AFlex wrap="wrap">
      <div v-for="(item, index) in accountList" :key="index" class="account-list">
        <AddAccount
          ref="addAccountRef"
          :index="index"
          :form="item"
          :character-list="characterList"
          @deleteClick="deleteClick"
        />
      </div>
    </AFlex>

    <AButton type="primary" ghost class="icon-button button-style" @click="addAccountForm">
      <AFlex align="center">
        <SvgIcon name="plus" />
        <span> {{ t('userManage.addAccount') }} </span>
      </AFlex>
    </AButton>
    <ConfirmModal
      ref="modalComponent"
      :title="t('common.deleteConfirmation')"
      :description-text="t('common.confirmDeletion')"
      :icon="{ name: 'delete' }"
      :icon-bg-color="'#F56C6C'"
      @confirm="confirm"
    />
  </div>
</template>

<style lang="scss" scoped>
.account-list {
  margin-right: 40px;
  margin-bottom: 16px;
}

.button-style {
  margin-top: 24px;
}

.account {
  margin-bottom: 16px;
  color: rgb(0 0 0 / 85%);
}

.account-text {
  font-size: 14px;
  font-style: normal;
  font-weight: 400;
  line-height: 22px;
  color: #e02020;
  text-align: left;
}
</style>
