<script setup lang="ts">
import { ref, watch, onMounted, computed } from 'vue';
import { useI18n } from 'vue-i18n';
import { useQuasar } from 'quasar';
import { useRoute, useRouter } from 'vue-router';
import { getUserId, getRole } from 'src/services/keycloak';
import { baseUrl, waitAll } from 'src/stores/utils';
import { dateFormat } from 'src/utils/datetime';
import { dialogCheckData } from 'stores/utils';

import useOcrStore from 'stores/ocr';
import useCustomerStore from 'stores/customer';
import useEmployeeStore from 'stores/employee';
import useMyBranchStore from 'stores/my-branch';
import { dialog, notify, resetScrollBar } from 'stores/utils';
import { useNavigator } from 'src/stores/navigator';
import useFlowStore from 'stores/flow';
import { Status } from 'stores/types';
import {
  CustomerStats,
  Customer,
  CustomerBranch,
  CustomerBranchCreate,
} from 'stores/customer/types';
import { Employee, EmployeeHistory } from 'stores/employee/types';
import {
  EditButton,
  DeleteButton,
  SaveButton,
  UndoButton,
} from 'components/button';

import ExpirationDate from 'components/03_customer-management/ExpirationDate.vue';
import { AddressForm } from 'components/form';
import BranchCard from 'src/components/01_branch-management/BranchCard.vue';
import ItemCard from 'src/components/ItemCard.vue';
import DrawerInfo from 'components/DrawerInfo.vue';
import FloatingActionButton from 'components/FloatingActionButton.vue';
import StatCardComponent from 'components/StatCardComponent.vue';
import TooltipComponent from 'components/TooltipComponent.vue';
import EmptyAddButton from 'components/AddButton.vue';
import NoData from 'components/NoData.vue';
import PaginationComponent from 'components/PaginationComponent.vue';
import BasicInformation from 'components/03_customer-management/employee/BasicInformation.vue';
import FormPerson from 'components/02_personnel-management/FormPerson.vue';
import { EmployerFormBasicInfo, EmployerFormBranch } from './components';
import BranchPage from './BranchPage.vue';
import FormEmployeePassport from 'components/03_customer-management/FormEmployeePassport.vue';
import DialogForm from 'components/DialogForm.vue';
import SideMenu from 'components/SideMenu.vue';
import TableEmpoloyee from 'src/components/03_customer-management/TableEmpoloyee.vue';
import HistoryEditComponent from 'src/components/03_customer-management/HistoryEditComponent.vue';
import { calculateAge, toISOStringWithTimezone } from 'src/utils/datetime';
import { runOcr, parseResultMRZ } from 'src/utils/ocr';
import { formatAddress } from 'src/utils/address';
import {
  UploadFileGroup,
  FormTm6,
  NoticeJobEmployment,
} from 'components/upload-file';

import {
  columnsCustomer,
  columnsEmployee,
  uploadFileListEmployee,
  columnsAttachment,
  dialogCreateCustomerItem,
} from './constant';
import { useCustomerForm, useEmployeeForm } from './form';
import { storeToRefs } from 'pinia';
import ProfileBanner from 'components/ProfileBanner.vue';
import ImageUploadDialog from 'components/ImageUploadDialog.vue';
import FormEmployeeHealthCheck from 'components/03_customer-management/FormEmployeeHealthCheck.vue';
import FormEmployeeWorkHistory from 'components/03_customer-management/FormEmployeeWorkHistory.vue';
import FormEmployeeOther from 'components/03_customer-management/FormEmployeeOther.vue';
import useOptionStore from 'stores/options';
import { DialogContainer, DialogHeader } from 'components/dialog';
import KebabAction from 'src/components/shared/KebabAction.vue';
import { nextTick } from 'vue';
import FormEmployeeVisa from 'components/03_customer-management/FormEmployeeVisa.vue';
import { group } from 'node:console';
import PaginationPageSize from 'src/components/PaginationPageSize.vue';

const { t, locale } = useI18n();
const $q = useQuasar();
const route = useRoute();
const router = useRouter();
const flowStore = useFlowStore();
const navigatorStore = useNavigator();
const customerStore = useCustomerStore();
const userBranchStore = useMyBranchStore();
const employeeStore = useEmployeeStore();
const customerFormStore = useCustomerForm();
const employeeFormStore = useEmployeeForm();
const optionStore = useOptionStore();
const ocrStore = useOcrStore();

const statusEmployeeCreate = ref<boolean>(false);
const mrz = ref<Awaited<ReturnType<typeof parseResultMRZ>>>();
const tabFieldRequired = ref<{ [key: string]: (keyof CustomerBranchCreate)[] }>(
  {
    main: [],
    business: ['businessType', 'jobPosition'],
    address: [
      'address',
      'addressEN',
      'provinceId',
      'districtId',
      'subDistrictId',
    ],
    contact: [],
  },
);

const { state: customerFormState, currentFormData: customerFormData } =
  storeToRefs(customerFormStore);
const { state: employeeFormState, currentFromDataEmployee } =
  storeToRefs(employeeFormStore);

async function init() {
  navigatorStore.current.title = 'menu.customer';
  navigatorStore.current.path = [
    {
      text: 'menu.customerCaption',
      i18n: true,
      handler: () => router.push('/customer-management'),
    },
  ];

  gridView.value = $q.screen.lt.md ? true : false;

  if (route.name === 'CustomerManagement') await fetchListCustomer(true);

  if (
    route.name === 'CustomerBranchManagement' &&
    typeof route.params.customerId === 'string'
  ) {
    const _data = await customerStore.fetchById(route.params.customerId);

    if (_data) {
      currentCustomer.value = _data;
      navigatorStore.current.path.push({
        text: `${
          _data.customerType === 'CORP'
            ? _data.branch[0].registerName
            : locale.value === 'eng'
              ? _data.branch[0].firstNameEN + ' ' + _data.branch[0].lastNameEN
              : _data.branch[0].firstName + ' ' + _data.branch[0].lastName
        }`,
        i18n: false,
      });
    } else {
      router.push('/customer-management');
    }
  }
  flowStore.rotate();
}
onMounted(init);

// NOTE: Page Data
const currentCustomer = ref<Customer>();
const listCustomer = ref<(Customer & { branch: CustomerBranch[] })[]>([]);
const listEmployee = ref<Employee[]>([]);
const hideStats = ref(false);
const statsCustomerType = ref<CustomerStats>({
  CORP: 0,
  PERS: 0,
});

// NOTE: Page State
const currentTab = ref<'employer' | 'employee'>('employer');
const inputSearch = ref('');
const currentStatus = ref<Status | 'All'>('All');
const customerTypeSelected = ref<{
  label: string;
  value: 'all' | 'customerLegalEntity' | 'customerNaturalPerson';
}>({
  label: t('general.all'),
  value: 'all',
});

const customerNameInfo = computed(() => {
  if (customerFormData.value.customerBranch === undefined) return;

  const name =
    locale.value === 'eng'
      ? `${customerFormData.value.customerBranch[0]?.firstNameEN} ${customerFormData.value.customerBranch[0]?.lastNameEN}`
      : `${customerFormData.value.customerBranch[0]?.firstName} ${customerFormData.value.customerBranch[0]?.lastName}`;
  return name || '-';
});
const currentBtnOpen = ref<boolean[]>([]);
const employeeStats = ref(0);
const gridView = ref(false);
const splitPercent = ref(15); // Customer only

const currentPageCustomer = ref<number>(1);
const maxPageCustomer = ref<number>(1);
const currentPageEmployee = ref<number>(1);
const maxPageEmployee = ref<number>(1);
const pageSize = ref<number>(30);
const dialogCustomerImageUpload = ref<InstanceType<typeof ImageUploadDialog>>();
const dialogEmployeeImageUpload = ref<InstanceType<typeof ImageUploadDialog>>();

// image
const refreshImageState = ref(false);
const imageList = ref<{ selectedImage: string; list: string[] }>();
const onCreateImageList = ref<{
  selectedImage: string;
  list: { url: string; imgFile: File | null; name: string }[];
}>({ selectedImage: '', list: [] });

watch(() => route.name, init);
watch(
  [currentTab, currentStatus, inputSearch, customerTypeSelected, pageSize],
  async ([tabName]) => {
    if (tabName === 'employer') {
      currentPageCustomer.value = 1;
      currentBtnOpen.value = [];
      await fetchListCustomer(true);
    }
    if (tabName === 'employee') {
      currentPageEmployee.value = 1;
      await fetchListEmployee(true);
    }
    flowStore.rotate();
  },
);
watch(locale, () => {
  customerTypeSelected.value = {
    label: `${customerTypeSelected.value.label}`,
    value: customerTypeSelected.value?.value,
  };
});
watch(
  () => $q.screen.lt.md,
  () => $q.screen.lt.md && (gridView.value = true),
);

const fieldDisplayCustomer = ref<
  {
    label: string;
    value: string;
  }[]
>(
  columnsCustomer
    .filter((v) => v.name !== 'action')
    .map((v) => ({ label: v.label, value: v.name })),
);

const fieldDisplayEmployee = ref<
  {
    label: string;
    value: string;
  }[]
>(
  columnsEmployee
    .filter((v) => v.name !== 'action')
    .map((v) => ({ label: v.label, value: v.name })),
);

const fieldSelected = ref<string[]>(
  [
    ...columnsEmployee.map((v) => v.name),
    ...columnsCustomer.map((v) => v.name),
  ].filter((v, index, self) => self.indexOf(v) === index),
);

const registerAbleBranchOption = ref<{ id: string; name: string }[]>();

const branch = ref<CustomerBranch[]>();

const customerStats = [
  { id: 1, count: 2, name: 'CORP' },
  { id: 2, count: 3, name: 'PERS' },
];

const fieldCustomer = [
  'all',
  'customerLegalEntity',
  'customerNaturalPerson',
] as const;

const employeeHistoryDialog = ref(false);
const employeeHistory = ref<EmployeeHistory[]>();

function validateTabField<T = CustomerBranchCreate>(
  value: T,
  fieldRequired: { [key: string]: (keyof T)[] },
) {
  const list: string[] = [];

  for (const tab in fieldRequired) {
    for (const field of fieldRequired[tab]) {
      if (!value[field] && !list.includes(tab)) list.push(tab);
    }
  }

  return list;
}

function deleteCustomerById(id: string) {
  dialog({
    color: 'negative',
    icon: 'mdi-alert',
    title: t('dialog.title.confirmDelete'),
    actionText: t('general.delete'),
    persistent: true,
    message: t('dialog.message.confirmDelete'),
    action: async () => {
      await customerStore.deleteById(id);

      await fetchListCustomer(true);
      customerFormState.value.dialogModal = false;
      flowStore.rotate();
    },
    cancel: () => {},
  });
}

async function deleteCustomerBranchById(id: string) {
  return await new Promise((resolve) => {
    dialog({
      color: 'negative',
      icon: 'mdi-alert',
      title: t('dialog.title.confirmDelete'),
      actionText: t('general.delete'),
      persistent: true,
      message: t('dialog.message.confirmDelete'),
      action: async () => {
        await customerStore.deleteBranchById(id);
        flowStore.rotate();
        resolve(true);
      },
      cancel: () => {
        resolve(false);
      },
    });
  });
}
async function fetchListOfOptionBranch() {
  if (registerAbleBranchOption.value) return;

  const uid = getUserId();
  const role = getRole();

  if (!uid) return; // should not possible as the system require login to be able to access resource.

  if (role?.includes('system')) {
    const result = await userBranchStore.fetchListOptionBranch();
    if (result && result.total > 0)
      registerAbleBranchOption.value = result.result;
  } else {
    const result = await userBranchStore.fetchListMyBranch(uid);
    if (result && result.total > 0)
      registerAbleBranchOption.value = result.result;
  }

  // TODO: Assign (first) branch of the user as register branch of the data
}

async function fetchListCustomer(fetchStats = false) {
  const resultList = await customerStore.fetchList({
    includeBranch: true,
    page: currentPageCustomer.value,
    pageSize: pageSize.value,
    status:
      currentStatus.value === 'All'
        ? undefined
        : currentStatus.value === 'ACTIVE'
          ? 'ACTIVE'
          : 'INACTIVE',
    query: inputSearch.value,
    customerType: (
      {
        all: undefined,
        customerLegalEntity: 'CORP',
        customerNaturalPerson: 'PERS',
      } as const
    )[customerTypeSelected.value.value],
  });

  if (resultList) {
    currentPageCustomer.value = resultList.page;
    maxPageCustomer.value = Math.ceil(resultList.total / pageSize.value);
    listCustomer.value = resultList.result;
  }

  if (fetchStats) {
    statsCustomerType.value = await customerStore
      .getStatsCustomer()
      .then((value) => (value ? value : { CORP: 0, PERS: 0 }));
  }
}

async function fetchListEmployee(fetchStats = false) {
  const resultListEmployee = await employeeStore.fetchList({
    page: currentPageEmployee.value,
    pageSize: pageSize.value,
    status:
      currentStatus.value === 'All'
        ? undefined
        : currentStatus.value === 'ACTIVE'
          ? 'ACTIVE'
          : 'INACTIVE',
    query: inputSearch.value,
    passport: true,
    visa: true,
  });
  if (resultListEmployee) {
    maxPageEmployee.value = Math.ceil(
      resultListEmployee.total / pageSize.value,
    );
    listEmployee.value = resultListEmployee.result;
  }

  if (fetchStats) employeeStats.value = await employeeStore.getStatsEmployee();
}

async function triggerChangeStatus(id: string, status: string) {
  return await new Promise((resolve, reject) => {
    dialog({
      color: status !== 'INACTIVE' ? 'warning' : 'info',
      icon:
        status !== 'INACTIVE' ? 'mdi-alert' : 'mdi-message-processing-outline',
      title: t('dialog.title.confirmChangeStatus'),
      actionText:
        status !== 'INACTIVE' ? t('general.close') : t('general.open'),
      message:
        status !== 'INACTIVE'
          ? t('dialog.message.confirmChangeStatusOff')
          : t('dialog.message.confirmChangeStatusOn'),
      action: async () => {
        if (currentTab.value === 'employee') {
          await toggleStatusEmployee(id, status === 'INACTIVE' ? false : true)
            .then(resolve)
            .catch(reject);
        } else {
          await toggleStatusCustomer(id, status === 'INACTIVE' ? false : true)
            .then(resolve)
            .catch(reject);
        }
      },
      cancel: () => {},
    });
  });
}

async function toggleStatusEmployee(id: string, status: boolean) {
  const res = await employeeStore.editById(id, {
    status: !status ? 'ACTIVE' : 'INACTIVE',
  });
  if (res && employeeFormState.value.drawerModal)
    currentFromDataEmployee.value.status = res.status;

  await fetchListEmployee();
  flowStore.rotate();
}

async function toggleStatusCustomer(id: string, status: boolean) {
  const res = await customerStore.editById(id, {
    status: !status ? 'ACTIVE' : 'INACTIVE',
  });
  if (res && customerFormState.value.drawerModal)
    customerFormData.value.status = res.status;

  await fetchListCustomer();
  flowStore.rotate();
}

async function deleteEmployeeById(opts: {
  id?: string;
  type?: 'passport' | 'visa' | 'healthCheck' | 'work';
  index?: number;
}) {
  dialog({
    color: 'negative',
    icon: 'mdi-alert',
    title: t('dialog.title.confirmDelete'),
    actionText: t('general.delete'),
    persistent: true,
    message: t('dialog.message.confirmDelete'),
    action: async () => {
      if (opts.type === 'passport' && opts.index !== undefined) {
        await employeeFormStore.deletePassport(opts.index);
      }

      if (opts.type === 'visa' && opts.index !== undefined) {
        await employeeFormStore.deleteVisa(opts.index);
      }

      if (opts.type === 'healthCheck' && opts.index !== undefined) {
        await employeeFormStore.deleteHealthCheck(opts.index);
      }

      if (opts.type === 'work' && opts.index !== undefined) {
        await employeeFormStore.deleteWorkHistory(opts.index);
      } else {
        if (!!opts.id) {
          const result = await employeeStore.deleteById(opts.id);

          if (result) {
            employeeFormState.value.drawerModal = false;
            employeeFormState.value.dialogModal = false;
          }
        }
      }

      await fetchListEmployee(true);

      flowStore.rotate();
    },
    cancel: () => {},
  });
}

async function openHistory(id: string) {
  const res = await employeeStore.getEditHistory(id);
  employeeHistory.value = res.reverse();
  employeeHistoryDialog.value = true;
}

async function editCustomerForm(id: string) {
  await customerFormStore.assignFormData(id);
  await fetchListOfOptionBranch();
  await fetchImageList(
    id,
    customerFormData.value.selectedImage || '',
    'customer',
  );
  customerFormState.value.branchIndex = -1;
  customerFormState.value.dialogType = 'edit';
  customerFormState.value.drawerModal = true;
  customerFormState.value.editCustomerId = id;
}

async function editEmployeeFormPersonal(id: string) {
  await employeeFormStore.assignFormDataEmployee(id);
  await fetchImageList(
    id,
    currentFromDataEmployee.value.selectedImage || '',
    'employee',
  );

  employeeFormState.value.isEmployeeEdit = true;
  employeeFormState.value.dialogType = 'edit';
  employeeFormState.value.drawerModal = true;
}

function employeeConfirmUnsave(close = true) {
  dialog({
    color: 'warning',
    icon: 'mdi-alert',
    title: t('form.warning.title'),
    actionText: t('ok'),
    persistent: true,
    message: t('form.warning.unsave'),
    action: () => {
      employeeFormStore.resetFormDataEmployee();
      onCreateImageList.value = { selectedImage: '', list: [] };
      employeeFormState.value.editReadonly = true;
      employeeFormState.value.dialogModal = !close;
      employeeFormState.value.drawerModal = !close;
    },
    cancel: () => {},
  });
}

function employeeFormUndo(close = true) {
  if (employeeFormStore.isFormDataDifferent()) {
    return employeeConfirmUnsave(close);
  }
  employeeFormStore.resetFormDataEmployee();
  employeeFormState.value.editReadonly = true;
}

function customerConfirmUnsave(close = true) {
  dialog({
    color: 'warning',
    icon: 'mdi-alert',
    title: t('form.warning.title'),
    actionText: t('ok'),
    persistent: true,
    message: t('form.warning.unsave'),

    action: () => {
      customerFormStore.resetForm();
      customerFormState.value.readonly = true;

      if (!customerFormState.value.drawerModal) {
        customerFormState.value.dialogModal = !close;
      } else {
        customerFormState.value.drawerModal = !close;
      }
    },
    cancel: () => {},
  });
}

function customerFormUndo(close = true) {
  if (customerFormStore.isFormDataDifferent()) {
    return customerConfirmUnsave(close);
  }
  customerFormStore.resetForm();
  customerFormState.value.readonly = true;
}

async function createCustomerForm(customerType: 'CORP' | 'PERS') {
  customerFormState.value.dialogModal = true;
  customerFormState.value.dialogType = 'create';
  customerFormData.value.customerType = customerType;
}

function createEmployeeForm() {
  employeeFormStore.resetFormDataEmployee(true);
  employeeFormState.value.dialogType = 'create';
  employeeFormState.value.dialogModal = true;
  employeeFormState.value.isEmployeeEdit = true;
}

async function fetchImageList(
  id: string,
  selectedName: string,
  type: 'customer' | 'employee',
) {
  const res =
    type === 'customer'
      ? await customerStore.fetchImageListById(id)
      : await employeeStore.fetchImageListById(id);
  imageList.value = {
    selectedImage: selectedName,
    list: res.map((n: string) => `${type}/${id}/image/${n}`),
  };

  return res;
}

// TODO: When in employee form, if select address same as customer then auto fill

watch(
  () => employeeFormState.value.formDataEmployeeOwner,
  (e) => {
    if (!e) return;
    if (employeeFormState.value.formDataEmployeeSameAddr) {
      currentFromDataEmployee.value.address = e.address;
      currentFromDataEmployee.value.addressEN = e.addressEN;
      currentFromDataEmployee.value.provinceId = e.provinceId;
      currentFromDataEmployee.value.districtId = e.districtId;
      currentFromDataEmployee.value.subDistrictId = e.subDistrictId;
    }
    currentFromDataEmployee.value.customerBranchId = e.id;
  },
);

watch(
  () => employeeFormState.value.formDataEmployeeSameAddr,
  (isSame) => {
    if (!employeeFormState.value.formDataEmployeeOwner) return;
    if (isSame) {
      currentFromDataEmployee.value.address =
        employeeFormState.value.formDataEmployeeOwner.address;
      currentFromDataEmployee.value.addressEN =
        employeeFormState.value.formDataEmployeeOwner.addressEN;
      currentFromDataEmployee.value.provinceId =
        employeeFormState.value.formDataEmployeeOwner.provinceId;
      currentFromDataEmployee.value.districtId =
        employeeFormState.value.formDataEmployeeOwner.districtId;
      currentFromDataEmployee.value.subDistrictId =
        employeeFormState.value.formDataEmployeeOwner.subDistrictId;
    }
    currentFromDataEmployee.value.customerBranchId =
      employeeFormState.value.formDataEmployeeOwner.id;
  },
);

watch(
  () => employeeFormState.value.currentTab,
  () => {
    employeeFormState.value.isEmployeeEdit = false;
  },
);

watch(
  () => currentFromDataEmployee.value.dateOfBirth,
  (v) => {
    const isEdit =
      employeeFormState.value.drawerModal &&
      employeeFormState.value.isEmployeeEdit;
    let currentFormDate = toISOStringWithTimezone(new Date(v));
    let currentDate: string = '';

    if (isEdit) {
      currentDate = toISOStringWithTimezone(
        new Date(employeeFormState.value.currentEmployee.dateOfBirth),
      );
    }

    if (
      employeeFormState.value.dialogModal ||
      (isEdit && currentFormDate !== currentDate)
    ) {
      const age = calculateAge(
        currentFromDataEmployee.value.dateOfBirth,
        'year',
      );
      if (currentFromDataEmployee.value.dateOfBirth && Number(age) < 15) {
        dialog({
          color: 'warning',
          icon: 'mdi-alert',
          title: t('dialog.title.youngWorker'),
          cancelText: t('general.edit'),
          persistent: true,
          message: t('dialog.message.youngWorker'),

          cancel: async () => {
            currentFromDataEmployee.value.dateOfBirth = null;
            return;
          },
        });
      }
    }
  },
);

watch(
  () => customerFormData.value.image,
  () => {
    if (customerFormData.value.image !== null)
      customerFormState.value.isImageEdit = true;
  },
);

const emptyCreateDialog = ref(false);
</script>

<template>
  <FloatingActionButton
    style="z-index: 999"
    :hide-icon="currentTab === 'employee'"
    v-if="$route.name === 'CustomerManagement'"
    @click="
      () => {
        if (currentTab === 'employee') {
          createEmployeeForm();
        }
      }
    "
  >
    <q-fab-action
      v-if="currentTab === 'employer'"
      id="add-customer-legal-entity"
      style="color: white; background-color: hsla(var(--violet-11-hsl))"
      @click="createCustomerForm('CORP')"
      padding="xs"
      icon="mdi-office-building-outline"
      :label="$t('general.add') + ' ' + $t('customer.employerLegalEntity')"
      external-label
      label-position="left"
    />
    <q-fab-action
      v-if="currentTab === 'employer'"
      id="add-customer-natural-person"
      :label="$t('general.add') + ' ' + $t('customer.employerNaturalPerson')"
      external-label
      label-position="left"
      @click="createCustomerForm('PERS')"
      style="color: white; background-color: hsla(var(--teal-10-hsl))"
      padding="xs"
      icon="mdi-account-plus-outline"
    />
  </FloatingActionButton>

  <div class="column full-height no-wrap">
    <div v-if="$route.name === 'CustomerManagement'" class="column full-height">
      <div class="text-body-2 text-weight-medium q-mb-xs flex items-center">
        {{ $t('general.dataSum') }}
        <q-badge
          v-if="listCustomer"
          rounded
          class="q-ml-sm"
          style="
            background-color: hsla(var(--info-bg) / 0.15);
            color: hsl(var(--info-bg));
          "
        >
          {{
            currentTab === 'employer'
              ? listCustomer?.length
              : listEmployee.length
          }}
        </q-badge>
        <q-btn
          class="q-ml-sm"
          icon="mdi-pin-outline"
          color="primary"
          size="sm"
          flat
          dense
          rounded
          @click="hideStats = !hideStats"
          :style="hideStats ? 'rotate: 90deg' : ''"
          style="transition: 0.1s ease-in-out"
        />
      </div>

      <div class="row full-width">
        <!-- stat -->
        <transition name="slide">
          <div v-if="!hideStats" class="col-12 q-mb-md">
            <div class="scroll">
              <StatCardComponent
                v-if="customerStats"
                label-i18n
                :branch="
                  customerStats &&
                  (currentTab === 'employer'
                    ? customerStats.map((v) => ({
                        count:
                          v.name === 'CORP'
                            ? (statsCustomerType?.CORP ?? 0)
                            : (statsCustomerType?.PERS ?? 0),
                        label:
                          v.name === 'CORP'
                            ? 'customer.employerLegalEntity'
                            : 'customer.employerNaturalPerson',
                        icon:
                          v.name === 'CORP'
                            ? 'mdi-office-building-outline'
                            : 'mdi-account-outline',
                        color: v.name === 'CORP' ? 'purple' : 'green',
                      }))
                    : [
                        {
                          label: 'customer.employee',
                          count: employeeStats,
                          icon: 'mdi-account-outline',
                          color: 'pink',
                        },
                      ])
                "
                :dark="$q.dark.isActive"
              />
            </div>
          </div>
        </transition>
      </div>

      <!-- main -->
      <div
        class="surface-2 bordered rounded col column full-width"
        style="overflow: hidden"
      >
        <!-- tabs -->
        <div class="column">
          <div
            class="row q-px-md q-py-sm justify-between full-width surface-3 bordered-b"
          >
            <q-input
              for="input-search"
              outlined
              dense
              :label="$t('general.search')"
              class="col-12 col-md-3"
              :bg-color="$q.dark.isActive ? 'dark' : 'white'"
              v-model="inputSearch"
              debounce="200"
            >
              <template #prepend>
                <q-icon name="mdi-magnify" />
              </template>
            </q-input>

            <div
              class="row col-md-5 col-12"
              :class="{ 'q-pt-xs': $q.screen.lt.md }"
              style="white-space: nowrap"
            >
              <!-- :class="{ 'offset-md-5': gridView }" -->
              <q-select
                id="select-status"
                for="select-status"
                v-model="currentStatus"
                outlined
                dense
                autocomplete="off"
                option-value="value"
                option-label="label"
                class="col"
                map-options
                emit-value
                :hide-dropdown-icon="$q.screen.lt.sm"
                :options="[
                  { label: $t('general.all'), value: 'All' },
                  { label: $t('status.ACTIVE'), value: 'ACTIVE' },
                  { label: $t('status.INACTIVE'), value: 'INACTIVE' },
                ]"
              ></q-select>
              <!-- v-if="gridView === false" -->
              <q-select
                id="select-field"
                for="select-field"
                class="q-ml-sm col"
                :options="
                  currentTab === 'employer'
                    ? gridView
                      ? fieldDisplayCustomer.filter((v) => {
                          return (
                            v.value !== 'orderNumber' &&
                            v.value !== 'titleName' &&
                            v.value !== 'address' &&
                            v.value !== 'contactName'
                          );
                        })
                      : fieldDisplayCustomer
                    : fieldDisplayEmployee
                "
                :display-value="$t('general.displayField')"
                :hide-dropdown-icon="$q.screen.lt.sm"
                v-model="fieldSelected"
                :option-label="(l) => $t(l.label)"
                option-value="value"
                autocomplete="off"
                map-options
                emit-value
                outlined
                multiple
                dense
              />

              <q-btn-toggle
                id="btn-mode"
                v-model="gridView"
                dense
                class="no-shadow bordered rounded surface-1 q-ml-sm"
                :toggle-color="$q.dark.isActive ? 'grey-9' : 'grey-2'"
                size="xs"
                :options="[
                  { value: true, slot: 'folder' },
                  { value: false, slot: 'list' },
                ]"
              >
                <template v-slot:folder>
                  <q-icon
                    id="icon-mode-grid"
                    name="mdi-view-grid-outline"
                    size="16px"
                    class="q-px-sm q-py-xs rounded"
                    :style="{
                      color: $q.dark.isActive
                        ? gridView
                          ? '#C9D3DB '
                          : '#787B7C'
                        : gridView
                          ? '#787B7C'
                          : '#C9D3DB',
                    }"
                  />
                </template>
                <template v-slot:list>
                  <q-icon
                    id="icon-mode-list"
                    name="mdi-format-list-bulleted"
                    class="q-px-sm q-py-xs rounded"
                    size="16px"
                    :style="{
                      color: $q.dark.isActive
                        ? gridView === false
                          ? '#C9D3DB'
                          : '#787B7C'
                        : gridView === false
                          ? '#787B7C'
                          : '#C9D3DB',
                    }"
                  />
                </template>
              </q-btn-toggle>
            </div>
          </div>

          <div class="surface-2 bordered-b q-px-md">
            <q-tabs
              dense
              v-model="currentTab"
              align="left"
              class="full-height"
              active-color="info"
            >
              <q-tab
                name="employer"
                class="text-capitalize"
                id="tab-employer"
                @click="
                  () => {
                    currentPageCustomer = 1;
                    inputSearch = '';
                    currentStatus = 'All';
                    flowStore.rotate();
                  }
                "
              >
                <div
                  class="row"
                  :class="
                    currentTab === 'employer' ? 'text-bold' : 'app-text-muted'
                  "
                >
                  {{ $t('customer.employer') }}
                </div>
              </q-tab>
              <q-tab
                name="employee"
                id="tab-employee"
                class="text-capitalize"
                @click="
                  () => {
                    currentPageEmployee = 1;
                    inputSearch = '';
                    currentStatus = 'All';
                    flowStore.rotate();
                  }
                "
              >
                <div
                  class="row"
                  :class="
                    currentTab === 'employee' ? 'text-bold' : 'app-text-muted'
                  "
                >
                  {{ $t('customer.employee') }}
                </div>
              </q-tab>
            </q-tabs>
          </div>
        </div>

        <!-- body -->

        <q-splitter
          v-model="splitPercent"
          :limits="[0, 100]"
          class="col full-width"
          before-class="overflow-hidden"
          after-class="overflow-hidden"
        >
          <template v-slot:before>
            <div
              class="column q-pa-md surface-1 full-height full-width"
              style="gap: var(--size-1)"
            >
              <template v-if="currentTab === 'employer'">
                <q-item
                  v-close-popup
                  clickable
                  v-for="v in fieldCustomer"
                  :key="v"
                  dense
                  class="no-padding items-center rounded full-width"
                  active-class="employer-active"
                  :active="customerTypeSelected.value === v"
                  @click="customerTypeSelected = { label: v, value: v }"
                  :id="`btn-${v}`"
                >
                  <span class="q-px-md ellipsis">
                    {{
                      $t(
                        {
                          all: 'general.all',
                          customerLegalEntity: 'customer.employerLegalEntity',
                          customerNaturalPerson:
                            'customer.employerNaturalPerson',
                        }[v],
                      )
                    }}
                  </span>
                </q-item>
              </template>
              <template v-else>
                <q-item
                  active
                  dense
                  active-class="employer-active"
                  class="no-padding items-center rounded full-width"
                  v-close-popup
                  clickable
                >
                  <span class="q-px-md ellipsis">
                    {{ $t('general.all') }}
                  </span>
                </q-item>
              </template>
            </div>
          </template>

          <template v-slot:after>
            <div class="column full-height no-wrap">
              <!-- employer -->
              <template
                v-if="
                  listCustomer &&
                  statsCustomerType.PERS + statsCustomerType.CORP > 0 &&
                  currentTab === 'employer'
                "
              >
                <div
                  v-if="listCustomer.length === 0"
                  class="row col full-width items-center justify-center"
                  style="min-height: 250px"
                >
                  <NoData :not-found="!!inputSearch" />
                </div>

                <div
                  v-if="listCustomer.length !== 0"
                  class="col q-pa-md scroll full-width"
                >
                  <q-table
                    flat
                    bordered
                    :grid="gridView"
                    :rows="listCustomer"
                    :columns="columnsCustomer"
                    class="full-width"
                    card-container-class="q-col-gutter-md"
                    row-key="name"
                    :rows-per-page-options="[0]"
                    hide-pagination
                    :visible-columns="fieldSelected"
                  >
                    <template v-slot:header="props">
                      <q-tr
                        style="background-color: hsla(var(--info-bg) / 0.07)"
                        :props="props"
                      >
                        <q-th
                          v-for="col in props.cols"
                          :key="col.name"
                          :props="props"
                        >
                          {{ $t(col.label) }}
                        </q-th>
                        <q-th auto-width />
                      </q-tr>
                    </template>

                    <template v-slot:body="props">
                      <q-tr
                        :class="{
                          'app-text-muted': props.row.status === 'INACTIVE',
                          'status-active': props.row.status !== 'INACTIVE',
                          'status-inactive': props.row.status === 'INACTIVE',
                        }"
                        :id="`row-table-${props.row.customerName}`"
                        :props="props"
                        @click="
                          $router.push(
                            `/customer-management/${props.row.id}/branch`,
                          )
                        "
                        :style="
                          props.rowIndex % 2 !== 0
                            ? $q.dark.isActive
                              ? 'background: hsl(var(--gray-11-hsl)/0.2)'
                              : `background: #f9fafc`
                            : ''
                        "
                      >
                        <q-td
                          class="text-center"
                          v-if="fieldSelected.includes('orderNumber')"
                        >
                          {{
                            (currentPageCustomer - 1) * pageSize +
                            props.rowIndex +
                            1
                          }}
                        </q-td>

                        <q-td
                          v-if="fieldSelected.includes('titleName')"
                          class="ellipsis"
                        >
                          <div class="row items-center no-wrap">
                            <div
                              class="q-mr-sm"
                              style="
                                display: flex;
                                margin-bottom: var(--size-2);
                              "
                            >
                              <div
                                :style="`
                                  border-radius: 50%;
                                  border-style: solid;
                                  border-width: 2px;
                                  border-color: hsl(var(${props.row.customerType === 'CORP' ? '--violet-11-hsl' : '--teal-10-hsl'}));
                                `"
                              >
                                <div class="branch-card__icon">
                                  <q-avatar size="md">
                                    <q-img
                                      :src="`${baseUrl}/customer/${props.row.id}/image/${props.row.selectedImage}`"
                                      class="full-height full-width"
                                    >
                                      <template #error>
                                        <q-img
                                          :src="`/images/customer-${props.row.customerType}-avartar-${props.row.customerType === 'PERS' ? props.row.branch[0].gender : 'male'}.png`"
                                        />
                                      </template>
                                    </q-img>
                                  </q-avatar>
                                </div>
                              </div>
                            </div>
                            <div class="col">
                              <div class="col">
                                {{
                                  props.row.customerType === 'CORP'
                                    ? props.row.branch[0]?.registerName || '-'
                                    : optionStore.mapOption(
                                        props.row.branch[0].namePrefix,
                                      ) +
                                        ' ' +
                                        props.row.branch[0]?.firstName +
                                        ' ' +
                                        props.row.branch[0]?.lastName || '-'
                                }}
                              </div>
                              <div class="col app-text-muted">
                                {{
                                  props.row.customerType === 'CORP'
                                    ? props.row.branch[0]?.registerNameEN || '-'
                                    : props.row.branch[0]?.firstNameEN +
                                        ' ' +
                                        props.row.branch[0]?.lastNameEN || '-'
                                }}
                              </div>
                            </div>
                          </div>
                        </q-td>

                        <q-td
                          v-if="fieldSelected.includes('businessTypePure')"
                          style="max-width: 150px"
                          class="ellipsis"
                        >
                          {{
                            props.row.branch.length !== 0
                              ? props.row.branch[0].businessType !== null
                                ? optionStore.mapOption(
                                    props.row.branch[0].businessType,
                                  )
                                : ''
                              : '-'
                          }}

                          <q-tooltip>
                            {{
                              props.row.branch.length !== 0
                                ? props.row.branch[0].businessType !== null
                                  ? optionStore.mapOption(
                                      props.row.branch[0].businessType,
                                    )
                                  : ''
                                : '-'
                            }}
                          </q-tooltip>
                        </q-td>

                        <q-td
                          v-if="fieldSelected.includes('jobPosition')"
                          style="max-width: 150px"
                          class="ellipsis"
                        >
                          {{
                            props.row.branch.length !== 0
                              ? props.row.branch[0].jobPosition !== null
                                ? optionStore.mapOption(
                                    props.row.branch[0].jobPosition,
                                  )
                                : ''
                              : '-'
                          }}

                          <q-tooltip>
                            {{
                              props.row.branch.length !== 0
                                ? props.row.branch[0].jobPosition !== null
                                  ? optionStore.mapOption(
                                      props.row.branch[0].jobPosition,
                                    )
                                  : ''
                                : '-'
                            }}
                          </q-tooltip>
                        </q-td>

                        <q-td v-if="fieldSelected.includes('address')">
                          {{
                            formatAddress({
                              address: props.row.branch[0].address,
                              addressEN: props.row.branch[0].addressEN,
                              moo: props.row.branch[0].moo,
                              mooEN: props.row.branch[0].mooEN,
                              soi: props.row.branch[0].soi,
                              soiEN: props.row.branch[0].soiEN,
                              street: props.row.branch[0].street,
                              streetEN: props.row.branch[0].streetEN,
                              province: props.row.branch[0].province,
                              district: props.row.branch[0].district,
                              subDistrict: props.row.branch[0].subDistrict,
                              en: $i18n.locale === 'eng',
                            })
                          }}
                          <q-tooltip>
                            {{
                              formatAddress({
                                address: props.row.branch[0].address,
                                addressEN: props.row.branch[0].addressEN,
                                moo: props.row.branch[0].moo,
                                mooEN: props.row.branch[0].mooEN,
                                soi: props.row.branch[0].soi,
                                soiEN: props.row.branch[0].soiEN,
                                street: props.row.branch[0].street,
                                streetEN: props.row.branch[0].streetEN,
                                province: props.row.branch[0].province,
                                district: props.row.branch[0].district,
                                subDistrict: props.row.branch[0].subDistrict,
                                en: $i18n.locale === 'eng',
                              })
                            }}
                          </q-tooltip>
                        </q-td>

                        <q-td v-if="fieldSelected.includes('contactName')">
                          {{ props.row.branch[0]?.contactName || '-' }}
                        </q-td>

                        <q-td v-if="fieldSelected.includes('officeTel')">
                          {{ props.row.branch[0]?.officeTel || '-' }}
                        </q-td>

                        <q-td>
                          <q-btn
                            :id="`btn-eye-${props.row.branch[0].customerName || props.row.branch[0].firstName}`"
                            dense
                            flat
                            @click.stop="
                              async () => {
                                const res = await employeeStore.fetchList({
                                  customerId: props.row.id,
                                  pageSize: 999,
                                  passport: true,
                                  visa: true,
                                });

                                if (res) {
                                  listEmployee = res.result;

                                  currentBtnOpen.map((v, i) => {
                                    if (i !== props.rowIndex) {
                                      currentBtnOpen[i] = false;
                                    }
                                  });

                                  currentBtnOpen[props.rowIndex] =
                                    !currentBtnOpen[props.rowIndex];
                                }
                              }
                            "
                          >
                            <div class="row items-center">
                              <q-icon name="mdi-account-group-outline" />
                              <q-icon
                                class="btn-arrow-right"
                                :class="{
                                  active: currentBtnOpen[props.rowIndex],
                                }"
                                size="xs"
                                name="mdi-chevron-right"
                              />
                            </div>
                          </q-btn>
                          <q-btn
                            icon="mdi-eye-outline"
                            :id="`btn-eye-${props.row.branch[0].customerName || props.row.branch[0].firstName}`"
                            size="sm"
                            dense
                            round
                            flat
                            @click.stop="editCustomerForm(props.row.id)"
                          />

                          <KebabAction
                            :id-name="
                              props.row.branch[0].customerName ||
                              props.row.branch[0].firstName
                            "
                            :status="props.row.status"
                            @view="
                              () => {
                                const { branch, ...payload } = props.row;
                                currentCustomer = payload;
                                editCustomerForm(props.row.id);
                              }
                            "
                            @edit="
                              async () => {
                                await editCustomerForm(props.row.id);
                                customerFormState.branchIndex = 0;
                              }
                            "
                            @delete="deleteCustomerById(props.row.id)"
                            @change-status="
                              async () => {
                                triggerChangeStatus(
                                  props.row.id,
                                  props.row.status,
                                );
                              }
                            "
                          />
                        </q-td>
                      </q-tr>

                      <q-tr
                        v-show="currentBtnOpen[props.rowIndex]"
                        :props="props"
                      >
                        <q-td colspan="100%" style="padding: 16px">
                          <div class="text-center">
                            <TableEmpoloyee
                              in-table
                              :list-employee="listEmployee"
                              :columns-employee="columnsEmployee"
                              @history="
                                (item: any) => {
                                  openHistory(item.id);
                                }
                              "
                              @view="
                                async (item: any) => {
                                  employeeFormState.drawerModal = true;
                                  employeeFormState.isEmployeeEdit = false;
                                  employeeFormStore.assignFormDataEmployee(
                                    item.id,
                                  );
                                  await fetchImageList(
                                    item.id,
                                    item.selectedImage || '',
                                    'employee',
                                  );
                                }
                              "
                              @edit="
                                (item: any) => editEmployeeFormPersonal(item.id)
                              "
                              @delete="
                                (item: any) => {
                                  deleteEmployeeById({ id: item.id });
                                }
                              "
                              @toggle-status="
                                async (item: any) => {
                                  triggerChangeStatus(item.id, item.status);
                                }
                              "
                            />
                          </div>
                        </q-td>
                      </q-tr>
                    </template>

                    <template v-slot:item="props">
                      <div class="col-12 col-md-6 column">
                        <BranchCard
                          i18n-key="customer.table"
                          class="surface-1 col"
                          :virtual-branch="props.row.virtual"
                          :id="`branch-card-${props.row.name}`"
                          :class="{
                            'cursor-pointer': props.row._count.branch !== 0,
                          }"
                          @click="
                            $router.push(
                              `/customer-management/${props.row.id}/branch`,
                            )
                          "
                          :metadata="props.row"
                          :color="
                            props.row.customerType === 'CORP'
                              ? 'hq'
                              : 'br-virtual'
                          "
                          :key="props.row.id"
                          :data="{
                            branchLabelName:
                              props.row.customerType === 'CORP'
                                ? $i18n.locale === 'eng'
                                  ? props.row.branch[0]?.registerNameEN || '-'
                                  : props.row.branch[0]?.registerName || '-'
                                : $i18n.locale === 'eng'
                                  ? props.row.branch[0]?.firstNameEN +
                                      ' ' +
                                      props.row.branch[0]?.lastNameEN || '-'
                                  : props.row.branch[0]?.firstName +
                                      ' ' +
                                      props.row.branch[0]?.lastName || '-',
                          }"
                          :inactive="props.row.status === 'INACTIVE'"
                          :field-selected="
                            fieldSelected.filter((v) => {
                              return columnsCustomer.some((c) => c.name === v);
                            })
                          "
                        >
                          <template #image>
                            <q-avatar size="3rem">
                              <q-img
                                :src="`${baseUrl}/customer/${props.row.id}/image/${props.row.selectedImage}`"
                                class="full-height full-width"
                              >
                                <template #error>
                                  <q-img
                                    :src="`/images/customer-${props.row.customerType}-avartar-${props.row.customerType === 'PERS' ? props.row.branch[0].gender : 'male'}.png`"
                                  />
                                </template>
                              </q-img>
                              <q-badge
                                class="absolute-bottom-right no-padding"
                                style="
                                  border-radius: 50%;
                                  min-width: 10px;
                                  min-height: 10px;
                                "
                                :style="{
                                  background: `var(--${props.row.status === 'INACTIVE' ? 'stone-5' : 'green-6'})`,
                                }"
                              ></q-badge>
                            </q-avatar>
                          </template>
                          <template #data>
                            <div
                              class="row"
                              style="
                                display: flex;
                                padding-block: var(--size-2);
                              "
                            >
                              <div class="col-12 q-py-sm row">
                                <span class="col-4 app-text-muted">
                                  {{
                                    props.row.customerType === 'CORP'
                                      ? $t('customer.form.legalPersonCode')
                                      : $t('customer.form.cardNumber')
                                  }}
                                </span>
                                <span class="col">
                                  {{
                                    props.row.customerType === 'CORP'
                                      ? props.row.branch[0]?.legalPersonNo
                                      : props.row.branch[0]?.citizenId
                                  }}
                                </span>
                              </div>
                              <div
                                class="col-12 q-py-sm row"
                                v-for="key in fieldSelected
                                  .filter((v) => {
                                    return columnsCustomer.some(
                                      (c) => c.name === v,
                                    );
                                  })
                                  .filter((v) => {
                                    return (
                                      v !== 'orderNumber' &&
                                      v !== 'titleName' &&
                                      v !== 'address' &&
                                      v !== 'contactName'
                                    );
                                  })"
                                :key="key"
                              >
                                <span class="col-4 app-text-muted">
                                  {{ $t(`customer.table.${key}`) }}
                                </span>
                                <span class="col">
                                  {{
                                    key === 'businessTypePure'
                                      ? optionStore.mapOption(
                                          props.row.branch[0].businessType,
                                        )
                                      : key === 'jobPosition'
                                        ? optionStore.mapOption(
                                            props.row.branch[0].jobPosition,
                                          )
                                        : key === 'officeTel'
                                          ? props.row.branch[0].officeTel || '-'
                                          : ''
                                  }}
                                </span>
                              </div>
                            </div>
                          </template>
                          <template v-slot:action>
                            <KebabAction
                              :status="props.row.status"
                              :id-name="props.row.name"
                              @view="
                                () => {
                                  const { branch, ...payload } = props.row;
                                  currentCustomer = payload;
                                  editCustomerForm(props.row.id);
                                }
                              "
                              @edit="
                                async () => {
                                  await editCustomerForm(props.row.id);
                                  customerFormState.branchIndex = 0;
                                }
                              "
                              @delete="deleteCustomerById(props.row.id)"
                              @change-status="
                                triggerChangeStatus(
                                  props.row.id,
                                  props.row.status,
                                )
                              "
                            />
                          </template>
                        </BranchCard>
                      </div>
                    </template>
                  </q-table>
                </div>

                <div
                  v-if="listCustomer.length !== 0"
                  class="row justify-between items-center q-px-md q-py-sm"
                >
                  <div class="row col-4 items-center">
                    <div
                      class="app-text-muted"
                      style="width: 80px"
                      v-if="$q.screen.gt.sm"
                    >
                      {{ $t('general.recordPerPage') }}
                    </div>

                    <div><PaginationPageSize v-model="pageSize" /></div>
                  </div>

                  <div class="col-4 flex justify-center app-text-muted">
                    {{
                      $t('general.recordsPage', {
                        resultcurrentPage: listCustomer.length,
                        total: statsCustomerType.PERS + statsCustomerType.CORP,
                      })
                    }}
                  </div>

                  <div class="col-4 flex justify-end">
                    <PaginationComponent
                      v-model:current-page="currentPageCustomer"
                      v-model:max-page="maxPageCustomer"
                      :fetch-data="
                        async () => {
                          await fetchListCustomer();
                          flowStore.rotate();
                        }
                      "
                    />
                  </div>
                </div>
              </template>

              <!-- employee -->
              <template
                v-if="
                  listEmployee && employeeStats > 0 && currentTab === 'employee'
                "
              >
                <div
                  v-if="listEmployee.length === 0"
                  class="row col full-width items-center justify-center"
                  style="min-height: 250px"
                >
                  <NoData :not-found="!!inputSearch" />
                </div>

                <div
                  v-if="listEmployee.length !== 0"
                  class="surface-2 q-pa-md scroll col full-width"
                >
                  <TableEmpoloyee
                    v-model:page-size="pageSize"
                    v-model:current-page="currentPageEmployee"
                    :grid-view="gridView"
                    :list-employee="listEmployee"
                    :columns-employee="columnsEmployee"
                    :field-selected="fieldSelected"
                    @history="
                      (item: any) => {
                        openHistory(item.id);
                      }
                    "
                    @view="
                      async (item: any) => {
                        employeeFormState.drawerModal = true;
                        employeeFormState.isEmployeeEdit = false;
                        employeeFormStore.assignFormDataEmployee(item.id);
                        await fetchImageList(
                          item.id,
                          item.selectedImage || '',
                          'employee',
                        );
                      }
                    "
                    @edit="(item: any) => editEmployeeFormPersonal(item.id)"
                    @delete="
                      (item: any) => {
                        deleteEmployeeById({ id: item.id });
                      }
                    "
                    @toggle-status="
                      async (item: any) => {
                        triggerChangeStatus(item.id, item.status);
                      }
                    "
                  />
                </div>
                <div
                  v-if="listEmployee.length !== 0"
                  class="row justify-between items-center q-px-md q-py-sm"
                >
                  <div class="row col-4 items-center">
                    <div
                      class="app-text-muted"
                      style="width: 80px"
                      v-if="$q.screen.gt.sm"
                    >
                      {{ $t('general.recordPerPage') }}
                    </div>

                    <div><PaginationPageSize v-model="pageSize" /></div>
                  </div>

                  <div class="col-4 flex justify-center app-text-muted">
                    {{
                      $t('general.recordsPage', {
                        resultcurrentPage: listEmployee.length,
                        total: employeeStats,
                      })
                    }}
                  </div>

                  <div class="col-4 flex justify-end">
                    <PaginationComponent
                      v-model:current-page="currentPageEmployee"
                      v-model:max-page="maxPageEmployee"
                      :fetch-data="
                        async () => {
                          await fetchListEmployee();
                          flowStore.rotate();
                        }
                      "
                    />
                  </div>
                </div>
              </template>

              <template
                v-if="
                  (statsCustomerType.CORP + statsCustomerType.PERS === 0 &&
                    currentTab === 'employer') ||
                  (employeeStats === 0 && currentTab === 'employee')
                "
              >
                <TooltipComponent
                  class="self-end q-ma-md"
                  :title="'general.noData'"
                  :caption="'general.clickToCreate'"
                  imgSrc="personnel-table-"
                />

                <div
                  class="row items-center justify-center"
                  style="flex-grow: 1"
                >
                  <EmptyAddButton
                    :label="'general.add'"
                    :i18n-args="{
                      text: $t(`customer.${currentTab}`),
                    }"
                    @trigger="
                      () => {
                        if (currentTab === 'employer') {
                          emptyCreateDialog = true;
                        } else {
                          createEmployeeForm();
                        }
                      }
                    "
                  />
                </div>
              </template>
            </div>
          </template>
        </q-splitter>
      </div>
    </div>

    <div
      class="col column rounded bordered"
      style="overflow: hidden"
      v-if="$route.name === 'CustomerBranchManagement'"
    >
      <BranchPage
        v-model:status-employee-create="statusEmployeeCreate"
        v-if="currentCustomer"
        :customer-type="currentCustomer.customerType"
        :current-customer-name="
          currentCustomer.customerType === 'PERS'
            ? locale === 'eng'
              ? `${currentCustomer.branch[0]?.firstNameEN} ${currentCustomer.branch[0]?.lastNameEN}`
              : `${currentCustomer.branch[0]?.firstName} ${currentCustomer.branch[0]?.lastName}`
            : locale === 'eng'
              ? currentCustomer.branch[0]?.registerNameEN
              : currentCustomer.branch[0]?.registerName
        "
        :count-employee="currentCustomer._count.employee"
        :selected-image="currentCustomer.selectedImage"
        :gender="currentCustomer.branch[0]?.gender"
        v-model:customer-id="currentCustomer.id"
        v-model:mode-view="gridView"
        @back="$router.push('/customer-management')"
        @add-employee="
          async (currentBranch) => {
            createEmployeeForm();
            await nextTick();
            employeeFormState.formDataEmployeeOwner = { ...currentBranch };
          }
        "
        v-model:branch="branch"
        v-model:current-customer-url-image="currentCustomer.imageUrl"
      />
    </div>
  </div>

  <!-- add customer -->
  <DialogForm
    v-model:modal="emptyCreateDialog"
    :title="$t('customer.employerType')"
    hide-footer
    no-app-box
    width="40vw"
    height="250px"
    :close="
      () => {
        emptyCreateDialog = false;
        onCreateImageList = { selectedImage: '', list: [] };
      }
    "
  >
    <div class="full-height row q-pa-md">
      <ItemCard
        class="col q-mx-sm full-height"
        v-for="value in dialogCreateCustomerItem"
        :key="value.text"
        :icon="value.icon"
        :text="value.text"
        :icon-color="value.iconColor"
        :bg-color="value.color"
        @trigger="
          () => {
            createCustomerForm(
              value.text === 'customer.employerLegalEntity' ? 'CORP' : 'PERS',
            );
            emptyCreateDialog = false;
          }
        "
      />
    </div>
  </DialogForm>

  <DialogContainer
    :model-value="customerFormState.dialogModal"
    :on-open="
      async () => {
        customerFormStore.resetForm(customerFormState.dialogType === 'create');
        onCreateImageList = { selectedImage: '', list: [] };
        customerFormState.customerImageUrl = '';
        await fetchListOfOptionBranch();
        await customerFormStore.addCurrentCustomerBranch();
      }
    "
    :on-close="
      () => {
        customerFormState.dialogModal = false;
        onCreateImageList = { selectedImage: '', list: [] };
      }
    "
  >
    <template #header>
      <DialogHeader
        :title="
          customerFormState.dialogType === 'create'
            ? $t(`general.add`, {
                text: `${$t('customer.employer')} `,
              })
            : `${$t('customer.employer')} `
        "
      >
        <template #title-after>
          <span
            :style="`color: hsla(var(--${customerFormData.customerType === 'PERS' ? 'teal-10-hsl' : 'violet-11-hsl'})/1)`"
          >
            :
            {{
              customerFormData.customerType === 'CORP'
                ? $t('customer.employerLegalEntity')
                : $t('customer.employerNaturalPerson')
            }}
          </span>
        </template>
      </DialogHeader>
    </template>

    <div
      :class="{
        'q-mx-lg q-my-md': $q.screen.gt.sm,
        'q-mx-md q-my-sm': !$q.screen.gt.sm,
      }"
    >
      <ProfileBanner
        v-if="customerFormData.customerBranch !== undefined"
        active
        hide-fade
        prefix="dialog"
        :fallback-cover="`/images/customer-${customerFormData.customerType}-banner-bg.jpg`"
        :img="
          customerFormState.customerImageUrl ||
          `/images/customer-${customerFormData.customerType}-avartar-${customerFormData.customerType === 'PERS' ? customerFormData.customerBranch[0]?.gender : 'male'}.png`
        "
        :fallbackImg="`/images/customer-${customerFormData.customerType}-avartar-${customerFormData.customerType === 'PERS' ? customerFormData.customerBranch[0]?.gender : 'male'}.png`"
        :color="`hsla(var(--${customerFormData.customerType === 'PERS' ? 'teal-10-hsl' : 'violet-11-hsl'})/1)`"
        :bg-color="`hsla(var(--${customerFormData.customerType === 'PERS' ? 'teal-10-hsl' : 'violet-11-hsl'})/0.1)`"
        :icon="
          customerFormData.customerType === 'PERS'
            ? 'mdi-account-plus-outline'
            : 'mdi-office-building-outline'
        "
        :title="
          customerFormData.customerType === 'PERS'
            ? `${customerFormData.customerBranch[0]?.firstName} ${customerFormData.customerBranch[0]?.lastName}`
            : customerFormData.customerBranch[0]?.registerName
        "
        :caption="
          customerFormData.customerType === 'PERS'
            ? `${customerFormData.customerBranch[0]?.firstNameEN} ${customerFormData.customerBranch[0]?.lastNameEN}`
            : customerFormData.customerBranch[0]?.registerNameEN
        "
        @view="
          () => {
            customerFormState.imageDialog = true;
            customerFormState.isImageEdit = false;
          }
        "
        @edit="
          customerFormState.imageDialog = customerFormState.isImageEdit = true
        "
      />
    </div>
    <div
      style="flex: 1; width: 100%; overflow-y: auto"
      id="customer-form"
      :class="{
        'q-px-lg q-pb-lg': $q.screen.gt.sm,
        'q-px-md q-pb-sm': !$q.screen.gt.sm,
      }"
    >
      <div class="col surface-1 full-height rounded bordered scroll row">
        <div
          class="col"
          style="height: 100%; max-height: 100; overflow-y: auto"
          v-if="$q.screen.gt.sm"
        >
          <div class="q-py-md q-pl-md q-pr-sm">
            <SideMenu
              :menu="[
                {
                  name: $t('form.field.basicInformation'),
                  anchor: 'form-basic-info-customer',
                },
                {
                  name: $t('customer.form.group.branch'),
                  anchor: 'form-branch-customer-branch',
                  useBtn: true,
                },
                ...(customerFormData.customerBranch?.map((v, i) => ({
                  name:
                    i === 0
                      ? $t('customer.form.headQuarters.title')
                      : $t('customer.form.branch.title', {
                          name: i,
                        }),
                  anchor: `form-branch-customer-no-${i}`,
                  sub: true,
                })) || []),
              ]"
              background="transparent"
              :active="{
                background: 'hsla(var(--blue-6-hsl) / .2)',
                foreground: 'var(--blue-6)',
              }"
              scroll-element="#customer-form-content"
            >
              <template v-slot:btn-form-branch-customer-branch>
                <q-btn
                  dense
                  flat
                  icon="mdi-plus"
                  size="sm"
                  rounded
                  padding="0px 0px"
                  style="color: var(--stone-9)"
                  @click.stop="customerFormStore.addCurrentCustomerBranch()"
                  v-if="
                    customerFormState.branchIndex === -1 &&
                    !!customerFormState.editCustomerId &&
                    customerFormState.dialogType !== 'create'
                  "
                  :disabled="!customerFormState.readonly"
                />
              </template>
            </SideMenu>
          </div>
        </div>
        <div
          class="col-12 col-md-10"
          :class="{
            'q-py-md q-pr-md ': $q.screen.gt.sm,
            'q-py-md q-px-lg': !$q.screen.gt.sm,
          }"
          id="customer-form-content"
          style="height: 100%; max-height: 100%; overflow-y: auto"
        >
          <EmployerFormBasicInfo
            prefixId="form"
            v-if="
              customerFormData.customerBranch !== undefined &&
              customerFormData.customerBranch.length > 0
            "
            class="q-mb-xl"
            :readonly="
              (customerFormState.dialogType === 'edit' &&
                customerFormState.readonly === true) ||
              customerFormState.dialogType === 'info'
            "
            :action-disabled="customerFormState.branchIndex !== -1"
            id="form-basic-info-customer"
            :onCreate="customerFormState.dialogType === 'create'"
            @edit="
              (customerFormState.dialogType = 'edit'),
                (customerFormState.readonly = false)
            "
            @cancel="() => customerFormUndo(false)"
            @delete="
              customerFormState.editCustomerId &&
                deleteCustomerById(customerFormState.editCustomerId)
            "
            :customer-type="customerFormData.customerType"
            v-model:registered-branch-id="customerFormData.registeredBranchId"
            v-model:customer-name="customerNameInfo"
            v-model:register-name="
              customerFormData.customerBranch[0].registerName
            "
            v-model:citizen-id="customerFormData.customerBranch[0].citizenId"
            v-model:legal-person-no="
              customerFormData.customerBranch[0].legalPersonNo
            "
            v-model:business-type="
              customerFormData.customerBranch[0].businessType
            "
            v-model:job-position="
              customerFormData.customerBranch[0].jobPosition
            "
            v-model:telephone-no="
              customerFormData.customerBranch[0].telephoneNo
            "
            v-model:branch-options="registerAbleBranchOption"
          />
          <div class="row q-col-gutter-sm" id="form-branch-customer-branch">
            <div class="col-12 text-weight-bold text-body1 row items-center">
              <q-icon
                flat
                size="xs"
                class="q-pa-sm rounded q-mr-xs"
                color="info"
                name="mdi-briefcase-outline"
                style="background-color: var(--surface-3)"
              />
              <span>{{ $t('customer.form.group.branch') }}</span>
            </div>

            <template
              v-for="(_, idx) in customerFormData.customerBranch"
              :key="idx"
            >
              <!-- v-if="customerFormData.customerBranch" -->
              <q-form
                class="full-width"
                greedy
                @submit.prevent="
                  async () => {
                    if (!customerFormData.customerBranch) return;

                    if (customerFormData.customerType === 'PERS') {
                      tabFieldRequired.main = [
                        'citizenId',
                        'namePrefix',
                        'firstName',
                        'firstNameEN',
                        'lastName',
                        'lastNameEN',
                        'gender',
                        'birthDate',
                      ];
                    }
                    if (customerFormData.customerType === 'CORP') {
                      tabFieldRequired.main = ['legalPersonNo', 'registerName'];
                    }
                    let tapIsUndefined = validateTabField(
                      customerFormData.customerBranch?.[idx],
                      tabFieldRequired,
                    );

                    if (tapIsUndefined.length > 0) {
                      return dialog({
                        color: 'warning',
                        icon: 'mdi-alert',
                        title: t('dialog.title.incompleteDataEntry'),
                        actionText: t('ok'),
                        persistent: true,
                        message: t('dialog.message.incompleteDataEntry', {
                          tap: `${tapIsUndefined.map((v: string) => t(`customerBranch.tab.${v}`)).join(', ')}`,
                        }),
                        action: async () => {
                          return;
                        },
                      });
                    }
                    if (!customerFormData.customerBranch[idx].id) {
                      let res;
                      if (idx === 0) {
                        res =
                          await customerFormStore.submitFormCustomer(
                            onCreateImageList,
                          );
                      } else {
                        res = await customerStore.createBranch({
                          ...customerFormData.customerBranch[idx],
                          customerId: customerFormState.editCustomerId || '',
                          id: undefined,
                        });
                      }
                      if (res) {
                        customerFormState.readonly = true;
                        notify('create', $t('general.success'));
                      }
                    } else {
                      if (!customerFormState.editCustomerId) return;
                      await customerStore.editBranchById(
                        customerFormData.customerBranch[idx].id || '',
                        {
                          ...customerFormData.customerBranch[idx],
                          id: undefined,
                        },
                      );
                    }

                    const uploadResult =
                      customerFormData.customerBranch[idx].file?.map(
                        async (v) => {
                          if (!v.file) return;

                          const ext = v.file.name.split('.').at(-1);
                          let filename = v.group + '-' + new Date().getTime();
                          if (ext) filename += `.${ext}`;

                          const res = await customerStore.putAttachment({
                            branchId:
                              customerFormData.customerBranch?.[idx].id || '',
                            file: v.file,
                            filename,
                          });

                          if (res) {
                            await customerFormStore.assignFormData(
                              customerFormState.editCustomerId,
                            );
                          }
                        },
                      ) || [];

                    for (const r of uploadResult) await r;

                    await customerFormStore.assignFormData(
                      customerFormState.editCustomerId,
                    );

                    await fetchListCustomer(true);
                    customerFormStore.resetForm();
                  }
                "
              >
                <!-- v-if="!!customerFormState.editCustomerId" -->

                <EmployerFormBranch
                  :index="idx"
                  prefixId="form"
                  v-if="customerFormData.customerBranch"
                  v-model:customer="customerFormData"
                  v-model:customer-branch="customerFormData.customerBranch[idx]"
                  :onCreate="customerFormState.dialogType === 'create'"
                  :customer-type="customerFormData.customerType"
                  :customer-name="`${customerFormData.firstName} ${customerFormData.lastName}`"
                  :readonly="customerFormState.branchIndex !== idx"
                  :action-disabled="
                    !customerFormState.readonly ||
                    (customerFormState.branchIndex !== -1 &&
                      customerFormState.branchIndex !== idx)
                  "
                  @edit="() => (customerFormState.branchIndex = idx)"
                  @cancel="() => customerFormUndo(false)"
                  @delete="
                    async () => {
                      if (!customerFormState.editCustomerId) return;

                      if (idx === 0) {
                        deleteCustomerById(customerFormState.editCustomerId);
                        return;
                      }
                      if (!!customerFormData.customerBranch?.[idx].id) {
                        const action = await deleteCustomerBranchById(
                          customerFormData.customerBranch[idx].id || '',
                        );
                        if (action) {
                          await customerFormStore.assignFormData(
                            customerFormState.editCustomerId,
                          );
                        }
                        customerFormStore.resetForm();
                      }
                    }
                  "
                  @save="() => {}"
                />
              </q-form>
            </template>
          </div>
        </div>
      </div>
    </div>
  </DialogContainer>

  <!-- add employee -->
  <DialogForm
    hideFooter
    :title="$t('form.title.create', { name: $t('customer.employee') })"
    v-model:modal="employeeFormState.dialogModal"
    :undo="() => employeeFormUndo(false)"
    :submit="
      async () => {
        if (employeeFormState.currentTab === 'personalInfo') {
          await employeeFormStore.submitPersonal(onCreateImageList);
          employeeFormState.isEmployeeEdit = false;
          employeeFormState.dialogType = 'info';
        }

        if (employeeFormState.currentTab === 'passport') {
          await employeeFormStore.submitPassport();
        }

        if (employeeFormState.currentTab === 'visa') {
          await employeeFormStore.submitVisa();
        }

        if (employeeFormState.currentTab === 'healthCheck') {
          await employeeFormStore.submitHealthCheck();
        }

        if (employeeFormState.currentTab === 'workHistory') {
          await employeeFormStore.submitWorkHistory();
        }

        if (employeeFormState.currentTab === 'other') {
          await employeeFormStore.submitOther();
        }
        statusEmployeeCreate = true;
        employeeFormState.isEmployeeEdit = false;

        await fetchListEmployee(true);
      }
    "
    :show="
      () => {
        employeeFormStore.resetFormDataEmployee(true);
      }
    "
    :before-close="
      () => {
        if (employeeFormStore.isFormDataDifferent()) {
          employeeConfirmUnsave();
          return true;
        } else {
          fetchListEmployee();
        }

        employeeFormState.currentTab = 'personalInfo';
        return false;
      }
    "
  >
    <div
      :class="{
        'q-mx-lg q-my-md': $q.screen.gt.sm,
        'q-mx-md q-my-sm': !$q.screen.gt.sm,
      }"
    >
      <ProfileBanner
        active
        useToggle
        prefix="dialog"
        color="white"
        icon="mdi-account-plus-outline"
        :bg-color="
          employeeFormState.profileUrl
            ? 'white'
            : 'linear-gradient(135deg, rgba(43,137,223,1) 0%, rgba(230,51,81,1) 100%)'
        "
        v-model:current-tab="employeeFormState.currentTab"
        v-model:toggle-status="currentFromDataEmployee.status"
        fallbackCover="/images/employee-banner.png"
        :img="
          `${baseUrl}/employee/${currentFromDataEmployee.id}/image/${currentFromDataEmployee.selectedImage}`.concat(
            refreshImageState ? `?ts=${Date.now()}` : '',
          ) || null
        "
        :fallbackImg="'/images/employee-avatar.png'"
        :tabs-list="
          [
            {
              name: 'personalInfo',
              label: 'customerEmployee.form.group.personalInfo',
            },
            {
              name: 'passport',
              label: 'customerEmployee.fileType.passport',
            },
            {
              name: 'visa',
              label: 'customerEmployee.form.group.visa',
            },

            {
              name: 'healthCheck',
              label: 'customerEmployee.form.group.healthCheck',
            },
            {
              name: 'workHistory',
              label: 'customerEmployee.form.group.workHistory',
            },
            { name: 'other', label: 'customerEmployee.form.group.other' },
          ].filter((v) => {
            if (!employeeFormState.statusSavePersonal) {
              return v.name === 'personalInfo';
            }

            return true;
          })
        "
        :toggleTitle="$t('status.title')"
        hideFade
        @view="
          () => {
            employeeFormState.imageDialog = true;
            employeeFormState.isImageEdit = false;
          }
        "
        @edit="
          employeeFormState.imageDialog = employeeFormState.isImageEdit = true
        "
        @update:toggle-status="
          () => {
            currentFromDataEmployee.status =
              currentFromDataEmployee.status === 'CREATED'
                ? 'INACTIVE'
                : 'CREATED';
          }
        "
      />
    </div>

    <div
      style="flex: 1; width: 100%; overflow-y: auto"
      :class="{
        'q-px-lg q-pb-lg': $q.screen.gt.sm,
        'q-px-md q-pb-sm': !$q.screen.gt.sm,
      }"
      id="drawer-employee-form"
    >
      <div
        class="col surface-1 full-height rounded bordered scroll row relative-position"
      >
        <div
          class="col"
          style="height: 100%; max-height: 100; overflow-y: auto"
          v-if="$q.screen.gt.sm"
        >
          <div class="q-py-md q-pl-md q-pr-sm">
            <SideMenu
              :menu="
                [
                  {
                    name: $t('form.field.basicInformation'),
                    anchor: 'form-information',
                    tab: 'personalInfo',
                  },
                  {
                    name: $t('customerEmployee.form.group.personalInfo'),
                    anchor: 'form-personal',
                    tab: 'personalInfo',
                  },
                  {
                    name: $t('general.address'),
                    anchor: 'form-personal-address',
                    tab: 'personalInfo',
                  },
                  {
                    name: $t('general.uploadFile'),
                    anchor: 'drawer-info-file-upload',
                    tab: 'personalInfo',
                  },

                  {
                    name: $t('customerEmployee.form.group.passport'),
                    anchor: 'form-passport',
                    tab: 'passport',
                    useBtn:
                      currentFromDataEmployee.employeePassport?.filter(
                        (item) => {
                          if (item.id === undefined) {
                            return true;
                          }
                          return false;
                        },
                      ).length === 0 &&
                      employeeFormState.currentIndexPassport === -1
                        ? true
                        : false,
                  },
                  ...(currentFromDataEmployee.employeePassport?.map((v, i) => ({
                    name: dateFormat(v.expireDate),
                    anchor: `drawer-employee-employeePassport-${i}`,
                    tab: 'passport',
                    sub: true,
                  })) || []),

                  {
                    name: $t('customerEmployee.form.group.visa'),
                    anchor: 'drawer-visa',
                    tab: 'visa',
                    useBtn:
                      currentFromDataEmployee.employeeVisa?.filter((item) => {
                        if (item.id === undefined) {
                          return true;
                        }
                        return false;
                      }).length === 0 &&
                      employeeFormState.currentIndexVisa === -1
                        ? true
                        : false,
                  },

                  ...(currentFromDataEmployee.employeeVisa?.map((v, i) => ({
                    name: dateFormat(v.expireDate),
                    anchor: `drawer-employee-visa-${i}`,
                    tab: 'visa',
                    sub: true,
                  })) || []),

                  {
                    name: $t('customerEmployee.form.group.visa'),
                    anchor: 'form-employee-checkup',
                    tab: 'healthCheck',
                    useBtn:
                      currentFromDataEmployee.employeeCheckup?.filter(
                        (item) => {
                          if (item.id === undefined) {
                            return true;
                          }
                          return false;
                        },
                      ).length === 0 &&
                      employeeFormState.currentIndexCheckup === -1
                        ? true
                        : false,
                  },

                  ...(currentFromDataEmployee.employeeCheckup?.map((v, i) => ({
                    name: $t('general.times', { number: i + 1 }),
                    anchor: `form-employee-checkup-${i}`,
                    tab: 'healthCheck',
                  })) || []),

                  {
                    name: $t('customerEmployee.form.group.workHistory'),
                    anchor: 'form-employee-work-history',
                    tab: 'workHistory',
                    useBtn:
                      currentFromDataEmployee.employeeWork?.filter((item) => {
                        if (item.id === undefined) {
                          return true;
                        }
                        return false;
                      }).length === 0 &&
                      employeeFormState.currentIndexWorkHistory === -1
                        ? true
                        : false,
                  },

                  ...(currentFromDataEmployee.employeeWork?.map((v, i) => ({
                    name: $t('general.times', { number: i + 1 }),
                    anchor: `form-employee-work-history-${i}`,
                    tab: 'workHistory',
                  })) || []),

                  {
                    name: $t('customerEmployee.form.group.family'),
                    anchor: 'form-employee-other',
                    tab: 'other',
                  },
                ].filter((v) => v.tab === employeeFormState.currentTab)
              "
              background="transparent"
              :active="{
                background: 'hsla(var(--blue-6-hsl) / .2)',
                foreground: 'var(--blue-6)',
              }"
              scroll-element="#employee-form-content"
            >
              <template v-slot:btn-form-passport>
                <q-btn
                  id="form-add-passport"
                  dense
                  flat
                  icon="mdi-plus"
                  size="sm"
                  rounded
                  padding="0px 0px"
                  style="color: var(--stone-9)"
                  @click.stop="employeeFormStore.addPassport()"
                />
              </template>

              <template v-slot:btn-drawer-visa>
                <q-btn
                  id="form-add-visa"
                  dense
                  flat
                  icon="mdi-plus"
                  size="sm"
                  rounded
                  style="color: var(--stone-9)"
                  @click.stop="employeeFormStore.addVisa()"
                />
              </template>

              <template v-slot:btn-drawer-employee-checkup>
                <q-btn
                  id="form-add-checkup"
                  dense
                  flat
                  icon="mdi-plus"
                  size="sm"
                  rounded
                  style="color: var(--stone-9)"
                  @click.stop="employeeFormStore.addCheckup()"
                />
              </template>

              <template v-slot:btn-drawer-employee-work-history>
                <q-btn
                  id="form-add-work-history"
                  dense
                  flat
                  icon="mdi-plus"
                  size="sm"
                  rounded
                  style="color: var(--stone-9)"
                  @click.stop="employeeFormStore.addWorkHistory()"
                />
              </template>
            </SideMenu>
          </div>
        </div>

        <div
          class="col-12 col-md-10"
          :class="{
            'q-py-md q-pr-md ': $q.screen.gt.sm,
            'q-py-md q-px-lg': !$q.screen.gt.sm,
          }"
          id="employee-form-content"
          style="height: 100%; max-height: 100; overflow-y: auto"
        >
          <template v-if="employeeFormState.currentTab === 'personalInfo'">
            <div
              class="rounded row q-py-md q-px-md"
              style="position: absolute; z-index: 999; top: 0; right: 0"
            >
              <div class="surface-1 row rounded">
                <UndoButton
                  v-if="
                    employeeFormState.isEmployeeEdit &&
                    employeeFormState.dialogType !== 'create'
                  "
                  id="btn-info-basic-undo"
                  icon-only
                  @click="
                    () => {
                      employeeFormStore.resetFormDataEmployee();
                      employeeFormState.isEmployeeEdit = false;
                      employeeFormState.dialogType = 'info';
                    }
                  "
                  type="button"
                />
                <SaveButton
                  v-if="employeeFormState.isEmployeeEdit"
                  id="btn-info-basic-save"
                  icon-only
                  type="submit"
                />
                <EditButton
                  v-if="!employeeFormState.isEmployeeEdit"
                  id="btn-info-basic-edit"
                  icon-only
                  @click="
                    () => {
                      employeeFormState.isEmployeeEdit = true;
                      employeeFormState.dialogType = 'edit';
                    }
                  "
                  type="button"
                />
                <DeleteButton
                  v-if="!employeeFormState.isEmployeeEdit"
                  id="btn-info-basic-delete"
                  icon-only
                  @click="
                    () => deleteEmployeeById({ id: currentFromDataEmployee.id })
                  "
                  type="button"
                />
              </div>
            </div>
            <BasicInformation
              no-action
              id="form-information"
              prefix-id="form-employee"
              :show-btn-save="employeeFormState.dialogType === 'create'"
              employee
              dense
              outlined
              separator
              title="form.field.basicInformation"
              :readonly="!employeeFormState.isEmployeeEdit"
              :employee-owner-option="employeeStore.ownerOption || []"
              v-model:customer-branch="employeeFormState.formDataEmployeeOwner"
              v-model:employee-id="employeeFormState.currentEmployeeCode"
              v-model:nrc-no="currentFromDataEmployee.nrcNo"
              v-model:code="currentFromDataEmployee.code"
              @filter-owner-branch="employeeFormStore.employeeFilterOwnerBranch"
              class="q-mb-xl"
            />
            <FormPerson
              id="form-personal"
              prefix-id="form-employee"
              dense
              outlined
              employee
              separator
              title="customerEmployee.form.group.personalInfo"
              :readonly="!employeeFormState.isEmployeeEdit"
              v-model:open="employeeFormState.dialogModal"
              v-model:prefix-name="currentFromDataEmployee.namePrefix"
              v-model:first-name="currentFromDataEmployee.firstName"
              v-model:last-name="currentFromDataEmployee.lastName"
              v-model:first-name-en="currentFromDataEmployee.firstNameEN"
              v-model:last-name-en="currentFromDataEmployee.lastNameEN"
              v-model:mid-name="currentFromDataEmployee.middleName"
              v-model:mid-name-en="currentFromDataEmployee.middleNameEN"
              v-model:gender="currentFromDataEmployee.gender"
              v-model:birth-date="currentFromDataEmployee.dateOfBirth"
              v-model:nationality="currentFromDataEmployee.nationality"
              class="q-mb-xl"
            />
            <AddressForm
              id="form-personal-address"
              prefix-id="form-employee"
              :readonly="!employeeFormState.isEmployeeEdit"
              v-model:same-with-employer="
                employeeFormState.formDataEmployeeSameAddr
              "
              v-model:address="currentFromDataEmployee.address"
              v-model:address-en="currentFromDataEmployee.addressEN"
              v-model:moo="currentFromDataEmployee.moo"
              v-model:moo-en="currentFromDataEmployee.mooEN"
              v-model:soi="currentFromDataEmployee.soi"
              v-model:soi-en="currentFromDataEmployee.soiEN"
              v-model:street="currentFromDataEmployee.street"
              v-model:street-en="currentFromDataEmployee.streetEN"
              v-model:province-id="currentFromDataEmployee.provinceId"
              v-model:district-id="currentFromDataEmployee.districtId"
              v-model:sub-district-id="currentFromDataEmployee.subDistrictId"
              employee
              dense
              class="q-mb-xl"
            />

            <div class="row q-mb-md" id="drawer-info-file-upload">
              <div class="col-12 q-pb-sm text-weight-bold text-body1">
                <q-icon
                  flat
                  size="xs"
                  class="q-pa-sm rounded q-mr-xs"
                  color="info"
                  name="mdi-upload"
                  style="background-color: var(--surface-3)"
                />
                {{ $t(`general.uploadFile`) }}
              </div>
              <!-- สร้างลูกจ้าง -->
              <UploadFileGroup
                v-model:current-id="currentFromDataEmployee.id"
                v-model="currentFromDataEmployee.file"
                hide-action
                :readonly="!employeeFormState.isEmployeeEdit"
                :menu="uploadFileListEmployee"
                :columns="columnsAttachment"
                @submit="
                  async (group, allMeta) => {
                    if (allMeta === undefined) return;

                    if (group === 'passport') {
                      const fullName = allMeta['full_name'].split(' ');
                      let tempValue: {
                        oldData: { nameField: string; value: string }[];
                        newData: { nameField: string; value: string }[];
                      } = { oldData: [], newData: [] };

                      if (
                        currentFromDataEmployee.gender !== '' &&
                        currentFromDataEmployee.gender !== allMeta['sex']
                      ) {
                        tempValue.oldData.push({
                          nameField: $t('form.gender'),
                          value: $t(
                            `general.${currentFromDataEmployee.gender}`,
                          ),
                        });
                        tempValue.newData.push({
                          nameField: $t('form.gender'),
                          value: $t(`general.${allMeta['sex']}`),
                        });
                      }

                      if (currentFromDataEmployee.firstName !== '') {
                        tempValue.oldData.push({
                          nameField: $t('personnel.form.firstName'),
                          value: currentFromDataEmployee.firstName,
                        });
                        tempValue.newData.push({
                          nameField: $t('personnel.form.firstName'),
                          value: fullName[0],
                        });
                      }

                      if (currentFromDataEmployee.lastName !== '') {
                        tempValue.oldData.push({
                          nameField: $t('personnel.form.lastName'),
                          value: currentFromDataEmployee.lastName,
                        });
                        tempValue.newData.push({
                          nameField: $t('personnel.form.lastName'),
                          value: fullName[1],
                        });
                      }

                      if (currentFromDataEmployee.nationality !== '') {
                        tempValue.oldData.push({
                          nameField: $t('general.nationality'),
                          value: currentFromDataEmployee.nationality || '',
                        });
                        tempValue.newData.push({
                          nameField: $t('general.nationality'),
                          value: allMeta['nationality'],
                        });
                      }

                      dialogCheckData({
                        action: async () => {
                          currentFromDataEmployee.gender = allMeta['sex'];
                          currentFromDataEmployee.firstName = fullName[0];
                          currentFromDataEmployee.lastName = fullName[1];
                          currentFromDataEmployee.nationality =
                            allMeta['nationality'];
                        },
                        checkData: () => {
                          return tempValue;
                        },
                        cancel: () => {
                          if (!currentFromDataEmployee.gender) {
                            currentFromDataEmployee.gender = allMeta['gender'];
                          }
                          if (!currentFromDataEmployee.firstName) {
                            currentFromDataEmployee.firstName = fullName[0];
                          }
                          if (!currentFromDataEmployee.firstName) {
                            currentFromDataEmployee.firstName = fullName[0];
                          }
                          if (!currentFromDataEmployee.lastName) {
                            currentFromDataEmployee.lastName = fullName[1];
                          }

                          if (!currentFromDataEmployee.nationality) {
                            currentFromDataEmployee.nationality =
                              allMeta['nationality'];
                          }
                        },
                      });
                    }
                  }
                "
                :ocr="
                  async (group, file) => {
                    if (group === 'passport') {
                      mrz = await runOcr(file, parseResultMRZ);

                      if (mrz !== null) {
                        const mapMrz = Object.entries(mrz.result || {}).map(
                          ([key, value]) => ({
                            name: key,
                            value: value,
                          }),
                        );
                        const tempValue = {
                          status: true,
                          group,
                          meta: mapMrz,
                        };

                        return tempValue;
                      }
                    }
                    if (group === 'visa') {
                      const res = await ocrStore.sendOcr({
                        file: file,
                        category: group,
                      });

                      if (res) {
                        const tempValue = {
                          status: true,
                          group,
                          meta: res.fields,
                        };

                        return tempValue;
                      }
                    }

                    return { status: true, group, meta: [] };
                  }
                "
                :auto-save="currentFromDataEmployee.id !== ''"
                :download="
                  (obj) => {
                    if (obj.group !== 'attachment') {
                      employeeStore.getFile({
                        parentId: currentFromDataEmployee.id || '',
                        group: obj.group,
                        fileId: obj._meta.id,
                        download: true,
                      });
                    } else {
                      employeeStore.getAttachment({
                        parentId: currentFromDataEmployee.id || '',
                        name: obj._meta.name,
                        download: true,
                      });
                    }
                  }
                "
                :delete-item="
                  async (obj) => {
                    let status: boolean = false;
                    const res = await employeeStore.delMeta({
                      parentId: currentFromDataEmployee.id || '',
                      group: obj.group,
                      metaId: obj._meta.id,
                    });

                    if (res) {
                      status = true;
                    }

                    await employeeFormStore.assignFormDataEmployee(
                      currentFromDataEmployee.id,
                    );

                    return status;
                  }
                "
                :save="
                  async (
                    group: 'passport' | 'visa' | 'attachment',
                    _meta: any,
                    file: File | undefined,
                  ) => {
                    let status: boolean = false;
                    if (group !== 'attachment') {
                      if (file !== undefined && currentFromDataEmployee.id) {
                        const res = await employeeStore.postMeta({
                          parentId: currentFromDataEmployee.id || '',
                          group,
                          meta: _meta,
                          file,
                        });

                        if (res) {
                          status = true;
                        }
                      } else {
                        const {
                          id,
                          employeeId,
                          createdAt,
                          updatedAt,
                          ...payload
                        } = _meta;

                        const res = await employeeStore.putMeta({
                          parentId: currentFromDataEmployee.id || '',
                          group,
                          metaId: _meta.id,
                          meta: payload,
                          file,
                        });
                        if (res) {
                          status = true;
                        }
                      }
                    } else {
                      if (file !== undefined) {
                        await employeeStore.uploadAttachment(
                          currentFromDataEmployee.id || '',
                          file,
                          file.name,
                        );
                        status = true;
                      }
                    }
                    await employeeFormStore.assignFormDataEmployee(
                      currentFromDataEmployee.id,
                    );
                    return status;
                  }
                "
                :get-file-list="
                  async (group: 'passport' | 'visa' | 'attachment') => {
                    if (
                      !!currentFromDataEmployee.id &&
                      group !== 'attachment'
                    ) {
                      const resMeta = await employeeStore.getMetaList({
                        parentId: currentFromDataEmployee.id,
                        group,
                      });

                      const tempValue = resMeta.map(async (i: any) => {
                        return {
                          _meta: { ...i },
                          name: `${group}-${dateFormat(i.expireDate)}` || '',
                          group: group,
                          url: await employeeStore.getFile({
                            parentId: currentFromDataEmployee.id || '',
                            group,
                            fileId: i.id,
                          }),
                          file: undefined,
                        };
                      });

                      return await waitAll(tempValue);
                    } else {
                      const res = await employeeStore.listAttachment({
                        parentId: currentFromDataEmployee.id || '',
                      });

                      const tempValue = (res as string[]).map(
                        async (i: any) => {
                          return {
                            _meta: { id: i, name: i },
                            name: i || '',
                            group: group,
                            url: await employeeStore.getAttachment({
                              parentId: currentFromDataEmployee.id || '',
                              name: i,
                            }),
                            file: undefined,
                          };
                        },
                      );

                      return await waitAll(tempValue);
                    }
                  }
                "
              >
                <template #form="{ mode, meta, isEdit }">
                  <FormCitizen
                    v-if="mode === 'citizen' && meta"
                    orc
                    ra
                    :readonly="!isEdit"
                    v-model:citizen-id="meta.citizenId"
                    v-model:birth-date="meta.birthDate"
                    v-model:first-name="meta.firstName"
                    v-model:first-name-en="meta.firstNameEN"
                    v-model:last-name="meta.lastName"
                    v-model:last-name-en="meta.lastNameEN"
                    v-model:address="meta.address"
                  />
                  <FormEmployeePassport
                    v-if="mode === 'passport' && meta"
                    prefix-id="drawer-info-employee"
                    id="form-passport"
                    dense
                    outlined
                    separator
                    ocr
                    :title="$t('customerEmployee.form.group.passport')"
                    :readonly="!isEdit"
                    v-model:birth-country="meta.birthCountry"
                    v-model:previous-passportRef="meta.previousPassportRef"
                    v-model:issue-place="meta.issuePlace"
                    v-model:issue-country="meta.issueCountry"
                    v-model:issue-date="meta.issueDate"
                    v-model:type="meta.type"
                    v-model:expire-date="meta.expireDate"
                    v-model:birth-date="meta.birthDate"
                    v-model:worker-status="meta.workerStatus"
                    v-model:nationality="meta.nationality"
                    v-model:gender="meta.gender"
                    v-model:last-name-en="meta.lastNameEN"
                    v-model:last-name="meta.lastName"
                    v-model:middle-name-en="meta.middleNameEN"
                    v-model:middle-name="meta.middleName"
                    v-model:first-name-en="meta.firstNameEN"
                    v-model:first-name="meta.firstName"
                    v-model:name-prefix="meta.namePrefix"
                    v-model:passport-number="meta.number"
                  />
                  <FormEmployeeVisa
                    v-if="mode === 'visa' && meta"
                    prefix-id="drawer-info-employee"
                    id="form-visa"
                    ocr
                    dense
                    outlined
                    title="customerEmployee.form.group.visa"
                    :readonly="!isEdit"
                    v-model:arrival-at="meta.arrivalAt"
                    v-model:arrival-tm-no="meta.arrivalTMNo"
                    v-model:arrival-tm="meta.arrivalTM"
                    v-model:mrz="meta.mrz"
                    v-model:entry-count="meta.entryCount"
                    v-model:issue-place="meta.issuePlace"
                    v-model:issue-country="meta.issueCountry"
                    v-model:issueDate="meta.issueDate"
                    v-model:type="meta.type"
                    v-model:expire-date="meta.expireDate"
                    v-model:visa-issue-date="meta.issueDate"
                    v-model:visa-expiry-date="meta.expireDate"
                    v-model:remark="meta.remark"
                    v-model:worker-type="meta.workerType"
                    v-model:number="meta.number"
                  />

                  <NoticeJobEmployment v-if="mode === 'noticeJobEmployment'" />
                </template>
              </UploadFileGroup>
            </div>
          </template>

          <template v-if="employeeFormState.currentTab === 'passport'">
            <div class="q-gutter-sm">
              <div class="col-12 q-pb-sm text-weight-bold text-body1">
                <q-icon
                  flat
                  size="xs"
                  class="q-pa-sm rounded q-mr-xs"
                  color="info"
                  name="mdi-passport"
                  style="background-color: var(--surface-3)"
                />
                {{ $t('customerEmployee.form.group.passport') }}
              </div>

              <FormEmployeePassport
                v-for="(
                  value, index
                ) in currentFromDataEmployee.employeePassport"
                prefix-id="drawer-info-employee"
                :key="index"
                id="form-passport"
                hide-title
                dense
                outlined
                separator
                :title="$t('customerEmployee.form.group.passport')"
                :readonly="employeeFormState.currentIndexPassport !== index"
                :full-name="employeeFormState.currentIndexPassport !== index"
                v-model:birth-country="value.birthCountry"
                v-model:previous-passportRef="value.previousPassportRef"
                v-model:issue-place="value.issuePlace"
                v-model:issue-country="value.issueCountry"
                v-model:issue-date="value.issueDate"
                v-model:type="value.type"
                v-model:expire-date="value.expireDate"
                v-model:birth-date="value.birthDate"
                v-model:worker-status="value.workerStatus"
                v-model:nationality="value.nationality"
                v-model:gender="value.gender"
                v-model:last-name-en="value.lastNameEN"
                v-model:last-name="value.lastName"
                v-model:middle-name-en="value.middleNameEN"
                v-model:middle-name="value.middleName"
                v-model:first-name-en="value.firstNameEN"
                v-model:first-name="value.firstName"
                v-model:name-prefix="value.namePrefix"
                v-model:passport-number="value.number"
              >
                <template v-slot:expiryDate>
                  {{ $t('general.expirationDate') }} :
                  {{ dateFormat(value.expireDate) }}
                  <ExpirationDate
                    v-if="value.id !== undefined"
                    :expiration-date="value.expireDate"
                  />
                </template>

                <template v-slot:button>
                  <div class="surface-1 row rounded" style="min-height: 35px">
                    <UndoButton
                      v-if="
                        employeeFormState.isEmployeeEdit &&
                        !(employeeFormState.currentIndexPassport === -1) &&
                        employeeFormState.currentIndexPassport === index
                      "
                      id="btn-info-basic-undo"
                      icon-only
                      @click="
                        () => {
                          employeeFormStore.resetFormDataEmployee();
                          employeeFormState.isEmployeeEdit = false;
                          employeeFormState.dialogType = 'info';
                          employeeFormState.currentIndexPassport = -1;
                        }
                      "
                      type="button"
                    />
                    <SaveButton
                      v-if="
                        (employeeFormState.isEmployeeEdit ||
                          value.id === undefined) &&
                        !(employeeFormState.currentIndexPassport === -1) &&
                        employeeFormState.currentIndexPassport === index
                      "
                      id="btn-info-basic-save"
                      icon-only
                      @click="
                        () => {
                          employeeFormState.currentIndexPassport = index;
                        }
                      "
                      type="submit"
                    />

                    <EditButton
                      v-if="
                        employeeFormState.currentIndexPassport === -1 ||
                        (!employeeFormState.isEmployeeEdit &&
                          value.id !== undefined &&
                          employeeFormState.currentIndexPassport === index)
                      "
                      id="btn-info-basic-edit"
                      icon-only
                      @click="
                        () => {
                          employeeFormState.currentIndexPassport = index;
                          employeeFormState.isEmployeeEdit = true;
                          employeeFormState.dialogType = 'edit';
                        }
                      "
                      type="button"
                    />
                    <DeleteButton
                      v-if="
                        employeeFormState.currentIndexPassport === -1 ||
                        (!employeeFormState.isEmployeeEdit &&
                          value.id !== undefined &&
                          !(employeeFormState.currentIndexPassport === -1) &&
                          employeeFormState.currentIndexPassport === index)
                      "
                      id="btn-info-basic-delete"
                      icon-only
                      @click.stop="
                        () => {
                          employeeFormState.currentIndexPassport = index;
                          deleteEmployeeById({ type: 'passport', index });
                        }
                      "
                      type="button"
                      :disabled="
                        !(employeeFormState.currentIndexPassport === -1) &&
                        !(employeeFormState.currentIndexPassport === index)
                      "
                    />
                  </div>
                </template>
              </FormEmployeePassport>
            </div>
          </template>

          <template v-if="employeeFormState.currentTab === 'visa'">
            <div class="q-gutter-sm">
              <div class="col-12 q-pb-sm text-weight-bold text-body1">
                <q-icon
                  flat
                  size="xs"
                  class="q-pa-sm rounded q-mr-xs"
                  color="info"
                  name="mdi-passport"
                  style="background-color: var(--surface-3)"
                />
                {{ $t('customerEmployee.form.group.visa') }}
              </div>

              <FormEmployeeVisa
                v-for="(value, index) in currentFromDataEmployee.employeeVisa"
                prefix-id="drawer-info-employee"
                id="form-visa"
                dense
                outlined
                title="customerEmployee.form.group.visa"
                :readonly="employeeFormState.currentIndexVisa !== index"
                hide-title
                v-model:arrival-at="value.arrivalAt"
                v-model:arrival-tm-no="value.arrivalTMNo"
                v-model:arrival-tm="value.arrivalTM"
                v-model:mrz="value.mrz"
                v-model:entry-count="value.entryCount"
                v-model:issue-place="value.issuePlace"
                v-model:issue-country="value.issueCountry"
                v-model:issueDate="value.issueDate"
                v-model:type="value.type"
                v-model:expire-date="value.expireDate"
                v-model:visa-issue-date="value.issueDate"
                v-model:visa-expiry-date="value.expireDate"
                v-model:remark="value.remark"
                v-model:worker-type="value.workerType"
                v-model:number="value.number"
              >
                <template v-slot:expiryDate>
                  {{ $t('general.expirationDate') }} :
                  {{ dateFormat(value.expireDate) }}
                  <ExpirationDate
                    v-if="value.id !== undefined"
                    :expiration-date="value.expireDate"
                  />
                </template>

                <template v-slot:button>
                  <div class="surface-1 row rounded" style="min-height: 35px">
                    <UndoButton
                      v-if="
                        employeeFormState.isEmployeeEdit &&
                        !(employeeFormState.currentIndexVisa === -1) &&
                        employeeFormState.currentIndexVisa === index
                      "
                      id="btn-info-basic-undo"
                      icon-only
                      @click="
                        () => {
                          employeeFormStore.resetFormDataEmployee();
                          employeeFormState.isEmployeeEdit = false;
                          employeeFormState.dialogType = 'info';
                          employeeFormState.currentIndexVisa = -1;
                        }
                      "
                      type="button"
                    />
                    <SaveButton
                      v-if="
                        (employeeFormState.isEmployeeEdit ||
                          value.id === undefined) &&
                        !(employeeFormState.currentIndexVisa === -1) &&
                        employeeFormState.currentIndexVisa === index
                      "
                      id="btn-info-basic-save"
                      icon-only
                      @click="
                        () => {
                          employeeFormState.currentIndexVisa = index;
                        }
                      "
                      type="submit"
                    />

                    <EditButton
                      v-if="
                        employeeFormState.currentIndexVisa === -1 ||
                        (!employeeFormState.isEmployeeEdit &&
                          value.id !== undefined &&
                          employeeFormState.currentIndexVisa === index)
                      "
                      id="btn-info-basic-edit"
                      icon-only
                      @click="
                        () => {
                          employeeFormState.currentIndexVisa = index;
                          employeeFormState.isEmployeeEdit = true;
                          employeeFormState.dialogType = 'edit';
                        }
                      "
                      type="button"
                    />
                    <DeleteButton
                      v-if="
                        employeeFormState.currentIndexVisa === -1 ||
                        (!employeeFormState.isEmployeeEdit &&
                          value.id !== undefined &&
                          !(employeeFormState.currentIndexVisa === -1) &&
                          employeeFormState.currentIndexVisa === index)
                      "
                      id="btn-info-basic-delete"
                      icon-only
                      @click.stop="
                        () => {
                          employeeFormState.currentIndexVisa = index;
                          deleteEmployeeById({ type: 'visa', index });
                        }
                      "
                      type="button"
                      :disabled="
                        !(employeeFormState.currentIndexVisa === -1) &&
                        !(employeeFormState.currentIndexVisa === index)
                      "
                    />
                  </div>
                </template>
              </FormEmployeeVisa>
            </div>
          </template>

          <template v-if="employeeFormState.currentTab === 'healthCheck'">
            <div class="q-gutter-sm">
              <div class="q-pb-sm text-weight-bold text-body1 row items-center">
                <q-icon
                  flat
                  size="xs"
                  class="q-pa-sm rounded q-mr-sm"
                  color="info"
                  name="mdi-hospital-box-outline"
                  style="background-color: var(--surface-3)"
                />

                {{ $t(`customerEmployee.formHealthCheck.title`) }}
              </div>
              <FormEmployeeHealthCheck
                v-if="employeeFormState.currentTab === 'healthCheck'"
                id="form-checkup"
                prefix-id="form-employee"
                dense
                outlined
                v-model:current-index="employeeFormState.currentIndexCheckup"
                v-model:employee-checkup="
                  currentFromDataEmployee.employeeCheckup
                "
                v-model:checkup-results-option="
                  optionStore.globalOption.checkupResults
                "
                v-model:checkup-type-option="
                  optionStore.globalOption.insurancePlace
                "
                v-model:medical-benefit-option="
                  optionStore.globalOption.typeInsurance
                "
                v-model:insurance-company-option="
                  optionStore.globalOption.insurancePlace
                "
                @delete="
                  (index) => {
                    employeeFormState.currentIndexCheckup = index;
                    deleteEmployeeById({ type: 'healthCheck', index });
                  }
                "
                @save="
                  (index) => {
                    employeeFormState.currentIndexCheckup = index;
                    notify('create', $t('general.success'));
                  }
                "
                @undo="
                  (index) => {
                    if (
                      currentFromDataEmployee.employeeCheckup?.[index]
                        .statusSave === false
                    ) {
                      currentFromDataEmployee.employeeCheckup[
                        index
                      ].statusSave = true;
                    }
                  }
                "
                @edit="
                  (index) => {
                    if (
                      currentFromDataEmployee.employeeCheckup?.[index]
                        .statusSave
                    ) {
                      currentFromDataEmployee.employeeCheckup[
                        index
                      ].statusSave = false;
                    }
                  }
                "
              />
            </div>
          </template>

          <template v-if="employeeFormState.currentTab === 'workHistory'">
            <div class="q-gutter-sm">
              <div
                class="col-12 q-pb-sm text-weight-bold text-body1 row items-center"
              >
                <q-icon
                  flat
                  size="xs"
                  class="q-pa-sm rounded q-mr-xs"
                  color="info"
                  name="mdi-briefcase-outline"
                  style="background-color: var(--surface-3)"
                />
                {{ $t(`customerEmployee.form.group.workHistory`) }}
              </div>
              <FormEmployeeWorkHistory
                v-if="employeeFormState.currentTab === 'workHistory'"
                id="form-work-history"
                prefix-id="form-employee"
                dense
                outlined
                v-model:current-index="
                  employeeFormState.currentIndexWorkHistory
                "
                v-model:employee-work="currentFromDataEmployee.employeeWork"
                v-model:position-name-option="optionStore.globalOption.position"
                v-model:job-type-option="optionStore.globalOption.businessType"
                v-model:workplace-option="optionStore.globalOption.area"
                @delete="
                  (index) => {
                    employeeFormState.currentIndexWorkHistory = index;
                    deleteEmployeeById({ type: 'work', index });
                  }
                "
                @save="
                  (index) => {
                    employeeFormState.currentIndexWorkHistory = index;
                  }
                "
                @undo="
                  (index) => {
                    if (
                      currentFromDataEmployee.employeeWork?.[index]
                        .statusSave === false
                    ) {
                      currentFromDataEmployee.employeeWork[index].statusSave =
                        true;
                    }
                  }
                "
                @edit="
                  (index) => {
                    if (
                      currentFromDataEmployee.employeeWork?.[index].statusSave
                    ) {
                      currentFromDataEmployee.employeeWork[index].statusSave =
                        false;
                    }
                  }
                "
              />
            </div>
          </template>

          <template v-if="employeeFormState.currentTab === 'other'">
            <FormEmployeeOther
              v-if="employeeFormState.currentTab === 'other'"
              id="form-employee-other"
              prefix-id="form-employee"
              dense
              outlined
              v-model:employee-other="currentFromDataEmployee.employeeOtherInfo"
              @undo="
                () => {
                  if (
                    currentFromDataEmployee.employeeOtherInfo?.statusSave ===
                    false
                  ) {
                    currentFromDataEmployee.employeeOtherInfo.statusSave = true;
                  }
                }
              "
              @edit="
                () => {
                  if (currentFromDataEmployee.employeeOtherInfo?.statusSave) {
                    currentFromDataEmployee.employeeOtherInfo.statusSave = false;
                  }
                }
              "
            />
          </template>
        </div>
      </div>
    </div>
  </DialogForm>

  <ImageUploadDialog
    ref="dialogCustomerImageUpload"
    v-model:dialog-state="customerFormState.imageDialog"
    v-model:file="customerFormData.image"
    v-model:image-url="customerFormState.customerImageUrl"
    v-model:data-list="imageList"
    v-model:on-create-data-list="onCreateImageList"
    :on-create="customerFormState.dialogModal"
    :default-url="customerFormState.defaultCustomerImageUrl"
    :hidden-footer="!customerFormState.isImageEdit"
    @add-image="
      async (v) => {
        if (!v) return;
        if (!customerFormState.editCustomerId) return;
        await customerStore.addImageList(
          v,
          customerFormState.editCustomerId,
          Date.now().toString(),
        );
        await fetchImageList(
          customerFormState.editCustomerId,
          customerFormData.selectedImage || '',
          'customer',
        );
      }
    "
    @remove-image="
      async (v) => {
        if (!v) return;
        if (!customerFormState.editCustomerId) return;
        const name = v.split('/').pop() || '';
        await customerStore.deleteImageByName(
          customerFormState.editCustomerId,
          name,
        );
        await fetchImageList(
          customerFormState.editCustomerId,
          customerFormData.selectedImage || '',
          'customer',
        );
      }
    "
    @submit="
      async (v) => {
        if (customerFormState.dialogModal) {
          customerFormState.customerImageUrl = v;
          customerFormState.imageDialog = false;
        } else {
          refreshImageState = true;
          customerFormData.selectedImage = v;
          imageList ? (imageList.selectedImage = v) : '';
          customerFormState.customerImageUrl = `${baseUrl}/customer/${customerFormState.editCustomerId && customerFormState.editCustomerId}/image/${v}`;
          customerFormStore.resetForm();
          await customerFormStore.submitFormCustomer();
          customerFormState.imageDialog = false;
          refreshImageState = false;
        }
      }
    "
  >
    <template #title>
      <span
        v-if="!customerFormState.dialogModal"
        class="justify-center flex text-bold"
      >
        {{ $t('general.image') }}
        {{
          $i18n.locale === 'eng'
            ? `${customerFormData.firstNameEN} ${customerFormData.lastNameEN}`
            : `${customerFormData.firstName} ${customerFormData.lastName}`
        }}
      </span>
    </template>
    <template #error>
      <div class="full-height full-width" style="background: white">
        <div
          class="full-height full-width flex justify-center items-center"
          :style="`background: ${
            customerFormData.gender
              ? customerFormData.customerType === 'CORP'
                ? '#5f1775'
                : '#347454'
              : `hsla(var(--${customerFormData.customerType === 'PERS' ? 'teal-10-hsl' : 'violet-11-hsl'})/0.1)`
          }`"
        >
          <q-img
            :src="`/images/customer-${customerFormData.customerType}-avartar-${customerFormData.customerType === 'PERS' ? customerFormData.gender : 'male'}.png`"
            fit="contain"
            style="height: 100%"
          >
            <template #error>
              <span
                class="full-width full-height column items-center justify-center"
              >
                <q-icon
                  size="3rem"
                  :name="
                    customerFormData.customerType === 'PERS'
                      ? 'mdi-account-plus-outline'
                      : 'mdi-office-building-outline'
                  "
                  :style="`color: hsla(var(--${customerFormData.customerType === 'PERS' ? 'teal-10-hsl' : 'violet-11-hsl'})/1)`"
                />
              </span>
            </template>
          </q-img>
        </div>
      </div>
    </template>
  </ImageUploadDialog>

  <ImageUploadDialog
    ref="dialogEmployeeImageUpload"
    v-model:dialog-state="employeeFormState.imageDialog"
    v-model:file="currentFromDataEmployee.image"
    v-model:image-url="employeeFormState.profileUrl"
    v-model:data-list="imageList"
    v-model:on-create-data-list="onCreateImageList"
    :on-create="employeeFormState.dialogModal"
    :hidden-footer="!employeeFormState.isImageEdit"
    @add-image="
      async (v) => {
        if (!v) return;
        if (!currentFromDataEmployee.id) return;
        await employeeStore.addImageList(
          v,
          currentFromDataEmployee.id,
          Date.now().toString(),
        );
        await fetchImageList(
          currentFromDataEmployee.id,
          currentFromDataEmployee.selectedImage || '',
          'employee',
        );
      }
    "
    @remove-image="
      async (v) => {
        if (!v) return;
        if (!currentFromDataEmployee.id) return;
        const name = v.split('/').pop() || '';
        await employeeStore.deleteImageByName(currentFromDataEmployee.id, name);
        await fetchImageList(
          currentFromDataEmployee.id,
          currentFromDataEmployee.selectedImage || '',
          'employee',
        );
      }
    "
    @submit="
      async (v) => {
        if (employeeFormState.dialogModal) {
          employeeFormState.profileUrl = v;
          employeeFormState.imageDialog = false;
        } else {
          refreshImageState = true;
          employeeFormState.dialogType = 'edit';
          currentFromDataEmployee.selectedImage = v;
          imageList ? (imageList.selectedImage = v) : '';
          employeeFormState.profileUrl = `${baseUrl}/employee/${currentFromDataEmployee.id && currentFromDataEmployee.id}/image/${v}`;
          employeeFormStore.resetFormDataEmployee();
          await employeeFormStore.submitPersonal();
          employeeFormState.imageDialog = false;
          refreshImageState = false;
          employeeFormState.isEmployeeEdit = false;
          employeeFormState.dialogType = 'info';
          await fetchListEmployee();
        }
      }
    "
  >
    <template #title>
      <span
        v-if="!employeeFormState.dialogModal"
        class="justify-center flex text-bold"
      >
        {{ $t('general.image') }}
        {{
          $i18n.locale === 'eng'
            ? `${currentFromDataEmployee.firstNameEN} ${currentFromDataEmployee.lastNameEN}`
            : `${currentFromDataEmployee.firstName} ${currentFromDataEmployee.lastName}`
        }}
      </span>
    </template>
    <template #error>
      <div class="full-height full-width" style="background: white">
        <div
          class="full-height full-width flex justify-center items-center"
          style="background: #ee4367"
        >
          <q-img
            src="/images/employee-avatar.png"
            fit="contain"
            style="height: 100%"
          />
        </div>
      </div>
    </template>
  </ImageUploadDialog>
  <!-- นายจ้าง edit customer -->
  <DrawerInfo
    hide-action
    v-model:drawer-open="customerFormState.drawerModal"
    :title="
      customerFormData.customerType === 'CORP'
        ? customerFormData.customerBranch[0]?.registerName
        : customerNameInfo
    "
    :badge-label="
      customerFormData.customerType === 'CORP'
        ? $t('customer.employerLegalEntity')
        : $t('customer.employerNaturalPerson')
    "
    :badge-style="
      customerFormData.customerType === 'CORP'
        ? `color: var(--${$q.dark.isActive ? 'violet-10' : 'violet-11'}); background: hsl(var(--${$q.dark.isActive ? 'violet-10-hsl' : 'violet-11-hsl'})/0.15)`
        : `color: var(--${$q.dark.isActive ? 'teal-8' : 'teal-10'}); background: hsl(var(--${$q.dark.isActive ? 'teal-8-hsl' : 'teal-10-hsl'})/0.15)`
    "
    :close="
      () => {
        customerFormState.drawerModal = false;
        resetScrollBar('customer-form-content');
      }
    "
    :submit="
      async () => {
        await customerFormStore.submitFormCustomer();
        customerFormState.readonly = true;
        notify('create', $t('general.success'));
        await fetchListCustomer();
      }
    "
    :show="
      async () => {
        // await fetchListOfOptionBranch();
        // customerFormStore.resetForm(true);
      }
    "
    :before-close="
      () => {
        if (customerFormStore.isFormDataDifferent()) {
          customerConfirmUnsave();
          return false;
        } else {
          fetchListCustomer();
          customerFormState.branchIndex = -1;
          customerFormStore.resetForm(true);
        }
        return false;
      }
    "
  >
    <div class="column full-height">
      <div
        :class="{
          'q-mx-lg q-my-md': $q.screen.gt.sm,
          'q-mx-md q-my-sm': !$q.screen.gt.sm,
        }"
      >
        <ProfileBanner
          v-if="customerFormData.customerBranch !== undefined"
          :prefix="customerFormData.registeredBranchId"
          :active="customerFormData.status !== 'INACTIVE'"
          hide-fade
          use-toggle
          v-model:toggle-status="customerFormData.status"
          :toggle-title="$t('status.title')"
          :fallback-cover="`/images/customer-${customerFormData.customerType}-banner-bg.jpg`"
          :img="
            `${baseUrl}/customer/${customerFormState.editCustomerId}/image/${customerFormData.selectedImage}`.concat(
              refreshImageState ? `?ts=${Date.now()}` : '',
            ) || null
          "
          :fallback-img="`/images/customer-${customerFormData.customerType}-avartar-${customerFormData.customerType === 'PERS' ? customerFormData.customerBranch[0]?.gender : 'male'}.png`"
          :color="`hsla(var(--${customerFormData.customerType === 'PERS' ? 'teal-10-hsl' : 'violet-11-hsl'})/1)`"
          :bg-color="`hsla(var(--${customerFormData.customerType === 'PERS' ? 'teal-10-hsl' : 'violet-11-hsl'})/0.1)`"
          :icon="
            customerFormData.customerType === 'PERS'
              ? 'mdi-account-plus-outline'
              : 'mdi-office-building-outline'
          "
          :title="
            customerFormData.customerType === 'PERS'
              ? `${customerFormData.customerBranch[0]?.firstName} ${customerFormData.customerBranch[0]?.lastName}`
              : customerFormData.customerBranch[0]?.registerName
          "
          :caption="
            customerFormData.customerType === 'PERS'
              ? `${customerFormData.customerBranch[0]?.firstNameEN} ${customerFormData.customerBranch[0]?.lastNameEN}`
              : customerFormData.customerBranch[0]?.registerNameEN
          "
          @view="
            () => {
              customerFormState.imageDialog = true;
              customerFormState.isImageEdit = false;
            }
          "
          @edit="
            customerFormState.imageDialog = customerFormState.isImageEdit = true
          "
          @update:toggle-status="
            async (v) => {
              if (!customerFormState.editCustomerId) return;
              await triggerChangeStatus(customerFormState.editCustomerId, v);
            }
          "
        />
      </div>

      <div
        style="flex: 1; width: 100%; overflow-y: auto"
        class="column"
        id="customer-form"
        :class="{
          'q-px-lg q-pb-lg': $q.screen.gt.sm,
          'q-px-md q-pb-sm': !$q.screen.gt.sm,
        }"
      >
        <div class="col bg-red surface-1 rounded bordered row">
          <div class="col full-height scroll" v-if="$q.screen.gt.sm">
            <div class="q-py-md q-pl-md q-pr-sm">
              <SideMenu
                :menu="[
                  {
                    name: $t('form.field.basicInformation'),
                    anchor: 'form-basic-info-customer',
                  },
                  {
                    name: $t('customer.form.group.branch'),
                    anchor: 'form-branch-customer-branch',
                    useBtn: true,
                  },

                  ...(customerFormData.customerBranch?.map((v, i) => ({
                    name:
                      i === 0
                        ? $t('customer.form.headQuarters.title')
                        : $t('customer.form.branch.title', {
                            name: i,
                          }),
                    anchor: `form-branch-customer-no-${i}`,
                    sub: true,
                  })) || []),
                ]"
                background="transparent"
                :active="{
                  background: 'hsla(var(--blue-6-hsl) / .2)',
                  foreground: 'var(--blue-6)',
                }"
                scroll-element="#customer-form-content"
              >
                <template v-slot:btn-form-branch-customer-branch>
                  <q-btn
                    dense
                    flat
                    icon="mdi-plus"
                    size="sm"
                    rounded
                    padding="0px 0px"
                    style="color: var(--stone-9)"
                    @click.stop="customerFormStore.addCurrentCustomerBranch()"
                    v-if="
                      customerFormState.branchIndex === -1 &&
                      !!customerFormState.editCustomerId &&
                      customerFormState.dialogType !== 'create'
                    "
                    :disabled="!customerFormState.readonly"
                  />
                </template>
              </SideMenu>
            </div>
          </div>

          <div
            class="col-12 col-md-10"
            :class="{
              'q-py-md q-pr-md ': $q.screen.gt.sm,
              'q-py-md q-px-lg': !$q.screen.gt.sm,
            }"
            id="customer-form-content"
            style="height: 100%; max-height: 100%; overflow-y: auto"
          >
            <EmployerFormBasicInfo
              v-if="
                customerFormData.customerBranch !== undefined &&
                customerFormData.customerBranch.length > 0
              "
              :readonly="
                (customerFormState.dialogType === 'edit' &&
                  customerFormState.readonly === true) ||
                customerFormState.dialogType === 'info'
              "
              :hide-action="customerFormData.status === 'INACTIVE'"
              :action-disabled="customerFormState.branchIndex !== -1"
              id="form-basic-info-customer"
              :onCreate="customerFormState.dialogType === 'create'"
              @edit="
                (customerFormState.dialogType = 'edit'),
                  (customerFormState.readonly = false)
              "
              @cancel="() => customerFormUndo(false)"
              @delete="
                customerFormState.editCustomerId &&
                  deleteCustomerById(customerFormState.editCustomerId)
              "
              :customer-type="customerFormData.customerType"
              v-model:registered-branch-id="customerFormData.registeredBranchId"
              v-model:customer-name="customerNameInfo"
              v-model:register-name="
                customerFormData.customerBranch[0].registerName
              "
              v-model:citizen-id="customerFormData.customerBranch[0].citizenId"
              v-model:legal-person-no="
                customerFormData.customerBranch[0].legalPersonNo
              "
              v-model:business-type="
                customerFormData.customerBranch[0].businessType
              "
              v-model:job-position="
                customerFormData.customerBranch[0].jobPosition
              "
              v-model:telephone-no="
                customerFormData.customerBranch[0].telephoneNo
              "
              v-model:branch-options="registerAbleBranchOption"
            />

            <div class="row q-col-gutter-sm" id="form-branch-customer-branch">
              <div
                class="col-12 text-weight-bold text-body1 row items-center q-mt-lg"
              >
                <q-icon
                  flat
                  size="xs"
                  class="q-pa-sm rounded q-mr-xs"
                  color="info"
                  name="mdi-briefcase-outline"
                  style="background-color: var(--surface-3)"
                />
                <span>{{ $t('customer.form.group.branch') }}</span>
              </div>

              <template
                v-for="(_, idx) in customerFormData.customerBranch"
                :key="idx"
              >
                <q-form
                  class="full-width q-mb-xl"
                  v-if="customerFormData.customerBranch"
                  greedy
                  @submit.prevent="
                    async () => {
                      if (!customerFormData.customerBranch) return;
                      if (!customerFormState.editCustomerId) return;

                      if (customerFormData.customerType === 'PERS') {
                        tabFieldRequired.main = [
                          'citizenId',
                          'namePrefix',
                          'firstName',
                          'firstNameEN',
                          'lastName',
                          'lastNameEN',
                          'gender',
                          'birthDate',
                        ];
                      }
                      if (customerFormData.customerType === 'CORP') {
                        tabFieldRequired.main = [
                          'legalPersonNo',
                          'registerName',
                        ];
                      }

                      let tapIsUndefined = validateTabField(
                        customerFormData.customerBranch?.[idx],
                        tabFieldRequired,
                      );

                      if (tapIsUndefined.length > 0) {
                        return dialog({
                          color: 'warning',
                          icon: 'mdi-alert',
                          title: t('dialog.title.incompleteDataEntry'),
                          actionText: t('ok'),
                          persistent: true,
                          message: t('dialog.message.incompleteDataEntry', {
                            tap: `${tapIsUndefined.map((v: string) => t(`customerBranch.tab.${v}`)).join(', ')}`,
                          }),
                          action: async () => {
                            return;
                          },
                        });
                      }
                      if (!customerFormData.customerBranch[idx].id) {
                        await customerStore.createBranch({
                          ...customerFormData.customerBranch[idx],
                          customerId: customerFormState.editCustomerId,
                          id: undefined,
                        });
                      } else {
                        await customerStore.editBranchById(
                          customerFormData.customerBranch[idx].id || '',
                          {
                            ...customerFormData.customerBranch[idx],
                            id: undefined,
                          },
                        );
                      }

                      customerFormData.customerBranch[idx].file?.forEach(
                        async (v) => {
                          if (!v.file) return;

                          const ext = v.file.name.split('.').at(-1);
                          let filename = v.group + '-' + new Date().getTime();
                          if (ext) filename += `.${ext}`;

                          const res = await customerStore.putAttachment({
                            branchId:
                              customerFormData.customerBranch?.[idx].id || '',
                            file: v.file,
                            filename,
                          });

                          if (res) {
                            await customerFormStore.assignFormData(
                              customerFormState.editCustomerId,
                            );
                          }
                        },
                      );

                      await customerFormStore.assignFormData(
                        customerFormState.editCustomerId,
                      );

                      customerFormStore.resetForm();
                    }
                  "
                >
                  <EmployerFormBranch
                    prefix-id="info"
                    v-if="!!customerFormState.editCustomerId"
                    :index="idx"
                    :hide-action="customerFormData.status === 'INACTIVE'"
                    v-model:customer="customerFormData"
                    v-model:customer-branch="
                      customerFormData.customerBranch[idx]
                    "
                    :customer-type="customerFormData.customerType"
                    :customer-name="`${customerFormData.firstName} ${customerFormData.lastName}`"
                    :action-disabled="
                      !customerFormState.readonly ||
                      (customerFormState.branchIndex !== -1 &&
                        customerFormState.branchIndex !== idx)
                    "
                    :readonly="customerFormState.branchIndex !== idx"
                    @edit="() => (customerFormState.branchIndex = idx)"
                    @cancel="() => customerFormUndo(false)"
                    @delete="
                      async () => {
                        if (!!customerFormData.customerBranch?.[idx].id) {
                          const action = await deleteCustomerBranchById(
                            customerFormData.customerBranch[idx].id || '',
                          );
                          if (action) {
                            await customerFormStore.assignFormData(
                              customerFormState.editCustomerId,
                            );
                          }
                          customerFormStore.resetForm();
                        }
                      }
                    "
                    @save="() => {}"
                  />
                </q-form>
              </template>
            </div>
          </div>
        </div>
      </div>
    </div>
  </DrawerInfo>

  <!-- ลูกจ้าง edit employee -->
  <DrawerInfo
    v-if="!!employeeFormState.currentEmployee"
    hide-action
    v-model:drawer-open="employeeFormState.drawerModal"
    :close="
      () => {
        resetScrollBar('drawer-employee-form-content');
      }
    "
    :title="
      employeeFormState.currentEmployee
        ? $i18n.locale === 'eng'
          ? `${employeeFormState.currentEmployee.firstNameEN} ${employeeFormState.currentEmployee.lastNameEN}`
          : `${employeeFormState.currentEmployee.firstName} ${employeeFormState.currentEmployee.lastName}`
        : '-'
    "
    :badge-class="
      currentFromDataEmployee.gender === 'male'
        ? 'app-bg-male text-white'
        : currentFromDataEmployee.gender === 'female'
          ? 'app-bg-female text-white'
          : ''
    "
    :submit="
      async () => {
        if (employeeFormState.currentTab === 'personalInfo') {
          await employeeFormStore.submitPersonal();
          employeeFormState.dialogType = 'info';
          employeeFormState.isEmployeeEdit = false;
        }

        if (employeeFormState.currentTab === 'passport') {
          await employeeFormStore.submitPassport();
        }

        if (employeeFormState.currentTab === 'visa') {
          await employeeFormStore.submitVisa();
        }

        if (employeeFormState.currentTab === 'healthCheck') {
          await employeeFormStore.submitHealthCheck();
        }

        if (employeeFormState.currentTab === 'workHistory') {
          await employeeFormStore.submitWorkHistory();
        }

        if (employeeFormState.currentTab === 'other') {
          await employeeFormStore.submitOther();
        }
        await fetchListEmployee();

        employeeFormState.isEmployeeEdit = false;
      }
    "
    :before-close="
      () => {
        if (employeeFormStore.isFormDataDifferent()) {
          employeeConfirmUnsave();
          return true;
        }

        employeeFormState.currentTab = 'personalInfo';
        return false;
      }
    "
  >
    <div class="column full-height">
      <div
        :class="{
          'q-mx-lg q-my-md': $q.screen.gt.sm,
          'q-mx-md q-my-sm': !$q.screen.gt.sm,
        }"
      >
        <ProfileBanner
          :prefix="employeeFormState.currentEmployee.firstName"
          hideFade
          @view="
            () => {
              employeeFormState.imageDialog = true;
              employeeFormState.isImageEdit = false;
            }
          "
          @edit="
            employeeFormState.imageDialog = employeeFormState.isImageEdit = true
          "
          @update:toggle-status="
            (v) => {
              if (currentFromDataEmployee.id !== undefined)
                triggerChangeStatus(currentFromDataEmployee.id, v);
            }
          "
          :active="currentFromDataEmployee.status !== 'INACTIVE'"
          :use-toggle="currentTab === 'employee'"
          color="white"
          icon="mdi-account-outline"
          :bg-color="
            employeeFormState.profileUrl
              ? 'white'
              : 'linear-gradient(135deg, rgba(43,137,223,1) 0%, rgba(230,51,81,1) 100%)'
          "
          v-model:current-tab="employeeFormState.currentTab"
          v-model:toggle-status="currentFromDataEmployee.status"
          fallback-cover="/images/employee-banner.png"
          :title="
            employeeFormState.currentEmployee
              ? $i18n.locale === 'eng'
                ? `${employeeFormState.currentEmployee.firstNameEN} ${employeeFormState.currentEmployee.lastNameEN}`
                : `${employeeFormState.currentEmployee.firstName} ${employeeFormState.currentEmployee.lastName}`
              : '-'
          "
          :caption="currentFromDataEmployee.code"
          :img="
            `${baseUrl}/employee/${currentFromDataEmployee.id}/image/${currentFromDataEmployee.selectedImage}`.concat(
              refreshImageState ? `?ts=${Date.now()}` : '',
            ) || null
          "
          :fallbackImg="'/images/employee-avatar.png'"
          :tabs-list="[
            {
              name: 'personalInfo',
              label: 'customerEmployee.form.group.personalInfo',
            },
            {
              name: 'passport',
              label: 'customerEmployee.fileType.passport',
            },
            {
              name: 'visa',
              label: 'customerEmployee.form.group.visa',
            },
            {
              name: 'healthCheck',
              label: 'customerEmployee.form.group.healthCheck',
            },
            {
              name: 'workHistory',
              label: 'customerEmployee.form.group.workHistory',
            },
            { name: 'other', label: 'customerEmployee.form.group.other' },
          ]"
          :toggle-title="$t('status.title')"
        />
      </div>
      <div
        style="flex: 1; width: 100%; overflow-y: auto"
        class="column relative-position"
        id="drawer-employee-form"
        :class="{
          'q-px-lg q-pb-lg': $q.screen.gt.sm,
          'q-px-md q-pb-sm': !$q.screen.gt.sm,
        }"
      >
        <div class="col bg-red surface-1 rounded bordered row">
          <div class="col full-height scroll" v-if="$q.screen.gt.sm">
            <div class="q-py-md q-pl-md q-pr-sm">
              <SideMenu
                :menu="
                  [
                    {
                      name: $t('form.field.basicInformation'),
                      anchor: 'drawer-form-information',
                      tab: 'personalInfo',
                    },
                    {
                      name: $t('customerEmployee.form.group.personalInfo'),
                      anchor: 'drawer-form-personal',
                      tab: 'personalInfo',
                    },
                    {
                      name: $t('form.address'),
                      anchor: 'drawer-form-personal-address',
                      tab: 'personalInfo',
                    },

                    {
                      name: $t('general.uploadFile'),
                      anchor: 'drawer-upload-file',
                      tab: 'personalInfo',
                    },

                    {
                      name: $t('customerEmployee.form.group.passport'),
                      anchor: 'drawer-passport',
                      tab: 'passport',
                      useBtn:
                        currentFromDataEmployee.employeePassport?.filter(
                          (item) => {
                            if (item.id === undefined) {
                              return true;
                            }
                            return false;
                          },
                        ).length === 0 &&
                        employeeFormState.currentIndexPassport === -1
                          ? true
                          : false,
                    },
                    ...(currentFromDataEmployee.employeePassport?.map(
                      (v, i) => ({
                        name: dateFormat(v.expireDate),
                        anchor: `drawer-employee-employeePassport-${i}`,
                        tab: 'passport',
                        sub: true,
                      }),
                    ) || []),

                    {
                      name: $t('customerEmployee.form.group.visa'),
                      anchor: 'drawer-visa',
                      tab: 'visa',
                      useBtn:
                        currentFromDataEmployee.employeeVisa?.filter((item) => {
                          if (item.id === undefined) {
                            return true;
                          }
                          return false;
                        }).length === 0 &&
                        employeeFormState.currentIndexVisa === -1
                          ? true
                          : false,
                    },

                    ...(currentFromDataEmployee.employeeVisa?.map((v, i) => ({
                      name: dateFormat(v.expireDate),
                      anchor: `drawer-employee-visa-${i}`,
                      tab: 'visa',
                      sub: true,
                    })) || []),

                    {
                      name: $t('customerEmployee.form.group.visa'),
                      anchor: 'drawer-employee-checkup',
                      tab: 'healthCheck',
                      useBtn:
                        currentFromDataEmployee.employeeCheckup?.filter(
                          (item) => {
                            if (item.id === undefined) {
                              return true;
                            }
                            return false;
                          },
                        ).length === 0 &&
                        employeeFormState.currentIndexCheckup === -1
                          ? true
                          : false,
                    },

                    ...(currentFromDataEmployee.employeeCheckup?.map(
                      (_v, i) => ({
                        name: $t('general.times', { number: i + 1 }),
                        anchor: `drawer-employee-checkup-${i}`,
                        tab: 'healthCheck',
                      }),
                    ) || []),

                    {
                      name: $t('customerEmployee.form.group.workHistory'),
                      anchor: 'drawer-employee-work-history',
                      tab: 'workHistory',
                      useBtn:
                        currentFromDataEmployee.employeeWork?.filter((item) => {
                          if (item.id === undefined) {
                            return true;
                          }
                          return false;
                        }).length === 0 &&
                        employeeFormState.currentIndexWorkHistory === -1
                          ? true
                          : false,
                    },

                    ...(currentFromDataEmployee.employeeWork?.map((_v, i) => ({
                      name: $t('general.times', { number: i + 1 }),
                      anchor: `drawer-employee-work-history-${i}`,
                      tab: 'workHistory',
                    })) || []),

                    {
                      name: $t('customerEmployee.form.group.family'),
                      anchor: 'drawer-other',
                      tab: 'other',
                    },
                  ].filter((v) => v.tab === employeeFormState.currentTab)
                "
                background="transparent"
                :active="{
                  background: 'hsla(var(--blue-6-hsl) / .2)',
                  foreground: 'var(--blue-6)',
                }"
                scroll-element="#drawer-employee-form-content"
              >
                <template v-slot:btn-drawer-passport>
                  <q-btn
                    v-if="currentTab === 'employee'"
                    id="form-add-passport"
                    dense
                    flat
                    icon="mdi-plus"
                    size="sm"
                    rounded
                    padding="0px 0px"
                    style="color: var(--stone-9)"
                    @click.stop="employeeFormStore.addPassport()"
                  />
                </template>

                <template v-slot:btn-drawer-visa>
                  <q-btn
                    v-if="currentTab === 'employee'"
                    id="form-add-visa"
                    dense
                    flat
                    icon="mdi-plus"
                    size="sm"
                    rounded
                    style="color: var(--stone-9)"
                    @click.stop="employeeFormStore.addVisa()"
                  />
                </template>

                <template v-slot:btn-drawer-employee-checkup>
                  <q-btn
                    v-if="currentTab === 'employee'"
                    id="form-add-checkup"
                    dense
                    flat
                    icon="mdi-plus"
                    size="sm"
                    rounded
                    style="color: var(--stone-9)"
                    @click.stop="employeeFormStore.addCheckup()"
                  />
                </template>

                <template v-slot:btn-drawer-employee-work-history>
                  <q-btn
                    v-if="currentTab === 'employee'"
                    id="form-add-work-history"
                    dense
                    flat
                    icon="mdi-plus"
                    size="sm"
                    rounded
                    style="color: var(--stone-9)"
                    @click.stop="employeeFormStore.addWorkHistory()"
                  />
                </template>
              </SideMenu>
            </div>
          </div>
          <div
            class="col-12 col-md-10 row"
            :class="{
              'q-py-md q-pr-md ': $q.screen.gt.sm,
              'q-py-md q-px-lg': !$q.screen.gt.sm,
            }"
            id="drawer-employee-form-content"
            style="height: 100%; overflow-y: auto"
          >
            <template v-if="employeeFormState.currentTab === 'personalInfo'">
              <div
                class="rounded row q-py-sm q-mx-lg q-px-md"
                style="position: absolute; z-index: 999; right: 0; top: 0"
                v-if="
                  currentTab === 'employee' &&
                  currentFromDataEmployee.status !== 'INACTIVE'
                "
              >
                <div class="surface-1 row rounded">
                  <UndoButton
                    v-if="employeeFormState.isEmployeeEdit"
                    id="btn-info-basic-undo"
                    icon-only
                    @click="
                      () => {
                        employeeFormStore.resetFormDataEmployee();
                        employeeFormState.isEmployeeEdit = false;
                        employeeFormState.dialogType = 'info';
                      }
                    "
                    type="button"
                  />
                  <SaveButton
                    v-if="employeeFormState.isEmployeeEdit"
                    id="btn-info-basic-save"
                    icon-only
                    type="submit"
                  />
                  <EditButton
                    v-if="!employeeFormState.isEmployeeEdit"
                    id="btn-info-basic-edit"
                    icon-only
                    @click="
                      () => {
                        employeeFormState.isEmployeeEdit = true;
                        employeeFormState.dialogType = 'edit';
                      }
                    "
                    type="button"
                  />
                  <DeleteButton
                    v-if="!employeeFormState.isEmployeeEdit"
                    id="btn-info-basic-delete"
                    icon-only
                    @click="
                      () =>
                        deleteEmployeeById({ id: currentFromDataEmployee.id })
                    "
                    type="button"
                  />
                </div>
              </div>
              <BasicInformation
                no-action
                id="drawer-form-information"
                prefix-id="drawer-info-employee"
                dense
                outlined
                title="form.field.basicInformation"
                :readonly="!employeeFormState.isEmployeeEdit"
                :employee-owner-option="employeeStore.ownerOption"
                v-model:customer-branch="
                  employeeFormState.formDataEmployeeOwner
                "
                v-model:employee-id="employeeFormState.currentEmployeeCode"
                v-model:nrc-no="currentFromDataEmployee.nrcNo"
                v-model:code="currentFromDataEmployee.code"
                @filter-owner-branch="
                  employeeFormStore.employeeFilterOwnerBranch
                "
                class="q-mb-xl"
              />
              <FormPerson
                id="drawer-form-personal"
                prefix-id="drawer-info-employee"
                dense
                outlined
                employee
                separator
                title="customerEmployee.form.group.personalInfo"
                :readonly="!employeeFormState.isEmployeeEdit"
                v-model:prefix-name="currentFromDataEmployee.namePrefix"
                v-model:first-name="currentFromDataEmployee.firstName"
                v-model:last-name="currentFromDataEmployee.lastName"
                v-model:first-name-en="currentFromDataEmployee.firstNameEN"
                v-model:last-name-en="currentFromDataEmployee.lastNameEN"
                v-model:mid-name="currentFromDataEmployee.middleName"
                v-model:mid-name-en="currentFromDataEmployee.middleNameEN"
                v-model:gender="currentFromDataEmployee.gender"
                v-model:birth-date="currentFromDataEmployee.dateOfBirth"
                v-model:nationality="currentFromDataEmployee.nationality"
                class="q-mb-xl"
              />
              <AddressForm
                id="drawer-form-personal-address"
                employee
                v-model:address="currentFromDataEmployee.address"
                v-model:address-en="currentFromDataEmployee.addressEN"
                v-model:moo="currentFromDataEmployee.moo"
                v-model:moo-en="currentFromDataEmployee.mooEN"
                v-model:soi="currentFromDataEmployee.soi"
                v-model:soi-en="currentFromDataEmployee.soiEN"
                v-model:street="currentFromDataEmployee.street"
                v-model:street-en="currentFromDataEmployee.streetEN"
                v-model:province-id="currentFromDataEmployee.provinceId"
                v-model:district-id="currentFromDataEmployee.districtId"
                v-model:sub-district-id="currentFromDataEmployee.subDistrictId"
                v-model:same-with-employer="
                  employeeFormState.formDataEmployeeSameAddr
                "
                :readonly="!employeeFormState.isEmployeeEdit"
                prefix-id="drawer-info-personnel"
                dense
                class="q-mb-xl"
              />

              <div class="row" id="drawer-upload-file">
                <div class="col-12 q-pb-sm text-weight-bold text-body1">
                  <q-icon
                    flat
                    size="xs"
                    class="q-pa-sm rounded q-mr-xs"
                    color="info"
                    name="mdi-upload"
                    style="background-color: var(--surface-3)"
                  />
                  {{ $t(`general.uploadFile`) }}
                </div>
              </div>
              <UploadFileGroup
                v-model:current-id="currentFromDataEmployee.id"
                v-model="currentFromDataEmployee.file"
                hide-action
                :readonly="!employeeFormState.isEmployeeEdit"
                :group-list="uploadFileListEmployee"
                :menu="uploadFileListEmployee"
                :columns="columnsAttachment"
                @submit="
                  async (group, allMeta) => {
                    if (allMeta === undefined) return;

                    if (group === 'passport') {
                      const fullName = allMeta['full_name'].split(' ');
                      let tempValue: {
                        oldData: { nameField: string; value: string }[];
                        newData: { nameField: string; value: string }[];
                      } = { oldData: [], newData: [] };

                      if (
                        currentFromDataEmployee.gender !== '' &&
                        currentFromDataEmployee.gender !== allMeta['sex']
                      ) {
                        tempValue.oldData.push({
                          nameField: $t('form.gender'),
                          value: $t(
                            `general.${currentFromDataEmployee.gender}`,
                          ),
                        });
                        tempValue.newData.push({
                          nameField: $t('form.gender'),
                          value: $t(`general.${allMeta['sex']}`),
                        });
                      }

                      if (currentFromDataEmployee.firstName !== '') {
                        tempValue.oldData.push({
                          nameField: $t('personnel.form.firstName'),
                          value: currentFromDataEmployee.firstName,
                        });
                        tempValue.newData.push({
                          nameField: $t('personnel.form.firstName'),
                          value: fullName[0],
                        });
                      }

                      if (currentFromDataEmployee.lastName !== '') {
                        tempValue.oldData.push({
                          nameField: $t('personnel.form.lastName'),
                          value: currentFromDataEmployee.lastName,
                        });
                        tempValue.newData.push({
                          nameField: $t('personnel.form.lastName'),
                          value: fullName[1],
                        });
                      }

                      if (currentFromDataEmployee.nationality !== '') {
                        tempValue.oldData.push({
                          nameField: $t('general.nationality'),
                          value: currentFromDataEmployee.nationality || '',
                        });
                        tempValue.newData.push({
                          nameField: $t('general.nationality'),
                          value: allMeta['nationality'],
                        });
                      }

                      dialogCheckData({
                        action: async () => {
                          currentFromDataEmployee.gender = allMeta['sex'];
                          currentFromDataEmployee.firstName = fullName[0];
                          currentFromDataEmployee.lastName = fullName[1];
                          currentFromDataEmployee.nationality =
                            allMeta['nationality'];
                        },
                        checkData: () => {
                          return tempValue;
                        },
                        cancel: () => {
                          if (!currentFromDataEmployee.gender) {
                            currentFromDataEmployee.gender = allMeta['gender'];
                          }
                          if (!currentFromDataEmployee.firstName) {
                            currentFromDataEmployee.firstName = fullName[0];
                          }
                          if (!currentFromDataEmployee.firstName) {
                            currentFromDataEmployee.firstName = fullName[0];
                          }
                          if (!currentFromDataEmployee.lastName) {
                            currentFromDataEmployee.lastName = fullName[1];
                          }

                          if (!currentFromDataEmployee.nationality) {
                            currentFromDataEmployee.nationality =
                              allMeta['nationality'];
                          }
                        },
                      });
                    }
                  }
                "
                :ocr="
                  async (group, file) => {
                    if (group === 'passport') {
                      mrz = await runOcr(file, parseResultMRZ);

                      if (mrz) {
                        const mapMrz = Object.entries(mrz.result || {}).map(
                          ([key, value]) => ({
                            name: key,
                            value: value,
                          }),
                        );

                        const tempValue = {
                          status: true,
                          group,
                          meta: mapMrz,
                        };

                        return tempValue;
                      }
                    }
                    if (group === 'visa') {
                      const res = await ocrStore.sendOcr({
                        file: file,
                        category: group,
                      });

                      if (res) {
                        const tempValue = {
                          status: true,
                          group,
                          meta: res.fields,
                        };

                        return tempValue;
                      }
                    }

                    return { status: true, group, meta: [] };
                  }
                "
                :auto-save="currentFromDataEmployee.id !== ''"
                :download="
                  (obj) => {
                    if (obj.group !== 'attachment') {
                      employeeStore.getFile({
                        parentId: currentFromDataEmployee.id || '',
                        group: obj.group,
                        fileId: obj._meta.id,
                        download: true,
                      });
                    } else {
                      employeeStore.getAttachment({
                        parentId: currentFromDataEmployee.id || '',
                        name: obj._meta.name,
                        download: true,
                      });
                    }
                  }
                "
                :delete-item="
                  async (obj) => {
                    let status: boolean = false;
                    const res = await employeeStore.delMeta({
                      parentId: currentFromDataEmployee.id || '',
                      group: obj.group,
                      metaId: obj._meta.id,
                    });

                    if (res) {
                      status = true;
                    }

                    await employeeFormStore.assignFormDataEmployee(
                      currentFromDataEmployee.id,
                    );

                    return status;
                  }
                "
                :save="
                  async (
                    group: 'passport' | 'visa' | 'attachment',
                    _meta: any,
                    file: File | undefined,
                  ) => {
                    let status: boolean = false;
                    if (group !== 'attachment') {
                      if (file !== undefined && currentFromDataEmployee.id) {
                        const res = await employeeStore.postMeta({
                          parentId: currentFromDataEmployee.id || '',
                          group,
                          meta: _meta,
                          file,
                        });

                        if (res) {
                          status = true;
                        }
                      } else {
                        const {
                          id,
                          employeeId,
                          createdAt,
                          updatedAt,
                          ...payload
                        } = _meta;

                        const res = await employeeStore.putMeta({
                          parentId: currentFromDataEmployee.id || '',
                          group,
                          metaId: _meta.id,
                          meta: payload,
                          file,
                        });
                        if (res) {
                          status = true;
                        }
                      }
                    } else {
                      if (file !== undefined) {
                        await employeeStore.uploadAttachment(
                          currentFromDataEmployee.id || '',
                          file,
                          file.name,
                        );
                        status = true;
                      }
                    }
                    await employeeFormStore.assignFormDataEmployee(
                      currentFromDataEmployee.id,
                    );
                    return status;
                  }
                "
                :get-file-list="
                  async (group: 'passport' | 'visa' | 'attachment') => {
                    if (
                      !!currentFromDataEmployee.id &&
                      group !== 'attachment'
                    ) {
                      const resMeta = await employeeStore.getMetaList({
                        parentId: currentFromDataEmployee.id,
                        group,
                      });

                      const tempValue = resMeta.map(async (i: any) => {
                        return {
                          _meta: { ...i },
                          name: `${group}-${dateFormat(i.expireDate)}` || '',
                          group: group,
                          url: await employeeStore.getFile({
                            parentId: currentFromDataEmployee.id || '',
                            group,
                            fileId: i.id,
                          }),
                          file: undefined,
                        };
                      });

                      return await waitAll(tempValue);
                    } else {
                      const res = await employeeStore.listAttachment({
                        parentId: currentFromDataEmployee.id || '',
                      });

                      const tempValue = (res as string[]).map(
                        async (i: any) => {
                          return {
                            _meta: { id: i, name: i },
                            name: i || '',
                            group: group,
                            url: await employeeStore.getAttachment({
                              parentId: currentFromDataEmployee.id || '',
                              name: i,
                            }),
                            file: undefined,
                          };
                        },
                      );

                      return await waitAll(tempValue);
                    }
                  }
                "
              >
                <template #form="{ mode, meta, isEdit }">
                  <FormCitizen
                    v-if="mode === 'citizen' && meta"
                    orc
                    ra
                    :readonly="!isEdit"
                    v-model:citizen-id="meta.citizenId"
                    v-model:birth-date="meta.birthDate"
                    v-model:first-name="meta.firstName"
                    v-model:first-name-en="meta.firstNameEN"
                    v-model:last-name="meta.lastName"
                    v-model:last-name-en="meta.lastNameEN"
                    v-model:address="meta.address"
                  />

                  <FormEmployeePassport
                    v-if="mode === 'passport' && meta"
                    prefix-id="drawer-info-employee"
                    id="form-passport"
                    dense
                    outlined
                    separator
                    ocr
                    :title="$t('customerEmployee.form.group.passport')"
                    :readonly="!isEdit"
                    v-model:birth-country="meta.birthCountry"
                    v-model:previous-passportRef="meta.previousPassportRef"
                    v-model:issue-place="meta.issuePlace"
                    v-model:issue-country="meta.issueCountry"
                    v-model:issue-date="meta.issueDate"
                    v-model:type="meta.type"
                    v-model:expire-date="meta.expireDate"
                    v-model:birth-date="meta.birthDate"
                    v-model:worker-status="meta.workerStatus"
                    v-model:nationality="meta.nationality"
                    v-model:gender="meta.gender"
                    v-model:last-name-en="meta.lastNameEN"
                    v-model:last-name="meta.lastName"
                    v-model:middle-name-en="meta.middleNameEN"
                    v-model:middle-name="meta.middleName"
                    v-model:first-name-en="meta.firstNameEN"
                    v-model:first-name="meta.firstName"
                    v-model:name-prefix="meta.namePrefix"
                    v-model:passport-number="meta.number"
                  ></FormEmployeePassport>
                  <FormEmployeeVisa
                    v-if="mode === 'visa' && meta"
                    prefix-id="drawer-info-employee"
                    id="form-visa"
                    ocr
                    dense
                    outlined
                    :title="$t('customerEmployee.form.group.visa')"
                    :readonly="!isEdit"
                    v-model:arrival-at="meta.arrivalAt"
                    v-model:arrival-tm-no="meta.arrivalTMNo"
                    v-model:arrival-tm="meta.arrivalTM"
                    v-model:mrz="meta.mrz"
                    v-model:entry-count="meta.entryCount"
                    v-model:issue-place="meta.issuePlace"
                    v-model:issue-country="meta.issueCountry"
                    v-model:issueDate="meta.issueDate"
                    v-model:type="meta.type"
                    v-model:expire-date="meta.expireDate"
                    v-model:visa-issue-date="meta.issueDate"
                    v-model:visa-expiry-date="meta.expireDate"
                    v-model:remark="meta.remark"
                    v-model:worker-type="meta.workerType"
                    v-model:number="meta.number"
                  />

                  <NoticeJobEmployment v-if="mode === 'noticeJobEmployment'" />
                </template>
              </UploadFileGroup>
            </template>

            <template v-if="employeeFormState.currentTab === 'passport'">
              <div class="q-gutter-sm full-width">
                <div class="col-12 q-pb-sm text-weight-bold text-body1">
                  <q-icon
                    flat
                    size="xs"
                    class="q-pa-sm rounded q-mr-xs"
                    color="info"
                    name="mdi-passport"
                    style="background-color: var(--surface-3)"
                  />
                  {{ $t('customerEmployee.form.group.passport') }}
                </div>

                <template
                  v-for="(
                    value, index
                  ) in currentFromDataEmployee.employeePassport"
                >
                  <FormEmployeePassport
                    v-if="value !== undefined"
                    prefix-id="drawer-info-employee"
                    id="form-passport"
                    hide-title
                    dense
                    outlined
                    separator
                    :title="$t('customerEmployee.form.group.passport')"
                    :readonly="employeeFormState.currentIndexPassport !== index"
                    :full-name="
                      employeeFormState.currentIndexPassport !== index
                    "
                    v-model:birth-country="value.birthCountry"
                    v-model:previous-passportRef="value.previousPassportRef"
                    v-model:issue-place="value.issuePlace"
                    v-model:issue-country="value.issueCountry"
                    v-model:issue-date="value.issueDate"
                    v-model:type="value.type"
                    v-model:expire-date="value.expireDate"
                    v-model:birth-date="value.birthDate"
                    v-model:worker-status="value.workerStatus"
                    v-model:nationality="value.nationality"
                    v-model:gender="value.gender"
                    v-model:last-name-en="value.lastNameEN"
                    v-model:last-name="value.lastName"
                    v-model:middle-name-en="value.middleNameEN"
                    v-model:middle-name="value.middleName"
                    v-model:first-name-en="value.firstNameEN"
                    v-model:first-name="value.firstName"
                    v-model:name-prefix="value.namePrefix"
                    v-model:passport-number="value.number"
                  >
                    <template v-slot:expiryDate>
                      {{ $t('general.expirationDate') }} :
                      {{ dateFormat(value.expireDate) }}
                      <ExpirationDate
                        v-if="value.id !== undefined"
                        :expiration-date="value.expireDate"
                      />
                    </template>

                    <template v-slot:button>
                      <div
                        class="surface-1 row rounded"
                        style="min-height: 35px"
                      >
                        <UndoButton
                          v-if="
                            employeeFormState.isEmployeeEdit &&
                            !(employeeFormState.currentIndexPassport === -1) &&
                            employeeFormState.currentIndexPassport === index
                          "
                          id="btn-info-basic-undo"
                          icon-only
                          @click="
                            () => {
                              employeeFormStore.resetFormDataEmployee();
                              employeeFormState.isEmployeeEdit = false;
                              employeeFormState.dialogType = 'info';
                              employeeFormState.currentIndexPassport = -1;
                            }
                          "
                          type="button"
                        />
                        <SaveButton
                          v-if="
                            (employeeFormState.isEmployeeEdit ||
                              value.id === undefined) &&
                            !(employeeFormState.currentIndexPassport === -1) &&
                            employeeFormState.currentIndexPassport === index
                          "
                          id="btn-info-basic-save"
                          icon-only
                          @click="
                            () => {
                              employeeFormState.currentIndexPassport = index;
                            }
                          "
                          type="submit"
                        />

                        <EditButton
                          v-if="
                            employeeFormState.currentIndexPassport === -1 ||
                            (!employeeFormState.isEmployeeEdit &&
                              value.id !== undefined &&
                              employeeFormState.currentIndexPassport === index)
                          "
                          id="btn-info-basic-edit"
                          icon-only
                          @click="
                            () => {
                              employeeFormState.currentIndexPassport = index;
                              employeeFormState.isEmployeeEdit = true;
                              employeeFormState.dialogType = 'edit';
                            }
                          "
                          type="button"
                        />
                        <DeleteButton
                          v-if="
                            employeeFormState.currentIndexPassport === -1 ||
                            (!employeeFormState.isEmployeeEdit &&
                              value.id !== undefined &&
                              !(
                                employeeFormState.currentIndexPassport === -1
                              ) &&
                              employeeFormState.currentIndexPassport === index)
                          "
                          id="btn-info-basic-delete"
                          icon-only
                          @click.stop="
                            () => {
                              deleteEmployeeById({ type: 'passport', index });
                            }
                          "
                          type="button"
                          :disabled="
                            !(employeeFormState.currentIndexPassport === -1) &&
                            !(employeeFormState.currentIndexPassport === index)
                          "
                        />
                      </div>
                    </template>
                  </FormEmployeePassport>
                </template>

                <div class="full-width flex flex-center">
                  <NoData
                    v-if="
                      currentFromDataEmployee.employeePassport?.length === 0
                    "
                  />
                </div>
              </div>
            </template>

            <template v-if="employeeFormState.currentTab === 'visa'">
              <div class="q-gutter-sm full-width">
                <div class="col-12 q-pb-sm text-weight-bold text-body1">
                  <q-icon
                    flat
                    size="xs"
                    class="q-pa-sm rounded q-mr-xs"
                    color="info"
                    name="mdi-passport"
                    style="background-color: var(--surface-3)"
                  />
                  {{ $t('customerEmployee.form.group.visa') }}
                </div>
                <FormEmployeeVisa
                  v-for="(value, index) in currentFromDataEmployee.employeeVisa"
                  prefix-id="drawer-info-employee"
                  id="form-visa"
                  dense
                  outlined
                  :title="$t('customerEmployee.form.group.visa')"
                  :readonly="employeeFormState.currentIndexVisa !== index"
                  hide-title
                  v-model:arrival-at="value.arrivalAt"
                  v-model:arrival-tm-no="value.arrivalTMNo"
                  v-model:arrival-tm="value.arrivalTM"
                  v-model:mrz="value.mrz"
                  v-model:entry-count="value.entryCount"
                  v-model:issue-place="value.issuePlace"
                  v-model:issue-country="value.issueCountry"
                  v-model:issueDate="value.issueDate"
                  v-model:type="value.type"
                  v-model:expire-date="value.expireDate"
                  v-model:visa-issue-date="value.issueDate"
                  v-model:visa-expiry-date="value.expireDate"
                  v-model:remark="value.remark"
                  v-model:worker-type="value.workerType"
                  v-model:number="value.number"
                >
                  <template v-slot:expiryDate>
                    {{ $t('general.expirationDate') }} :
                    {{ dateFormat(value.expireDate) }}
                    <ExpirationDate
                      v-if="value.id !== undefined"
                      :expiration-date="value.expireDate"
                    />
                  </template>

                  <template v-slot:button>
                    <div class="surface-1 row rounded" style="min-height: 35px">
                      <UndoButton
                        v-if="
                          employeeFormState.isEmployeeEdit &&
                          !(employeeFormState.currentIndexVisa === -1) &&
                          employeeFormState.currentIndexVisa === index
                        "
                        id="btn-info-basic-undo"
                        icon-only
                        @click="
                          () => {
                            employeeFormStore.resetFormDataEmployee();
                            employeeFormState.isEmployeeEdit = false;
                            employeeFormState.dialogType = 'info';
                            employeeFormState.currentIndexVisa = -1;
                          }
                        "
                        type="button"
                      />
                      <SaveButton
                        v-if="
                          (employeeFormState.isEmployeeEdit ||
                            value.id === undefined) &&
                          !(employeeFormState.currentIndexVisa === -1) &&
                          employeeFormState.currentIndexVisa === index
                        "
                        id="btn-info-basic-save"
                        icon-only
                        @click="
                          () => {
                            employeeFormState.currentIndexVisa = index;
                          }
                        "
                        type="submit"
                      />

                      <EditButton
                        v-if="
                          employeeFormState.currentIndexVisa === -1 ||
                          (!employeeFormState.isEmployeeEdit &&
                            value.id !== undefined &&
                            employeeFormState.currentIndexVisa === index)
                        "
                        id="btn-info-basic-edit"
                        icon-only
                        @click="
                          () => {
                            employeeFormState.currentIndexVisa = index;
                            employeeFormState.isEmployeeEdit = true;
                            employeeFormState.dialogType = 'edit';
                          }
                        "
                        type="button"
                      />
                      <DeleteButton
                        v-if="
                          employeeFormState.currentIndexVisa === -1 ||
                          (!employeeFormState.isEmployeeEdit &&
                            value.id !== undefined &&
                            !(employeeFormState.currentIndexVisa === -1) &&
                            employeeFormState.currentIndexVisa === index)
                        "
                        id="btn-info-basic-delete"
                        icon-only
                        @click.stop="
                          () => {
                            deleteEmployeeById({ type: 'visa', index });
                          }
                        "
                        type="button"
                        :disabled="
                          !(employeeFormState.currentIndexVisa === -1) &&
                          !(employeeFormState.currentIndexVisa === index)
                        "
                      />
                    </div>
                  </template>
                </FormEmployeeVisa>

                <div class="full-width flex flex-center">
                  <NoData
                    v-if="currentFromDataEmployee.employeeVisa?.length === 0"
                  />
                </div>
              </div>
            </template>

            <template v-if="employeeFormState.currentTab === 'healthCheck'">
              <div class="q-gutter-sm full-width">
                <div
                  class="q-pb-sm text-weight-bold text-body1 row items-center"
                >
                  <q-icon
                    flat
                    size="xs"
                    class="q-pa-sm rounded q-mr-sm"
                    color="info"
                    name="mdi-hospital-box-outline"
                    style="background-color: var(--surface-3)"
                  />

                  {{ $t(`customerEmployee.formHealthCheck.title`) }}
                </div>

                <FormEmployeeHealthCheck
                  v-if="employeeFormState.currentTab === 'healthCheck'"
                  id="drawer-form-checkup"
                  prefix-id="drawer-employee"
                  dense
                  outlined
                  :hide-action="
                    currentTab !== 'employee' ||
                    currentFromDataEmployee.status === 'INACTIVE'
                  "
                  v-model:current-index="employeeFormState.currentIndexCheckup"
                  v-model:employee-checkup="
                    currentFromDataEmployee.employeeCheckup
                  "
                  v-model:checkup-results-option="
                    optionStore.globalOption.checkupResults
                  "
                  v-model:checkup-type-option="
                    optionStore.globalOption.insurancePlace
                  "
                  v-model:medical-benefit-option="
                    optionStore.globalOption.typeInsurance
                  "
                  v-model:insurance-company-option="
                    optionStore.globalOption.insurancePlace
                  "
                  @save="
                    (index) => {
                      employeeFormState.currentIndexCheckup = index;
                      notify('create', $t('general.success'));
                    }
                  "
                  @edit="
                    (index) => {
                      if (
                        currentFromDataEmployee.employeeCheckup?.[index]
                          .statusSave
                      ) {
                        employeeFormState.currentIndexCheckup = index;
                        currentFromDataEmployee.employeeCheckup[
                          index
                        ].statusSave = false;
                      }
                    }
                  "
                  @undo="
                    (index) => {
                      if (
                        currentFromDataEmployee.employeeCheckup?.[index]
                          .statusSave === false
                      ) {
                        employeeFormState.currentIndexCheckup = -1;
                        currentFromDataEmployee.employeeCheckup[
                          index
                        ].statusSave = true;
                        employeeFormStore.resetFormDataEmployee();
                      }
                    }
                  "
                  @delete="
                    (index) => {
                      employeeFormState.currentIndexCheckup = index;
                      deleteEmployeeById({ type: 'healthCheck', index });
                    }
                  "
                />

                <div class="full-width flex flex-center">
                  <NoData
                    v-if="currentFromDataEmployee.employeeCheckup?.length === 0"
                  />
                </div>
              </div>
            </template>
            <template v-if="employeeFormState.currentTab === 'workHistory'">
              <div class="q-gutter-sm full-width">
                <div
                  class="col-12 q-pb-sm text-weight-bold text-body1 row items-center"
                >
                  <q-icon
                    flat
                    size="xs"
                    class="q-pa-sm rounded q-mr-xs"
                    color="info"
                    name="mdi-briefcase-outline"
                    style="background-color: var(--surface-3)"
                  />
                  {{ $t(`customerEmployee.form.group.workHistory`) }}
                </div>

                <FormEmployeeWorkHistory
                  v-if="employeeFormState.currentTab === 'workHistory'"
                  id="drawer-work-history"
                  prefix-id="drawer-employee"
                  dense
                  :hide-action="
                    currentTab !== 'employee' ||
                    currentFromDataEmployee.status === 'INACTIVE'
                  "
                  outlined
                  v-model:current-index="
                    employeeFormState.currentIndexWorkHistory
                  "
                  v-model:employee-work="currentFromDataEmployee.employeeWork"
                  v-model:position-name-option="
                    optionStore.globalOption.position
                  "
                  v-model:job-type-option="
                    optionStore.globalOption.businessType
                  "
                  v-model:workplace-option="optionStore.globalOption.area"
                  @delete="
                    (index) => {
                      employeeFormState.currentIndexWorkHistory = index;
                      deleteEmployeeById({ type: 'work', index });
                    }
                  "
                  @save="
                    (index) => {
                      employeeFormState.currentIndexWorkHistory = index;
                    }
                  "
                  @undo="
                    (index) => {
                      if (
                        currentFromDataEmployee.employeeWork?.[index]
                          .statusSave === false
                      ) {
                        employeeFormState.currentIndexWorkHistory = -1;
                        currentFromDataEmployee.employeeWork[index].statusSave =
                          true;
                      }
                    }
                  "
                  @edit="
                    (index) => {
                      if (
                        currentFromDataEmployee.employeeWork?.[index].statusSave
                      ) {
                        employeeFormState.currentIndexWorkHistory = index;
                        currentFromDataEmployee.employeeWork[index].statusSave =
                          false;
                      }
                    }
                  "
                />
              </div>

              <div class="full-width flex flex-center">
                <NoData
                  v-if="currentFromDataEmployee.employeeWork?.length === 0"
                />
              </div>
            </template>
            <template v-if="employeeFormState.currentTab === 'other'">
              <FormEmployeeOther
                :readonly="currentTab !== 'employee'"
                :hide-action="
                  currentTab !== 'employee' ||
                  currentFromDataEmployee.status === 'INACTIVE'
                "
                v-if="employeeFormState.currentTab === 'other'"
                id="drawer-other"
                prefix-id="drawer-employee"
                dense
                outlined
                v-model:employee-other="
                  currentFromDataEmployee.employeeOtherInfo
                "
                @undo="
                  () => {
                    if (
                      currentFromDataEmployee.employeeOtherInfo?.statusSave ===
                      false
                    ) {
                      currentFromDataEmployee.employeeOtherInfo.statusSave = true;
                    }
                  }
                "
                @edit="
                  () => {
                    if (currentFromDataEmployee.employeeOtherInfo?.statusSave) {
                      currentFromDataEmployee.employeeOtherInfo.statusSave = false;
                    }
                  }
                "
              />
            </template>
          </div>
        </div>
      </div>
    </div>
  </DrawerInfo>

  <DialogForm
    :title="$t('general.historyEdit')"
    hide-footer
    v-model:modal="employeeHistoryDialog"
  >
    <div class="q-pa-md">
      <HistoryEditComponent
        v-if="employeeHistory"
        v-model:history-list="employeeHistory"
      />
    </div>
  </DialogForm>
</template>

<style scoped>
.customer-row {
  display: grid;
  gap: var(--size-6);
  transition: 0.3s ease-in-out;
}

.hover-card:hover {
  cursor: pointer;
  border-radius: 10px;
  box-shadow: var(--shadow-3);
}

.slide-enter-active {
  transition: all 0.1s ease-out;
}

.slide-leave-active {
  transition: all 0.1s cubic-bezier(1, 0.5, 0.8, 1);
}

.slide-enter-from,
.slide-leave-to {
  transform: translateY(-20px);
  opacity: 0;
}

.employer-active {
  background-color: hsla(var(--info-bg) / 0.1);
  color: hsl(var(--info-bg));
}

.tags {
  display: inline-block;
  color: hsla(var(--_color) / 1);
  background: hsla(var(--_color) / 0.15);
  border-radius: var(--radius-2);
  padding-inline: var(--size-2);
}

.tags__pink {
  --_color: var(--pink-6-hsl);
}

.tags__purple {
  --_color: var(--violet-11-hsl);
}

.tags__green {
  --_color: var(--teal-10-hsl);
}

.dark .tags__purple {
  --_color: var(--violet-10-hsl);
}

.dark .tags__green {
  --_color: var(--teal-8-hsl);
}

.status-active {
  --_branch-status-color: var(--green-6-hsl);
}

.status-inactive {
  --_branch-status-color: var(--stone-5-hsl);
  --_branch-badge-bg: var(--stone-5-hsl);
  filter: grayscale(0.5);
  opacity: 0.5;
}

.branch-card__icon {
  background-color: hsla(var(--_branch-card-bg) / 0.15);
  border-radius: 50%;
  padding: var(--size-1);
  position: relative;
  transform: rotate(45deg);

  &::after {
    content: ' ';
    display: block;
    block-size: 0.5rem;
    aspect-ratio: 1;
    position: absolute;
    border-radius: 50%;
    right: -0.1rem;
    top: calc(50% - 0.25rem);
    bottom: calc(50% - 0.25rem);
    background-color: hsla(var(--_branch-status-color) / 1);
  }

  & :deep(.q-avatar) {
    transform: rotate(-45deg);
    color: hsla(var(--_branch-card-bg) / 1);
  }
}

& .symbol-gender {
  color: hsla(var(--_fg));

  &.symbol-gender__male {
    --_fg: var(--gender-male);
  }

  &.symbol-gender__female {
    --_fg: var(--gender-female);
  }
}

.btn-arrow-right {
  transform: rotate(0deg);
  transition: transform 0.3s ease;
}

.btn-arrow-right.active {
  transform: rotate(90deg);
  transition: transform 0.3s ease;
}
</style>
