<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 useOcrStore from 'stores/ocr';
import useCustomerStore from 'stores/customer';
import useEmployeeStore from 'stores/employee';
import useMyBranchStore from 'stores/my-branch';
import useUtilsStore, { dialog, notify, resetScrollBar } from 'stores/utils';
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 { 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 ButtonAddComponent from 'components/ButtonAddCompoent.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 FormEmployeeVisa from 'components/03_customer-management/FormEmployeeVisa.vue';
import DialogForm from 'components/DialogForm.vue';
import SideMenu from 'components/SideMenu.vue';
import { AddButton } from 'components/button';
import TableEmpoloyee from 'src/components/03_customer-management/TableEmpoloyee.vue';
import { calculateAge, toISOStringWithTimezone } from 'src/utils/datetime';
import { UploadFileGroup } from 'components/upload-file';

import {
  columnsCustomer,
  columnsEmployee,
  formMenuIconEmployee,
  uploadFileListEmployee,
  columnsAttachment,
} 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 { group } from 'node:console';
import { readonly } from 'vue';

const currentSelectedMenu = ref<{ label: string; value: string }>({
  label: '',
  value: '',
});

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

const tabFieldRequired = ref<{ [key: string]: (keyof CustomerBranchCreate)[] }>(
  {
    main: [],
    business: ['businessType', 'jobPosition'],
    address: [
      'homeCode',
      'address',
      'addressEN',
      'provinceId',
      'districtId',
      'subDistrictId',
    ],
    contact: [],
  },
);

const formMenuIcon = ref<{ icon: string; color: string; bgColor: string }[]>([
  {
    icon: 'mdi-office-building-outline',
    color: 'hsl(var(--info-bg))',
    bgColor: 'var(--surface-1)',
  },
  {
    icon: 'mdi-briefcase-outline',
    color: 'hsl(var(--info-bg))',
    bgColor: 'var(--surface-1)',
  },
]);

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

async function init() {
  utilsStore.currentTitle.title = 'menu.customer';
  utilsStore.currentTitle.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;
      utilsStore.currentTitle.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>>();
const dialogCreateCustomerItem = [
  {
    icon: 'mdi:office-building',
    text: 'customer.employerLegalEntity',
    iconColor: '--purple-10',
    color: 'var(--purple-8-hsl)',
  },
  {
    icon: 'heroicons:user-solid',
    text: 'customer.employerNaturalPerson',
    iconColor: '--green-11',
    color: 'var(--green-9-hsl)',
  },
];

// 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],
  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,
  });
  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?: 'healthCheck' | 'work';
}) {
  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 === 'healthCheck') {
        await employeeFormStore.deleteHealthCheck();
      }

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

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

      const resultList = await employeeStore.fetchList();
      if (resultList) listEmployee.value = resultList.result;
      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.zipCode = e.zipCode;
    }
    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.zipCode =
        employeeFormState.value.formDataEmployeeOwner.zipCode;
    }
    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) < 18) {
        dialog({
          color: 'warning',
          icon: 'mdi-alert',
          title: t('dialog.title.youngWorker'),
          actionText: t('dialog.action.ok'),
          persistent: true,
          message: t('dialog.message.youngWorker'),
          action: async () => {
            return;
          },
          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>
  <ButtonAddComponent
    style="z-index: 999"
    v-if="$route.name === 'CustomerManagement'"
  >
    <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"
    />
    <q-fab-action
      v-if="currentTab === 'employee'"
      :label="$t('general.add') + ' ' + $t('customer.employee')"
      external-label
      id="add-employee"
      label-position="left"
      @click="createEmployeeForm()"
      color="primary"
      padding="xs"
      icon="mdi-account-plus-outline"
    />
  </ButtonAddComponent>

  <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"
                labelI18n
                :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
                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"
                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 }"
                >
                  <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')"
                          style="padding-block: 7px; padding-inline: 0px"
                        >
                          <div class="row items-center">
                            <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 || '-'
                                    : 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')">
                          {{
                            props.row.branch.length !== 0
                              ? props.row.branch[0].businessType !== null
                                ? optionStore.mapOption(
                                    props.row.branch[0].businessType,
                                  )
                                : ''
                              : '-'
                          }}
                        </q-td>

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

                        <q-td v-if="fieldSelected.includes('address')">
                          {{
                            locale === 'eng'
                              ? `${props.row.branch[0].addressEN} ${props.row.branch[0].mooEN} ${props.row.branch[0].soiEN} ${props.row.branch[0].streetEN} ${props.row.branch[0].subDistrict.nameEN} ${props.row.branch[0].district.nameEN} ${props.row.branch[0].province.nameEN} ${props.row.branch[0].subDistrict.zipCode}`
                              : `${props.row.branch[0].address} ${props.row.branch[0].moo} ${props.row.branch[0].soi} ${props.row.branch[0].street} ต.${props.row.branch[0].subDistrict.name} อ.${props.row.branch[0].district.name} จ.${props.row.branch[0].province.name} ${props.row.branch[0].subDistrict.zipCode}`
                          }}
                        </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
                            dense
                            flat
                            @click.stop="
                              async () => {
                                const res = await employeeStore.fetchList({
                                  customerId: props.row.id,
                                });

                                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.customerName}`"
                            size="sm"
                            dense
                            round
                            flat
                            @click.stop="editCustomerForm(props.row.id)"
                          />

                          <KebabAction
                            :id-name="props.row.code"
                            :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
                              v-model:page-size="pageSize"
                              v-model:current-page="currentPageEmployee"
                              :list-employee="listEmployee"
                              :columns-employee="columnsEmployee"
                              @history="(item: any) => {}"
                              @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">
                        <BranchCard
                          i18nKey="customer.table"
                          class="surface-1"
                          :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"
                              :idName="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>
                      <q-btn-dropdown
                        dense
                        unelevated
                        class="bordered q-pl-md rounded"
                        :label="pageSize"
                        style="background-color: var(--surface-1)"
                      >
                        <q-list>
                          <q-item
                            v-for="v in [10, 30, 50, 100, 500, 1000]"
                            :key="v"
                            clickable
                            v-close-popup
                            @click="
                              async () => {
                                pageSize = v;
                                await fetchListCustomer();
                              }
                            "
                          >
                            <q-item-section>
                              <q-item-label>{{ v }}</q-item-label>
                            </q-item-section>
                          </q-item>
                        </q-list>
                      </q-btn-dropdown>
                    </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
                    :grid-view="gridView"
                    :list-employee="listEmployee"
                    :columns-employee="columnsEmployee"
                    :field-selected="fieldSelected"
                    @history="(item: any) => {}"
                    @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>
                      <q-btn-dropdown
                        dense
                        unelevated
                        :label="pageSize"
                        class="bordered q-pl-md"
                        style="background-color: var(--surface-1)"
                      >
                        <q-list>
                          <q-item
                            v-for="v in [10, 30, 50, 100, 500, 1000]"
                            :key="v"
                            clickable
                            v-close-popup
                            @click="
                              async () => {
                                pageSize = v;
                                await fetchListEmployee();
                              }
                            "
                          >
                            <q-item-section>
                              <q-item-label>{{ v }}</q-item-label>
                            </q-item-section>
                          </q-item>
                        </q-list>
                      </q-btn-dropdown>
                    </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-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')"
        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-px-lg q-pt-lg surface-2">
      <ProfileBanner
        v-if="customerFormData.customerBranch !== undefined"
        active
        hide-fade
        :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"
      class="surface-2 q-pa-lg"
      id="customer-form"
    >
      <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"
                  class="app-text-muted"
                  @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 q-py-md q-pr-md q-pl-sm"
          id="customer-form-content"
          style="height: 100%; max-height: 100%; overflow-y: auto"
        >
          <EmployerFormBasicInfo
            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:customerName="customerNameInfo"
            v-model:registerName="
              customerFormData.customerBranch[0].registerName
            "
            v-model:citizenId="customerFormData.customerBranch[0].citizenId"
            v-model:legalPersonNo="
              customerFormData.customerBranch[0].legalPersonNo
            "
            v-model:businessType="
              customerFormData.customerBranch[0].businessType
            "
            v-model:jobPosition="customerFormData.customerBranch[0].jobPosition"
            v-model:telephoneNo="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',
                        'registerNameEN',
                        'customerName',
                      ];
                    }
                    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();
                    customerFormStore.resetForm();
                  }
                "
              >
                <!-- v-if="!!customerFormState.editCustomerId" -->

                <EmployerFormBranch
                  :index="idx"
                  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 (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 === 'healthCheck') {
          await employeeFormStore.submitHealthCheck();
        }

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

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

        employeeFormState.isEmployeeEdit = false;
        employeeFormState.currentIndex = -1;

        await fetchListEmployee();
      }
    "
    :show="
      () => {
        employeeFormStore.resetFormDataEmployee(true);
      }
    "
    :before-close="
      () => {
        if (employeeFormStore.isFormDataDifferent()) {
          employeeConfirmUnsave();
          return true;
        } else {
          fetchListEmployee();
        }
        return false;
      }
    "
  >
    <div class="q-px-lg q-pt-lg surface-2">
      <ProfileBanner
        active
        useToggle
        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="employeeFormState.profileUrl || `/images/employee-avatar.png`"
        :tabs-list="
          [
            {
              name: 'personalInfo',
              label: 'customerEmployee.form.group.personalInfo',
            },
            {
              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;
          })
        "
        :menu="formMenuIconEmployee"
        :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="surface-2 q-pa-lg"
      id="drawer-employee-form"
    >
      <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-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('customerEmployee.form.group.passport'),
                    anchor: 'form-passport',
                    tab: 'personalInfo',
                  },
                  {
                    name: $t('customerEmployee.form.group.visa'),
                    anchor: 'form-visa',
                    tab: 'personalInfo',
                  },
                  {
                    name: $t('general.uploadFile'),
                    anchor: 'drawer-info-file-upload',
                    tab: 'personalInfo',
                  },
                  ...(currentFromDataEmployee.employeeCheckup?.map((v, i) => ({
                    name: $t('general.times', { number: i + 1 }),
                    anchor: `form-employee-checkup-${i}`,
                    tab: 'healthCheck',
                  })) || []),

                  ...(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"
            />
          </div>
        </div>

        <div
          class="col-12 col-md-10 q-py-md q-pr-md q-pl-sm"
          id="employee-form-content"
          style="height: 100%; max-height: 100; overflow-y: auto"
        >
          <template v-if="employeeFormState.currentTab === 'personalInfo'">
            <div
              class="surface-1 rounded q-pt-sm row"
              style="position: absolute; z-index: 999; right: 4%"
            >
              <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>

            <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:prefixName="currentFromDataEmployee.namePrefix"
              v-model:firstName="currentFromDataEmployee.firstName"
              v-model:lastName="currentFromDataEmployee.lastName"
              v-model:firstNameEN="currentFromDataEmployee.firstNameEN"
              v-model:lastNameEN="currentFromDataEmployee.lastNameEN"
              v-model:midName="currentFromDataEmployee.middleName"
              v-model:midNameEN="currentFromDataEmployee.middleNameEN"
              v-model:gender="currentFromDataEmployee.gender"
              v-model:birthDate="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:addressEN="currentFromDataEmployee.addressEN"
              v-model:provinceId="currentFromDataEmployee.provinceId"
              v-model:districtId="currentFromDataEmployee.districtId"
              v-model:subDistrictId="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
                :group-list="uploadFileListEmployee"
                :menu="uploadFileListEmployee"
                :columns="columnsAttachment"
                :ocr="
                  async (group, file) => {
                    const res = await ocrStore.sendOcr({
                      file: file,
                      category: group,
                    });

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

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

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

                      if (res) {
                        return 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) {
                        return true;
                      }
                    }

                    return false;
                  }
                "
                :get-file-list="
                  async (group: 'passport' | 'visa') => {
                    if (!!currentFromDataEmployee.id) {
                      const resMeta = await employeeStore.getMetaList({
                        parentId: currentFromDataEmployee.id,
                        group,
                      });

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

                      return await waitAll(tempValue);
                    }
                    return [];
                  }
                "
              >
                <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:passport-type="meta.type"
                    v-model:passport-number="meta.number"
                    v-model:passport-issue-date="meta.issueDate"
                    v-model:passport-expiry-date="meta.expireDate"
                    v-model:passport-issuing-place="meta.issuePlace"
                    v-model:passport-issuing-country="meta.issueCountry"
                  />
                  <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:visa-type="meta.type"
                    v-model:visa-number="meta.number"
                    v-model:visa-issue-date="meta.issueDate"
                    v-model:visa-expiry-date="meta.expireDate"
                    v-model:visa-issuing-place="meta.issuePlace"
                  />
                </template>
              </UploadFileGroup>
            </div>
          </template>

          <template v-if="employeeFormState.currentTab === 'healthCheck'">
            <FormEmployeeHealthCheck
              v-if="employeeFormState.currentTab === 'healthCheck'"
              id="form-checkup"
              prefix-id="form-employee"
              dense
              outlined
              v-model:current-index="employeeFormState.currentIndex"
              v-model:employeeCheckup="currentFromDataEmployee.employeeCheckup"
              v-model:checkupTypeOption="
                optionStore.globalOption.insurancePlace
              "
              v-model:medicalBenefitOption="
                optionStore.globalOption.typeInsurance
              "
              v-model:insuranceCompanyOption="
                optionStore.globalOption.insurancePlace
              "
              @delete="
                (index) => {
                  employeeFormState.currentIndex = index;
                  deleteEmployeeById({ type: 'healthCheck' });
                }
              "
              @save="
                (index) => {
                  employeeFormState.currentIndex = 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;
                  }
                }
              "
            />
          </template>

          <template v-if="employeeFormState.currentTab === 'workHistory'">
            <FormEmployeeWorkHistory
              v-if="employeeFormState.currentTab === 'workHistory'"
              id="form-work-history"
              prefix-id="form-employee"
              dense
              outlined
              v-model:current-index="employeeFormState.currentIndex"
              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.currentIndex = index;
                  deleteEmployeeById({ type: 'work' });
                }
              "
              @save="
                (index) => {
                  employeeFormState.currentIndex = 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;
                  }
                }
              "
            />
            a
          </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"
    :hiddenFooter="!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"
    :hiddenFooter="!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
    "
    :badgeLabel="
      customerFormData.customerType === 'CORP'
        ? $t('customer.employerLegalEntity')
        : $t('customer.employerNaturalPerson')
    "
    :badgeStyle="
      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-px-lg q-pt-lg surface-2">
        <ProfileBanner
          v-if="customerFormData.customerBranch !== undefined"
          :active="customerFormData.status !== 'INACTIVE'"
          hide-fade
          useToggle
          v-model:toggle-status="customerFormData.status"
          :menu="formMenuIcon"
          :toggleTitle="$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
          "
          :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
          "
          @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="surface-2 q-pa-lg column"
        id="customer-form"
      >
        <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"
                    class="app-text-muted"
                    @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 q-py-md q-pr-md q-pl-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:customerName="customerNameInfo"
              v-model:registerName="
                customerFormData.customerBranch[0].registerName
              "
              v-model:citizenId="customerFormData.customerBranch[0].citizenId"
              v-model:legalPersonNo="
                customerFormData.customerBranch[0].legalPersonNo
              "
              v-model:businessType="
                customerFormData.customerBranch[0].businessType
              "
              v-model:jobPosition="
                customerFormData.customerBranch[0].jobPosition
              "
              v-model:telephoneNo="
                customerFormData.customerBranch[0].telephoneNo
              "
              v-model:branch-options="registerAbleBranchOption"
            />

            <!-- <div class="row q-col-gutter-sm q-mb-xl">
              <UploadFile
                id="form-upload-file-customer"
                class="q-mb-xl"
                hide-action
                :dropdown-list="uploadFileList"
                v-model:file="customerFormState.file"
                @send-ocr="
                  (group: any, file: any) => ocrStore.sendOcr({ file })
                "
              />
            </div> -->

            <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',
                          'registerNameEN',
                          'customerName',
                        ];
                      }

                      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
                    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="
      () => {
        employeeFormState.drawerModal = false;
        resetScrollBar('drawer-employee-form-content');
      }
    "
    :title="
      employeeFormState.currentEmployee
        ? $i18n.locale === 'eng'
          ? `${employeeFormState.currentEmployee.firstNameEN} ${employeeFormState.currentEmployee.lastNameEN}`
          : `${employeeFormState.currentEmployee.firstName} ${employeeFormState.currentEmployee.lastName}`
        : '-'
    "
    :badgeClass="
      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 === 'healthCheck') {
          await employeeFormStore.submitHealthCheck();
        }

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

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

        employeeFormState.isEmployeeEdit = false;
        employeeFormState.currentIndex = -1;
      }
    "
    :before-close="
      () => {
        if (employeeFormStore.isFormDataDifferent()) {
          employeeConfirmUnsave();
          return true;
        }
        return false;
      }
    "
  >
    <div class="column full-height">
      <div class="q-px-lg q-pt-lg surface-2">
        <ProfileBanner
          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: 'healthCheck',
              label: 'customerEmployee.form.group.healthCheck',
            },
            {
              name: 'workHistory',
              label: 'customerEmployee.form.group.workHistory',
            },
            { name: 'other', label: 'customerEmployee.form.group.other' },
          ]"
          :menu="formMenuIconEmployee"
          :toggle-title="$t('status.title')"
        />
      </div>
      <div
        style="flex: 1; width: 100%; overflow-y: auto"
        class="surface-2 q-pa-lg column"
        id="drawer-employee-form"
      >
        <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('customerEmployee.form.group.passport'),
                      anchor: 'drawer-form-passport',
                      tab: 'personalInfo',
                    },
                    {
                      name: $t('customerEmployee.form.group.visa'),
                      anchor: 'drawer-form-visa',
                      tab: 'personalInfo',
                    },

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

                    ...(currentFromDataEmployee.employeeCheckup?.map(
                      (v, i) => ({
                        name: $t('general.times', { number: i + 1 }),
                        anchor: `drawer-employee-checkup-${i}`,
                        tab: 'healthCheck',
                      }),
                    ) || []),
                    ...(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"
              />
            </div>
          </div>
          <div
            class="col-12 col-md-10 q-py-md q-pr-md q-pl-sm"
            id="drawer-employee-form-content"
            style="height: 100%; overflow-y: auto"
          >
            <template v-if="employeeFormState.currentTab === 'personalInfo'">
              <div
                class="surface-1 rounded q-pt-sm row"
                style="position: absolute; z-index: 999; right: 4%"
                v-if="
                  currentTab === 'employee' &&
                  currentFromDataEmployee.status !== 'INACTIVE'
                "
              >
                <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>
              <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:prefixName="currentFromDataEmployee.namePrefix"
                v-model:firstName="currentFromDataEmployee.firstName"
                v-model:lastName="currentFromDataEmployee.lastName"
                v-model:firstNameEN="currentFromDataEmployee.firstNameEN"
                v-model:lastNameEN="currentFromDataEmployee.lastNameEN"
                v-model:midName="currentFromDataEmployee.middleName"
                v-model:midNameEN="currentFromDataEmployee.middleNameEN"
                v-model:gender="currentFromDataEmployee.gender"
                v-model:birthDate="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:addressEN="currentFromDataEmployee.addressEN"
                v-model:provinceId="currentFromDataEmployee.provinceId"
                v-model:districtId="currentFromDataEmployee.districtId"
                v-model:subDistrictId="currentFromDataEmployee.subDistrictId"
                v-model:sameWithEmployer="
                  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>
                <!-- แก้ไขลูกจ้าง -->
                <UploadFileGroup
                  v-model:current-id="currentFromDataEmployee.id"
                  v-model="currentFromDataEmployee.file"
                  hide-action
                  v-model:current-selected-menu="currentSelectedMenu"
                  :group-list="uploadFileListEmployee"
                  :menu="uploadFileListEmployee"
                  :columns="columnsAttachment"
                  :ocr="
                    async (group, file) => {
                      const res = await ocrStore.sendOcr({
                        file: file,
                        category: group,
                      });

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

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

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

                        if (res) {
                          return 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) {
                          return true;
                        }
                      }

                      return false;
                    }
                  "
                  :get-file-list="
                    async (group: 'passport' | 'visa') => {
                      if (!!currentFromDataEmployee.id) {
                        const resMeta = await employeeStore.getMetaList({
                          parentId: currentFromDataEmployee.id,
                          group,
                        });

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

                        return await waitAll(tempValue);
                      }
                      return [];
                    }
                  "
                >
                  <template #form="{ mode, meta, isEdit }">
                    <FormCitizen
                      v-if="mode === 'citizen' && meta"
                      orc
                      :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:passport-type="meta.type"
                      v-model:passport-number="meta.number"
                      v-model:passport-issue-date="meta.issueDate"
                      v-model:passport-expiry-date="meta.expireDate"
                      v-model:passport-issuing-place="meta.issuePlace"
                      v-model:passport-issuing-country="meta.issueCountry"
                    />
                    <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:visa-type="meta.type"
                      v-model:visa-number="meta.number"
                      v-model:visa-issue-date="meta.issueDate"
                      v-model:visa-expiry-date="meta.expireDate"
                      v-model:visa-issuing-place="meta.issuePlace"
                    />
                  </template>
                </UploadFileGroup>
              </div>
            </template>
            <template v-if="employeeFormState.currentTab === 'healthCheck'">
              <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.currentIndex"
                v-model:employee-checkup="
                  currentFromDataEmployee.employeeCheckup
                "
                v-model:checkup-type-option="
                  optionStore.globalOption.insurancePlace
                "
                v-model:medical-benefit-option="
                  optionStore.globalOption.typeInsurance
                "
                v-model:insuranceCompanyOption="
                  optionStore.globalOption.insurancePlace
                "
                @save="
                  (index) => {
                    employeeFormState.currentIndex = index;
                    notify('create', $t('general.success'));
                  }
                "
                @edit="
                  (index) => {
                    if (
                      currentFromDataEmployee.employeeCheckup?.[index]
                        .statusSave
                    ) {
                      employeeFormState.currentIndex = index;
                      currentFromDataEmployee.employeeCheckup[
                        index
                      ].statusSave = false;
                    }
                  }
                "
                @undo="
                  (index) => {
                    if (
                      currentFromDataEmployee.employeeCheckup?.[index]
                        .statusSave === false
                    ) {
                      employeeFormState.currentIndex = -1;
                      currentFromDataEmployee.employeeCheckup[
                        index
                      ].statusSave = true;
                      employeeFormStore.resetFormDataEmployee();
                    }
                  }
                "
                @delete="
                  (index) => {
                    employeeFormState.currentIndex = index;
                    deleteEmployeeById({ type: 'healthCheck' });
                  }
                "
              />
            </template>
            <template v-if="employeeFormState.currentTab === 'workHistory'">
              <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.currentIndex"
                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.currentIndex = index;
                    deleteEmployeeById({ type: 'work' });
                  }
                "
                @save="
                  (index) => {
                    employeeFormState.currentIndex = index;
                  }
                "
                @undo="
                  (index) => {
                    if (
                      currentFromDataEmployee.employeeWork?.[index]
                        .statusSave === false
                    ) {
                      employeeFormState.currentIndex = -1;
                      currentFromDataEmployee.employeeWork[index].statusSave =
                        true;
                    }
                  }
                "
                @edit="
                  (index) => {
                    if (
                      currentFromDataEmployee.employeeWork?.[index].statusSave
                    ) {
                      employeeFormState.currentIndex = index;
                      currentFromDataEmployee.employeeWork[index].statusSave =
                        false;
                    }
                  }
                "
              />
            </template>
            <template v-if="employeeFormState.currentTab === 'other'">
              <FormEmployeeOther
                :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>
</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>
