<script setup lang="ts">
import { ref, watch, onMounted } 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 } 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 } 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 ItemCard from 'src/components/ItemCard.vue';
import DrawerInfo from 'components/DrawerInfo.vue';
import ButtonAddComponent from 'components/ButtonAddCompoent.vue';
import PersonCard from 'components/shared/PersonCard.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 { UploadFile } from 'components/upload-file';

import {
  columnsCustomer,
  columnsEmployee,
  formMenuIconEmployee,
  uploadFileList,
} 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';

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 filtdRequire = ref<{ [key: string]: (keyof CustomerBranchCreate)[] }>({
  main: ['citizenId', 'legalPersonNo', 'registerName'],
  address: ['address', 'addressEN', 'provinceId', 'districtId'],
  business: [],
  contact: ['contactName', 'telephoneNo'],
});

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: `${currentCustomer.value.firstName || '-'} ${currentCustomer.value.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 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: 'customerLegalEntity',
    color: 'var(--purple-8)',
  },
  {
    icon: 'heroicons:user-solid',
    text: 'customerNaturalPerson',
    color: 'var(--green-9)',
  },
];

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 validateFiltdRequire<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) {
  await employeeStore.editById(id, { status: !status ? 'ACTIVE' : 'INACTIVE' });

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

async function toggleStatusCustomer(id: string, status: boolean) {
  await customerStore.editById(id, { status: !status ? 'ACTIVE' : 'INACTIVE' });
  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);
  customerFormState.value.dialogType = 'edit';
  customerFormState.value.drawerModal = true;
  customerFormState.value.editCustomerId = id;
}

async function editEmployeeFormPersonal(id: string) {
  await employeeFormStore.assignFormDataEmployee(id);
  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();
      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;

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

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

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;
}

// 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;
  },
);

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
              lazy-rules="ondemand"
              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"
            >
              <q-select
                lazy-rules="ondemand"
                id="select-status"
                for="select-status"
                v-model="currentStatus"
                outlined
                dense
                option-value="value"
                option-label="label"
                class="col"
                :class="{ 'offset-md-5': gridView }"
                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>
              <q-select
                lazy-rules="ondemand"
                id="select-field"
                v-if="gridView === false"
                for="select-field"
                class="q-ml-sm col"
                :options="
                  currentTab === 'employer'
                    ? 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"
                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"
                @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('customerName')">
                          <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`"
                                      class="full-height full-width"
                                    >
                                      <template #error>
                                        <q-img
                                          :src="`${props.row.customerType === 'CORP' ? '/images/customer-CORP-avartar.png' : '/images/customer-PERS-avartar.png'}`"
                                        />
                                      </template>
                                    </q-img>
                                  </q-avatar>
                                </div>
                              </div>
                            </div>
                            <div class="col">
                              <div class="col">
                                {{ props.row.firstName }}
                                {{ props.row.lastName }}
                              </div>
                              <div class="col app-text-muted">
                                {{ props.row.firstNameEN || '-' }}
                                {{ props.row.lastNameEN || '-' }}
                              </div>
                            </div>
                          </div>
                        </q-td>
                        <q-td v-if="fieldSelected.includes('businessTypePure')">
                          {{
                            props.row.branch.length !== 0
                              ? props.row.branch[0].businessType !== null
                                ? props.row.branch[0].businessType
                                : ''
                              : '-'
                          }}
                        </q-td>

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

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

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

                        <q-td v-if="fieldSelected.includes('contactPhone')">
                          {{
                            props.row.branch.length !== 0
                              ? props.row.branch[0].telephoneNo !== null
                                ? props.row.branch[0].telephoneNo
                                : ''
                              : '-'
                          }}
                        </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.dialogType = 'edit';
                                customerFormState.readonly = false;
                              }
                            "
                            @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="
                                (item: any) => {
                                  employeeFormState.drawerModal = true;
                                  employeeFormState.isEmployeeEdit = false;
                                  employeeFormStore.assignFormDataEmployee(
                                    item.id,
                                  );
                                }
                              "
                              @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-3 col-sm-6">
                        <PersonCard
                          :id="`card-${props.row.customerName}`"
                          :field-selected="fieldSelected"
                          separateEnter
                          history
                          :prefix-id="
                            props.row.customerNameEN ?? String(props.rowIndex)
                          "
                          :data="{
                            code: props.row.code,
                            name:
                              $i18n.locale === 'eng'
                                ? `${props.row.firstNameEN} ${props.row.lastNameEN} `.trim()
                                : `${props.row.firstName} ${props.row.lastName} `.trim(),
                            img:
                              props.row.imageUrl ||
                              '/images/customer-' +
                                props.row.customerType +
                                '-avartar.png',
                            male: undefined,
                            female: undefined,
                            detail: [
                              {
                                icon: 'mdi-phone-outline',
                                value: props.row.branch[0]?.telephoneNo || '-',
                              },
                              {
                                icon: 'mdi-account-outline',
                                value: props.row.personName || '-',
                              },
                            ],
                          }"
                          :tag="[
                            {
                              color:
                                {
                                  CORP: 'purple',
                                  PERS: 'green',
                                }[props.row.customerType as string] || 'CORP',
                              value: $t(
                                props.row.customerType === 'CORP'
                                  ? 'customer.employerLegalEntity'
                                  : 'customer.employerNaturalPerson',
                              ),
                            },
                          ]"
                          :disabled="props.row.status === 'INACTIVE'"
                          @history="openHistory(props.row.id)"
                          @update-card="
                            async () => {
                              await editCustomerForm(props.row.id);
                              customerFormState.dialogType = 'edit';
                              customerFormState.readonly = false;
                            }
                          "
                          @enter-card="
                            $router.push(
                              `/customer-management/${props.row.id}/branch`,
                            )
                          "
                          @view-card="
                            () => {
                              const { branch, ...payload } = props.row;
                              currentCustomer = payload;
                              editCustomerForm(props.row.id);
                            }
                          "
                          @delete-card="deleteCustomerById(props.row.id)"
                          @toggle-status="
                            triggerChangeStatus(props.row.id, props.row.status)
                          "
                        />
                      </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="
                      (item: any) => {
                        employeeFormState.drawerModal = true;
                        employeeFormState.isEmployeeEdit = false;
                        employeeFormStore.assignFormDataEmployee(item.id);
                      }
                    "
                    @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.firstName} ${currentCustomer.lastName}`"
        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="60vw"
    height="300px"
    :close="() => (emptyCreateDialog = false)"
  >
    <div class="full-height row q-pa-md">
      <ItemCard
        class="col q-mx-sm full-height"
        v-for="i in dialogCreateCustomerItem"
        :key="i.text"
        :icon="i.icon"
        :text="i.text"
        :color="i.color"
        @trigger="
          () => {
            createCustomerForm(
              i.text === 'customerLegalEntity' ? 'CORP' : 'PERS',
            );
            emptyCreateDialog = false;
          }
        "
      />
    </div>
  </DialogForm>

  <DialogContainer
    :model-value="customerFormState.dialogModal"
    :on-open="
      async () => {
        await fetchListOfOptionBranch();
        customerFormStore.resetForm(customerFormState.dialogType === 'create');
      }
    "
    :on-close="() => (customerFormState.dialogModal = false)"
  >
    <template #header>
      <DialogHeader
        :title="
          $t(`form.title.${customerFormState.dialogType}`, {
            name: $t('customer.employer'),
          })
        "
      >
        <template
          v-if="
            customerFormState.dialogType !== 'create' &&
            customerFormState.editCustomerCode
          "
          #title-after
        >
          {{ customerFormState.editCustomerCode }}
        </template>
      </DialogHeader>
    </template>

    <div class="q-px-lg q-pt-lg surface-2">
      <ProfileBanner
        active
        hide-fade
        :fallback-cover="`/images/customer-${customerFormData.customerType}-banner-bg.jpg`"
        :img="
          customerFormState.customerImageUrl ||
          `/images/customer-${customerFormData.customerType}-avartar.png`
        "
        color="hsla(var(--pink-6-hsl)/1)"
        bg-color="hsla(var(--pink-6-hsl)/0.15)"
        @view="customerFormState.imageDialog = true"
        @edit="dialogCustomerImageUpload?.browse()"
      />
    </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',
                },
                ...(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"
            />
          </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"
        >
          <q-form
            @submit.prevent="
              async () => {
                await customerFormStore.submitFormCustomer();
                customerFormState.readonly = true;
                notify('create', $t('success'));
                await fetchListCustomer();
              }
            "
            greedy
            :style="{
              opacity: customerFormState.branchIndex !== -1 ? '0.5' : undefined,
            }"
          >
            <EmployerFormBasicInfo
              class="q-mb-xl"
              :readonly="
                (customerFormState.dialogType === 'edit' &&
                  customerFormState.readonly === true) ||
                customerFormState.dialogType === 'info'
              "
              :action-disabled="customerFormState.branchIndex !== -1"
              id="form-basic-info-customer"
              :create="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:code="customerFormData.code"
              v-model:registered-branch-id="customerFormData.registeredBranchId"
              v-model:branch-options="registerAbleBranchOption"
              v-model:first-name="customerFormData.firstName"
              v-model:last-name="customerFormData.lastName"
              v-model:first-name-en="customerFormData.firstNameEN"
              v-model:last-name-en="customerFormData.lastNameEN"
              v-model:name-prefix="customerFormData.namePrefix"
              v-model:gender="customerFormData.gender"
              v-model:birth-date="customerFormData.birthDate"
            />
          </q-form>
          <div class="row q-col-gutter-sm" id="form-branch-customer-branch">
            <div
              class="col-12 text-weight-bold text-body1 row items-center"
              :style="{
                opacity:
                  customerFormState.branchIndex !== -1 ? '0.5' : undefined,
              }"
            >
              <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>
              <AddButton
                type="button"
                class="q-ml-sm"
                @click="customerFormStore.addCurrentCustomerBranch()"
                v-if="
                  customerFormState.branchIndex === -1 &&
                  !!customerFormState.editCustomerId
                "
                :disabled="!customerFormState.readonly"
              />
            </div>
            <template
              v-for="(_, idx) in customerFormData.customerBranch"
              :key="idx"
            >
              <q-form
                class="full-width"
                v-if="customerFormData.customerBranch"
                greedy
                @submit.prevent="
                  async () => {
                    if (!customerFormData.customerBranch) return;
                    if (!customerFormState.editCustomerId) return;

                    if (customerFormData.customerType === 'CORP') {
                      filtdRequire.main = ['legalPersonNo', 'registerName'];
                    }
                    if (customerFormData.customerType === 'PERS') {
                      filtdRequire.main = ['citizenId'];
                    }

                    let tapIsUndefined = validateFiltdRequire(
                      customerFormData.customerBranch?.[idx],
                      filtdRequire,
                    );

                    if (tapIsUndefined.length > 0) {
                      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;
                        },
                      });
                    } else {
                      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,
                          },
                        );
                      }

                      await customerFormStore.assignFormData(
                        customerFormState.editCustomerId,
                      );
                      customerFormStore.resetForm();
                    }
                  }
                "
              >
                <EmployerFormBranch
                  v-if="!!customerFormState.editCustomerId"
                  :index="idx"
                  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>
  </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();
          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"
        bgColor="linear-gradient(135deg, rgba(43,137,223,1) 0%, rgba(230,51,81,1) 100%)"
        v-model:current-tab="employeeFormState.currentTab"
        v-model:cover-url="employeeFormState.profileUrl"
        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="
          employeeFormState.profileUrl === '' ||
          employeeFormState.profileUrl === undefined
        "
        @view="employeeFormState.imageDialog = true"
        @edit="dialogEmployeeImageUpload && dialogEmployeeImageUpload.browse()"
        @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',
                  },
                  ...(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"
              v-model:open="employeeFormState.dialogModal"
              v-model:prefixName="employeeFormState.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"
              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"
              v-model:zipCode="currentFromDataEmployee.zipCode"
              employee
              dense
              class="q-mb-xl"
            />

            <FormEmployeePassport
              prefix-id="drawer-info-employee"
              id="form-passport"
              dense
              outlined
              separator
              :title="$t('customerEmployee.form.group.passport')"
              v-model:passport-type="currentFromDataEmployee.passportType"
              v-model:passport-number="currentFromDataEmployee.passportNumber"
              v-model:passport-issue-date="
                currentFromDataEmployee.passportIssueDate
              "
              v-model:passport-expiry-date="
                currentFromDataEmployee.passportExpiryDate
              "
              v-model:passport-issuing-place="
                currentFromDataEmployee.passportIssuingPlace
              "
              v-model:passport-issuing-country="
                currentFromDataEmployee.passportIssuingCountry
              "
              v-model:previous-passport-reference="
                currentFromDataEmployee.previousPassportReference
              "
              class="q-mb-xl"
            />

            <FormEmployeeVisa
              prefix-id="drawer-info-employee"
              id="form-visa"
              dense
              outlined
              title="customerEmployee.form.group.visa"
              v-model:visa-type="currentFromDataEmployee.visaType"
              v-model:visa-number="currentFromDataEmployee.visaNumber"
              v-model:visa-issue-date="currentFromDataEmployee.visaIssueDate"
              v-model:visa-expiry-date="currentFromDataEmployee.visaExpiryDate"
              v-model:visa-issuing-place="
                currentFromDataEmployee.visaIssuingPlace
              "
              v-model:visa-stay-until-date="
                currentFromDataEmployee.visaStayUntilDate
              "
              v-model:tm6-number="currentFromDataEmployee.tm6Number"
              v-model:entry-date="currentFromDataEmployee.entryDate"
              class="q-mb-xl"
            />
          </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('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;
                  }
                }
              "
            />
          </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"
    :default-url="customerFormState.defaultCustomerImageUrl"
    clear-button
    @save="
      async (v) => {
        if (v && customerFormState.editCustomerId) {
          await customerStore.setImage(customerFormState.editCustomerId, v);
          await fetchListCustomer();
          customerFormState.imageDialog = false;
        }
      }
    "
  >
    <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.customerType === 'CORP' ? '#5f1775' : '#347454'}`"
        >
          <q-img
            :src="`/images/customer-${customerFormData.customerType}-avartar.png`"
            fit="contain"
            style="height: 100%"
          />
        </div>
      </div>
    </template>
  </ImageUploadDialog>

  <ImageUploadDialog
    ref="dialogEmployeeImageUpload"
    v-model:dialog-state="employeeFormState.imageDialog"
    v-model:file="currentFromDataEmployee.image"
    v-model:image-url="employeeFormState.profileUrl"
    :hidden-footer="
      !currentFromDataEmployee.image || !employeeFormState.profileUrl
    "
    clear-button
    @save="
      async () => {
        await employeeFormStore.submitPersonal();
      }
    "
  >
    <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="
      $t(`form.title.${customerFormState.dialogType}`, {
        name: $t('customer.employer'),
      })
    "
    :badgeClass="
      customerFormData.gender === 'male'
        ? 'app-bg-male text-white'
        : customerFormData.gender === 'female'
          ? 'app-bg-female text-white'
          : ''
    "
    :close="
      () => {
        customerFormState.drawerModal = false;
      }
    "
    :submit="
      async () => {
        await customerFormStore.submitFormCustomer();
        customerFormState.readonly = true;
        notify('create', $t('success'));
        await fetchListCustomer();
      }
    "
    :show="
      async () => {
        await fetchListOfOptionBranch();
        customerFormStore.resetForm(customerFormState.dialogType === 'create');
      }
    "
    :before-close="
      () => {
        if (customerFormStore.isFormDataDifferent()) {
          customerConfirmUnsave();
          return false;
        } else {
          fetchListCustomer();
          customerFormState.branchIndex = -1;
        }
        return false;
      }
    "
  >
    <div class="column full-height">
      <div class="q-px-lg q-pt-lg surface-2">
        <ProfileBanner
          active
          hide-fade
          :fallback-cover="`/images/customer-${customerFormData.customerType}-banner-bg.jpg`"
          :img="
            customerFormState.customerImageUrl ||
            `/images/customer-${customerFormData.customerType}-avartar.png`
          "
          color="hsla(var(--pink-6-hsl)/1)"
          bg-color="hsla(var(--pink-6-hsl)/0.15)"
          @view="customerFormState.imageDialog = true"
          @edit="dialogCustomerImageUpload?.browse()"
        />
      </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',
                  },
                  ...(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"
              />
            </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
              class="q-mb-xl"
              :readonly="
                (customerFormState.dialogType === 'edit' &&
                  customerFormState.readonly === true) ||
                customerFormState.dialogType === 'info'
              "
              :action-disabled="customerFormState.branchIndex !== -1"
              id="form-basic-info-customer"
              :create="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:code="customerFormData.code"
              v-model:registered-branch-id="customerFormData.registeredBranchId"
              v-model:branch-options="registerAbleBranchOption"
              v-model:first-name="customerFormData.firstName"
              v-model:last-name="customerFormData.lastName"
              v-model:first-name-en="customerFormData.firstNameEN"
              v-model:last-name-en="customerFormData.lastNameEN"
              v-model:name-prefix="customerFormData.namePrefix"
              v-model:gender="customerFormData.gender"
              v-model:birth-date="customerFormData.birthDate"
            />

            <div class="row q-col-gutter-sm" id="form-branch-customer-branch">
              <div
                class="col-12 text-weight-bold text-body1 row items-center"
                :style="{
                  opacity:
                    customerFormState.branchIndex !== -1 ? '0.5' : undefined,
                }"
              >
                <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>
                <AddButton
                  icon-only
                  type="button"
                  class="q-ml-sm"
                  @click="customerFormStore.addCurrentCustomerBranch()"
                  v-if="
                    customerFormState.branchIndex === -1 &&
                    !!customerFormState.editCustomerId
                  "
                  :disabled="!customerFormState.readonly"
                />
              </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 === 'CORP') {
                        filtdRequire.main = ['legalPersonNo', 'registerName'];
                      }
                      if (customerFormData.customerType === 'PERS') {
                        filtdRequire.main = ['citizenId'];
                      }

                      let tapIsUndefined = validateFiltdRequire(
                        customerFormData.customerBranch?.[idx],
                        filtdRequire,
                      );

                      if (tapIsUndefined.length > 0) {
                        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;
                          },
                        });
                      } else {
                        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,
                            },
                          );
                        }

                        await customerFormStore.assignFormData(
                          customerFormState.editCustomerId,
                        );
                        customerFormStore.resetForm();
                      }
                    }
                  "
                >
                  <EmployerFormBranch
                    v-if="!!customerFormState.editCustomerId"
                    :index="idx"
                    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
    hide-action
    v-model:drawer-open="employeeFormState.drawerModal"
    :close="
      () => {
        employeeFormState.drawerModal = false;
      }
    "
    :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;
      }
    "
    :show="
      () => {
        employeeFormStore.resetFormDataEmployee(true);
      }
    "
    :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
          @view="employeeFormState.imageDialog = true"
          @edit="
            dialogEmployeeImageUpload && dialogEmployeeImageUpload.browse()
          "
          @update:toggle-status="
            (v) => {
              if (currentFromDataEmployee.id !== undefined)
                triggerChangeStatus(currentFromDataEmployee.id, v);
            }
          "
          active
          use-toggle
          color="white"
          icon="mdi-account-outline"
          bg-color="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"
          v-model:cover-url="employeeFormState.profileUrl"
          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="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' },
          ]"
          :menu="formMenuIconEmployee"
          :toggle-title="$t('status.title')"
          :hide-fade="
            employeeFormState.profileUrl === '' ||
            employeeFormState.profileUrl === undefined
          "
        />
      </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('อัปโหลดไฟล์'),
                      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%"
              >
                <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:zipCode="currentFromDataEmployee.zipCode"
                v-model:sameWithEmployer="
                  employeeFormState.formDataEmployeeSameAddr
                "
                :readonly="!employeeFormState.isEmployeeEdit"
                prefix-id="drawer-info-personnel"
                dense
                class="q-mb-xl"
              />
              <FormEmployeePassport
                prefix-id="drawer-info-employee"
                id="drawer-form-passport"
                dense
                outlined
                separator
                :title="'customerEmployee.form.group.passport'"
                :readonly="!employeeFormState.isEmployeeEdit"
                v-model:passport-type="currentFromDataEmployee.passportType"
                v-model:passport-number="currentFromDataEmployee.passportNumber"
                v-model:passport-issue-date="
                  currentFromDataEmployee.passportIssueDate
                "
                v-model:passport-expiry-date="
                  currentFromDataEmployee.passportExpiryDate
                "
                v-model:passport-issuing-place="
                  currentFromDataEmployee.passportIssuingPlace
                "
                v-model:passport-issuing-country="
                  currentFromDataEmployee.passportIssuingCountry
                "
                v-model:previous-passport-reference="
                  currentFromDataEmployee.previousPassportReference
                "
                class="q-mb-xl"
              />
              <FormEmployeeVisa
                prefix-id="drawer-info-employee"
                id="drawer-form-visa"
                dense
                outlined
                title="customerEmployee.form.group.visa"
                :readonly="!employeeFormState.isEmployeeEdit"
                v-model:visa-type="currentFromDataEmployee.visaType"
                v-model:visa-number="currentFromDataEmployee.visaNumber"
                v-model:visa-issue-date="currentFromDataEmployee.visaIssueDate"
                v-model:visa-expiry-date="
                  currentFromDataEmployee.visaExpiryDate
                "
                v-model:visa-issuing-place="
                  currentFromDataEmployee.visaIssuingPlace
                "
                v-model:visa-stay-until-date="
                  currentFromDataEmployee.visaStayUntilDate
                "
                v-model:tm6-number="currentFromDataEmployee.tm6Number"
                v-model:entry-date="currentFromDataEmployee.entryDate"
                class="q-mb-xl"
              />

              <UploadFile
                :tree="[]"
                :dropdown-list="uploadFileList"
                @send-ocr="
                  async (v: any, f: any) => {
                    console.log(v, f);

                    await ocrStore.sendOcr({ file: f });
                  }
                "
              />
            </template>
            <template v-if="employeeFormState.currentTab === 'healthCheck'">
              <FormEmployeeHealthCheck
                v-if="employeeFormState.currentTab === 'healthCheck'"
                id="drawer-form-checkup"
                prefix-id="drawer-employee"
                dense
                outlined
                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('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
                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
                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>
