<script setup lang="ts">
import { ref, onMounted, watch, computed } from 'vue';
import { storeToRefs } from 'pinia';
import { useI18n } from 'vue-i18n';

import useUserStore from 'stores/user';
import useFlowStore from 'stores/flow';
import useBranchStore from 'stores/branch';
import useOptionStore from 'stores/options';
import useAddressStore from 'stores/address';
import useMyBranch from 'src/stores/my-branch';
import { calculateAge } from 'src/utils/datetime';
import { useQuasar, type QTableProps } from 'quasar';
import useUtilsStore, { dialog, baseUrl } from 'stores/utils';
import { isRoleInclude, resetScrollBar } from 'src/stores/utils';
import { BranchUserStats } from 'stores/branch/types';

import {
  User,
  UserAttachmentCreate,
  UserCreate,
  UserTypeStats,
} from 'stores/user/types';

import {
  EditButton,
  DeleteButton,
  SaveButton,
  UndoButton,
} from 'components/button';

import NoData from 'components/NoData.vue';
import { AddressForm } from 'components/form';
import SideMenu from 'components/SideMenu.vue';
import AddButton from 'components/AddButton.vue';
import DialogForm from 'components/DialogForm.vue';
import DrawerInfo from 'components/DrawerInfo.vue';
import ProfileBanner from 'components/ProfileBanner.vue';
import PersonCard from 'components/shared/PersonCard.vue';
import KebabAction from 'components/shared/KebabAction.vue';
import TooltipComponent from 'components/TooltipComponent.vue';
import StatCardComponent from 'components/StatCardComponent.vue';
import ImageUploadDialog from 'components/ImageUploadDialog.vue';
import ButtonAddComponent from 'components/ButtonAddCompoent.vue';
import PaginationComponent from 'components/PaginationComponent.vue';
import InfoForm from 'components/02_personnel-management/InfoForm.vue';
import FormPerson from 'components/02_personnel-management/FormPerson.vue';
import FormByType from 'components/02_personnel-management/FormByType.vue';
import FormInformation from 'components/02_personnel-management/FormInformation.vue';

const { locale, t } = useI18n();
const $q = useQuasar();

const userStore = useUserStore();
const flowStore = useFlowStore();
const utilsStore = useUtilsStore();
const optionStore = useOptionStore();
const branchStore = useBranchStore();
const adrressStore = useAddressStore();
const useMyBranchStore = useMyBranch();
const { data: userData } = storeToRefs(userStore);
const { myBranch } = storeToRefs(useMyBranchStore);

// state & control
const modal = ref(false);
const isEdit = ref(false);
const hideStat = ref(false);
const modeView = ref(false);
const infoDrawer = ref(false);
const isImageEdit = ref(false);
const imageDialog = ref(false);
const infoDrawerEdit = ref(false);
const refreshImageState = ref(false);

const inputSearch = ref('');
const currentTab = ref<string>('ALL');
const statusFilter = ref<'all' | 'statusACTIVE' | 'statusINACTIVE'>('all');

const currentPage = ref(1);
const pageSize = ref(30);
const currentMaxPage = computed(() =>
  userData.value ? Math.ceil(userData.value?.total / pageSize.value) : 1,
);

// form & data
const hqId = ref<string>();
const brId = ref<string>();
const currentUser = ref<User>();
const userCode = ref<string>();

const statusToggle = ref(true);
const agencyFile = ref<File[]>([]);
const agencyFileList = ref<{ name: string; url: string }[]>([]);

const typeStats = ref<UserTypeStats>();
const userStats = ref<BranchUserStats[]>();

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

const defaultFormData = {
  provinceId: null,
  districtId: null,
  subDistrictId: null,
  telephoneNo: '',
  email: '',
  zipCode: '',
  gender: '',
  addressEN: '',
  address: '',
  mooEN: '',
  moo: '',
  soiEN: '',
  soi: '',
  streetEN: '',
  street: '',
  trainingPlace: null,
  importNationality: null,
  sourceNationality: null,
  licenseExpireDate: null,
  licenseIssueDate: null,
  licenseNo: null,
  discountCondition: null,
  retireDate: null,
  startDate: null,
  registrationNo: null,
  lastNameEN: '',
  lastName: '',
  firstNameEN: '',
  firstName: '',
  userRole: '',
  userType: '',
  birthDate: null,
  responsibleArea: null,
  username: '',
  status: 'CREATED',
  checkpoint: null,
  checkpointEN: null,
  namePrefix: null,
  middleNameEN: '',
  middleName: '',
  citizenExpire: null,
  citizenIssue: null,
  citizenId: '',
};

const formData = ref<UserCreate>({
  selectedImage: '',
  branchId: '',
  provinceId: null,
  districtId: null,
  subDistrictId: null,
  telephoneNo: '',
  email: '',
  zipCode: '',
  gender: '',
  addressEN: '',
  address: '',
  mooEN: '',
  moo: '',
  soiEN: '',
  soi: '',
  streetEN: '',
  street: '',
  trainingPlace: null,
  importNationality: null,
  sourceNationality: null,
  licenseExpireDate: null,
  licenseIssueDate: null,
  licenseNo: null,
  discountCondition: null,
  retireDate: null,
  startDate: null,
  registrationNo: null,
  lastNameEN: '',
  lastName: '',
  middleNameEN: '',
  middleName: '',
  firstNameEN: '',
  firstName: '',
  namePrefix: null,
  userRole: '',
  userType: '',
  birthDate: null,
  responsibleArea: null,
  checkpoint: null,
  checkpointEN: null,
  username: '',
  status: 'CREATED',
  citizenExpire: null,
  citizenIssue: null,
  citizenId: '',
});

const fieldSelectedOption = ref<{ label: string; value: string }[]>([
  {
    label: 'general.order',
    value: 'orderNumber',
  },

  {
    label: 'general.fullName',
    value: 'name',
  },
  {
    label: 'general.type',
    value: 'type',
  },
  {
    label: 'general.telephone',
    value: 'telephoneNo',
  },
  {
    label: 'personnel.age',
    value: 'birthDate',
  },
  {
    label: 'form.email',
    value: 'email',
  },
  {
    label: 'personnel.form.userRole',
    value: 'userRole',
  },
]);

const fieldSelected = ref<
  (
    | 'orderNumber'
    | 'name'
    | 'type'
    | 'telephoneNo'
    | 'birthDate'
    | 'email'
    | 'userRole'
  )[]
>([
  'orderNumber',
  'name',
  'type',
  'telephoneNo',
  'birthDate',
  'email',
  'userRole',
]);

const columns = [
  {
    name: 'orderNumber',
    align: 'center',
    label: 'general.order',
    field: 'branchNo',
  },

  {
    name: 'name',
    align: 'left',
    label: 'general.fullName',
    field: 'firstName',
  },
  {
    name: 'type',
    align: 'left',
    label: 'general.type',
    field: 'type',
  },
  {
    name: 'telephoneNo',
    align: 'left',
    label: 'general.telephone',
    field: 'telephoneNo',
  },
  {
    name: 'birthDate',
    align: 'left',
    label: 'personnel.age',
    field: 'birthDate',
  },
  {
    name: 'email',
    align: 'left',
    label: 'form.email',
    field: 'email',
  },

  {
    name: 'userRole',
    align: 'left',
    label: 'personnel.form.userRole',
    field: 'userRole',
  },
] satisfies QTableProps['columns'];

function undo() {
  if (!currentUser.value) return;
  isImageEdit.value = false;
  infoDrawerEdit.value = false;
  assignFormData(currentUser.value.id);
}

function mapRole(value: string) {
  const option = userStore.userOption.roleOpts.find(
    (option) => option.value === value,
  );
  return option ? option.label : '-';
}

function mapUserType(label: string) {
  const userTypeMap: { [key: string]: string } = {
    USER: 'USER',
    MESSENGER: 'MESSENGER',
    DELEGATE: 'DELEGATE',
    AGENCY: 'AGENCY',
  };
  formData.value.userType = userTypeMap[label];
}

function onClose(excludeDialog?: boolean) {
  if (excludeDialog) {
    infoDrawer.value = excludeDialog || false;
    return;
  }
  hqId.value = '';
  brId.value = '';
  userCode.value = '';
  urlProfile.value = '';
  profileFileImg.value = null;
  infoDrawerEdit.value = false;
  agencyFile.value = [];
  modal.value = false;
  isEdit.value = false;
  statusToggle.value = true;
  isImageEdit.value = false;
  currentUser.value = undefined;
  Object.assign(formData.value, defaultFormData);
  mapUserType(currentTab.value);
  imageList.value = { selectedImage: '', list: [] };
  onCreateImageList.value = { selectedImage: '', list: [] };
  flowStore.rotate();
}

async function openDialog(
  action?: 'FORM' | 'INFO',
  id?: string,
  isPersonEdit: boolean = false,
) {
  if (userStore.userOption.hqOpts.length === 0) {
    await userStore.fetchHqOption();
  }

  if (userStore.userOption.roleOpts.length === 0) {
    await userStore.fetchRoleOption();
  }

  if (id && userData.value) {
    isEdit.value = true;
    await assignFormData(id);

    if (formData.value.userType === 'AGENCY') {
      const result = await userStore.fetchAttachment(id);

      if (result) {
        agencyFileList.value = result;
      }
    }
  }
  if (userStore.userOption.hqOpts.length !== 0 && !id) {
    hqId.value = userStore.userOption.hqOpts[0].value;
  }
  if (userStore.userOption.hqOpts.length === 0) {
    dialog({
      color: 'warning',
      icon: 'mdi-alert',
      title: t('form.warning.title'),
      actionText: t('ok'),
      persistent: true,
      message: t('dialog.message.headquartersNotEstablished'),
      action: async () => {},
    });

    return;
  }

  if (action === 'FORM') {
    modal.value = true;

    if (isRoleInclude(['branch_manager'])) {
      hqId.value =
        myBranch.value?.[0].isHeadOffice === true
          ? myBranch.value?.[0].id
          : myBranch.value?.[0].headOfficeId || '';

      brId.value =
        myBranch.value?.[0].isHeadOffice === true ? '' : myBranch.value?.[0].id;
    }
  } else if (action === 'INFO') {
    if (!userData.value) return;

    infoDrawerEdit.value = isPersonEdit ? true : false;
    infoDrawer.value = true;
  }

  statusToggle.value = true;
  userStore.userOption.brOpts = [];
}

async function onSubmit(excludeDialog?: boolean) {
  if (isEdit.value && currentUser.value) {
    if (!currentUser.value.id) return;

    formData.value.branchId = brId.value
      ? brId.value
      : hqId.value
        ? hqId.value
        : '';
    const formDataEdit = {
      ...formData.value,
      status: !statusToggle.value ? 'INACTIVE' : 'ACTIVE',
    } as const;

    await userStore.editById(currentUser.value.id, formDataEdit);

    if (currentUser.value.id && formDataEdit.userType === 'AGENCY') {
      if (!agencyFile.value) return;
      const payload: UserAttachmentCreate = {
        file: agencyFile.value,
      };

      if (payload?.file) {
        await userStore.addAttachment(currentUser.value.id, payload);
      }
    }

    await fetchUserList();
    typeStats.value = await userStore.typeStats();
    const res = await branchStore.userStats(formData.value.userType);
    if (res) {
      userStats.value = res;
    }
    onClose(excludeDialog);
  } else {
    if (!hqId.value) return;

    if (statusToggle.value) {
      formData.value.status = 'CREATED';
    } else {
      formData.value.status = 'INACTIVE';
    }

    formData.value.branchId = brId.value
      ? brId.value
      : hqId.value
        ? hqId.value
        : '';
    const result = await userStore.create(
      formData.value,
      onCreateImageList.value,
    );

    if (result && formData.value.userType === 'AGENCY') {
      if (!agencyFile.value) return;

      const payload: UserAttachmentCreate = {
        file: agencyFile.value,
      };

      if (payload?.file) {
        await userStore.addAttachment(result.id, payload);
      }
    }

    currentTab.value = formData.value.userType;

    await fetchUserList();

    typeStats.value = await userStore.typeStats();
    const res = await branchStore.userStats(formData.value.userType);
    if (res) {
      userStats.value = res;
    }
    onClose();
  }
  flowStore.rotate();
}

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

      await fetchUserList();
      typeStats.value = await userStore.typeStats();
      infoDrawer.value = false;
      flowStore.rotate();
    },
    cancel: () => {},
  });
}

async function toggleStatus(id: string) {
  const record = userData.value?.result.find((v) => v.id === id);

  if (!record) return;

  const res = await userStore.editById(record.id, {
    status: record.status !== 'INACTIVE' ? 'INACTIVE' : 'ACTIVE',
  });
  if (res) {
    record.status = res.status;
    formData.value.status = res.status;

    await fetchUserList();
  }
}

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 () => {
        await toggleStatus(id).then(resolve).catch(reject);
      },
      cancel: () => {},
    });
  });
}

async function assignFormData(idEdit: string) {
  if (!userData.value) return;
  const foundUser = userData.value.result.find((user) => user.id === idEdit);

  if (foundUser) {
    currentUser.value = foundUser;
    formData.value = {
      branchId: foundUser.branch[0]?.id,
      provinceId: foundUser.provinceId,
      districtId: foundUser.districtId,
      subDistrictId: foundUser.subDistrictId,
      telephoneNo: foundUser.telephoneNo,
      email: foundUser.email,
      zipCode: foundUser.zipCode,
      gender: foundUser.gender,
      addressEN: foundUser.addressEN,
      address: foundUser.address,
      moo: foundUser.moo,
      mooEN: foundUser.mooEN,
      soi: foundUser.soi,
      soiEN: foundUser.soiEN,
      street: foundUser.street,
      streetEN: foundUser.streetEN,
      trainingPlace: foundUser.trainingPlace,
      importNationality: foundUser.importNationality,
      sourceNationality: foundUser.sourceNationality,
      licenseNo: foundUser.licenseNo,
      discountCondition: foundUser.discountCondition,
      registrationNo: foundUser.registrationNo,
      lastNameEN: foundUser.lastNameEN,
      lastName: foundUser.lastName,
      middleNameEN: foundUser.middleNameEN,
      middleName: foundUser.middleName,
      firstNameEN: foundUser.firstNameEN,
      firstName: foundUser.firstName,
      namePrefix: foundUser.namePrefix,
      userRole: foundUser.userRole,
      userType: foundUser.userType,
      username: foundUser.username,
      checkpoint: foundUser.checkpoint,
      checkpointEN: foundUser.checkpointEN,
      responsibleArea: foundUser.responsibleArea,
      status: foundUser.status,
      selectedImage: foundUser.selectedImage,
      licenseExpireDate:
        (foundUser.licenseExpireDate &&
          new Date(foundUser.licenseExpireDate)) ||
        null,
      licenseIssueDate:
        (foundUser.licenseIssueDate && new Date(foundUser.licenseIssueDate)) ||
        null,
      retireDate:
        (foundUser.retireDate && new Date(foundUser.retireDate)) || null,
      startDate: (foundUser.startDate && new Date(foundUser.startDate)) || null,
      birthDate: (foundUser.birthDate && new Date(foundUser.birthDate)) || null,
      citizenId: foundUser.citizenId,
      citizenIssue:
        (foundUser.citizenIssue && new Date(foundUser.citizenIssue)) || null,
      citizenExpire:
        (foundUser.citizenExpire && new Date(foundUser.citizenExpire)) || null,
    };

    formData.value.status === 'ACTIVE' || 'CREATED'
      ? (statusToggle.value = true)
      : (statusToggle.value = false);

    if (foundUser.branch) {
      if (foundUser.branch?.[0].isHeadOffice) {
        hqId.value = foundUser.branch[0].id as string;
      } else {
        hqId.value = foundUser.branch[0].headOfficeId as string;
        brId.value = foundUser.branch[0].id;
      }
    }

    userCode.value = foundUser.code;
    urlProfile.value = `${baseUrl}/user/${foundUser.id}/profile-image/${foundUser.selectedImage}`;

    isEdit.value = true;
    hqId.value && (await userStore.fetchBrOption(hqId.value));

    await fetchImageList(foundUser.id, foundUser.selectedImage);

    if (formData.value.districtId) {
      await adrressStore.fetchSubDistrictByProvinceId(
        formData.value.districtId,
      );
    }
  }
}

async function fetchImageList(id: string, selectedName: string) {
  const res = await userStore.fetchImageListById(id);
  imageList.value = {
    selectedImage: selectedName,
    list: res.map((n: string) => `user/${id}/profile-image/${n}`),
  };
  return res;
}

async function fetchUserList() {
  await userStore.fetchList({
    includeBranch: true,
    pageSize: pageSize.value,
    page: currentPage.value,
    query: !!inputSearch.value ? inputSearch.value : undefined,
    userType: currentTab.value === 'ALL' ? undefined : currentTab.value,
    status:
      statusFilter.value === 'all'
        ? undefined
        : statusFilter.value === 'statusACTIVE'
          ? 'ACTIVE'
          : 'INACTIVE',
  });
}

onMounted(async () => {
  utilsStore.currentTitle.title = 'personnel.title';
  utilsStore.currentTitle.path = [{ text: 'personnel.caption', i18n: true }];
  modeView.value = $q.screen.lt.md ? true : false;

  await fetchUserList();
  if (optionStore.globalOption) {
    userStore.userOption.genderOpts = optionStore.globalOption.gender;
    userStore.userOption.responsibleAreaOpts = optionStore.globalOption.area;
    userStore.userOption.nationalityOpts = optionStore.globalOption.nationality;
    userStore.userOption.trainingPlaceOpts = optionStore.globalOption.training;
  }

  typeStats.value = await userStore.typeStats();
  const res = await branchStore.userStats(formData.value.userType);
  if (res) {
    userStats.value = res;
  }
  flowStore.rotate();
});

watch(
  () => currentTab.value,
  async (label) => {
    mapUserType(label);
    await fetchUserList();
    const res = await branchStore.userStats(label);
    if (res) {
      userStats.value = res;
    }
  },
);

watch(
  () => formData.value.userType,
  async () => {
    if (!infoDrawerEdit.value) return;
    formData.value.registrationNo = null;
    formData.value.startDate = null;
    formData.value.retireDate = null;
    formData.value.responsibleArea = null;
    formData.value.discountCondition = null;
    formData.value.sourceNationality = null;
    formData.value.importNationality = null;
    formData.value.trainingPlace = null;
    formData.value.checkpoint = null;
    formData.value.checkpointEN = null;
    agencyFile.value = [];
  },
);

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

watch([inputSearch, statusFilter], async () => await fetchUserList());

watch(
  () => $q.screen.lt.md,
  (v) => {
    if (v) modeView.value = true;
  },
);
</script>

<template>
  <ButtonAddComponent
    style="z-index: 999"
    hide-icon
    @click="openDialog('FORM')"
  ></ButtonAddComponent>

  <!-- stat -->
  <div class="column full-height no-wrap">
    <div class="text-body-2 q-mb-xs flex items-center">
      {{ $t('general.dataSum') }}
      <q-badge
        v-if="typeStats"
        rounded
        class="q-ml-sm"
        style="
          background-color: hsla(var(--info-bg) / 0.15);
          color: hsl(var(--info-bg));
        "
      >
        {{
          currentTab === 'ALL'
            ? Object.values(typeStats).reduce((acc, val) => acc + val, 0)
            : typeStats[currentTab]
        }}
      </q-badge>
      <q-btn
        class="q-ml-sm"
        icon="mdi-pin-outline"
        color="primary"
        size="sm"
        flat
        dense
        rounded
        @click="hideStat = !hideStat"
        :style="hideStat ? 'rotate: 90deg' : ''"
        style="transition: 0.1s ease-in-out"
      />
    </div>

    <transition name="slide">
      <div v-if="!hideStat" class="scroll q-mb-md">
        <div style="display: inline-block">
          <StatCardComponent
            v-if="typeStats && userData?.result"
            label-i18n
            :branch="
              currentTab === 'ALL'
                ? Object.entries(typeStats).map(([key, val]) => ({
                    count: val,
                    label: `personnel.${key}`,
                    icon: 'mdi-account-outline',
                    color:
                      (
                        {
                          USER: 'cyan',
                          MESSENGER: 'yellow',
                          DELEGATE: 'red',
                          AGENCY: 'magenta',
                        } as const
                      )[key] || 'pink',
                  }))
                : [
                    {
                      label: `personnel.${currentTab}`,
                      count: typeStats[currentTab],
                      icon: 'mdi-account-outline',
                      color:
                        currentTab === 'USER'
                          ? 'cyan'
                          : currentTab === 'MESSENGER'
                            ? 'yellow'
                            : currentTab === 'DELEGATE'
                              ? 'red'
                              : 'magenta',
                    },
                  ]
            "
            :dark="$q.dark.isActive"
          />
        </div>
      </div>
    </transition>

    <!-- main -->
    <div
      class="col surface-2 rounded justify-between column no-wrap bordered full-height"
      style="overflow: hidden"
    >
      <div class="column">
        <div
          class="row surface-3 justify-between full-width items-center bordered-b"
          style="z-index: 1"
        >
          <div class="row q-py-sm q-px-md justify-between full-width">
            <q-input
              for="input-search"
              outlined
              dense
              :label="$t('general.search')"
              class="q-mr-md 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-12 col-md-5"
              :class="{ 'q-pt-xs': $q.screen.lt.md }"
              style="white-space: nowrap"
            >
              <q-select
                v-model="statusFilter"
                outlined
                dense
                option-value="value"
                option-label="label"
                class="col"
                :class="{ 'offset-md-5': modeView }"
                map-options
                emit-value
                :for="'field-select-status'"
                :hide-dropdown-icon="$q.screen.lt.sm"
                :options="[
                  { label: $t('general.all'), value: 'all' },
                  { label: $t('general.active'), value: 'statusACTIVE' },
                  { label: $t('general.inactive'), value: 'statusINACTIVE' },
                ]"
              ></q-select>

              <q-select
                v-if="!modeView"
                id="select-field"
                for="select-field"
                class="col q-ml-sm"
                :options="
                  fieldSelectedOption.map((v) => ({
                    ...v,
                    label: $t(v.label),
                  }))
                "
                :display-value="$t('general.displayField')"
                :hide-dropdown-icon="$q.screen.lt.sm"
                v-model="fieldSelected"
                option-label="label"
                option-value="value"
                map-options
                emit-value
                outlined
                multiple
                dense
              />

              <q-btn-toggle
                id="btn-mode"
                v-model="modeView"
                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
                    name="mdi-view-grid-outline"
                    size="16px"
                    class="q-px-sm q-py-xs rounded"
                    :style="{
                      color: $q.dark.isActive
                        ? modeView
                          ? '#C9D3DB '
                          : '#787B7C'
                        : modeView
                          ? '#787B7C'
                          : '#C9D3DB',
                    }"
                  />
                </template>
                <template v-slot:list>
                  <q-icon
                    name="mdi-format-list-bulleted"
                    class="q-px-sm q-py-xs rounded"
                    size="16px"
                    :style="{
                      color: $q.dark.isActive
                        ? modeView === false
                          ? '#C9D3DB'
                          : '#787B7C'
                        : modeView === false
                          ? '#787B7C'
                          : '#C9D3DB',
                    }"
                  />
                </template>
              </q-btn-toggle>
            </div>
          </div>
        </div>

        <div class="surface-2 bordered-b q-px-md full-width">
          <q-tabs
            inline-label
            mobile-arrows
            dense
            v-model="currentTab"
            align="left"
            class="full-width"
            active-color="info"
          >
            <q-tab
              name="ALL"
              @click="
                async () => {
                  currentPage = 1;
                  inputSearch = '';
                  currentTab = 'ALL';
                  statusFilter = 'all';
                  flowStore.rotate();
                }
              "
            >
              <div
                class="row text-capitalize"
                :class="currentTab === 'ALL' ? 'text-bold' : 'app-text-muted'"
              >
                {{ $t('general.all') }}
              </div>
            </q-tab>
            <q-tab
              name="USER"
              @click="
                async () => {
                  currentTab = 'USER';
                  statusFilter = 'all';
                  currentPage = 1;
                  inputSearch = '';
                  flowStore.rotate();
                }
              "
            >
              <div
                class="row text-capitalize"
                :class="currentTab === 'USER' ? 'text-bold' : 'app-text-muted'"
              >
                {{ $t('personnel.USER') }}
              </div>
            </q-tab>
            <q-tab
              name="MESSENGER"
              @click="
                async () => {
                  currentTab = 'MESSENGER';
                  statusFilter = 'all';
                  currentPage = 1;
                  inputSearch = '';
                  flowStore.rotate();
                }
              "
            >
              <div
                class="row text-capitalize"
                :class="
                  currentTab === 'MESSENGER' ? 'text-bold' : 'app-text-muted'
                "
              >
                {{ $t('personnel.MESSENGER') }}
              </div>
            </q-tab>
            <q-tab
              name="DELEGATE"
              @click="
                async () => {
                  currentTab = 'DELEGATE';
                  statusFilter = 'all';
                  currentPage = 1;
                  inputSearch = '';
                  flowStore.rotate();
                }
              "
            >
              <div
                class="row text-capitalize"
                :class="
                  currentTab === 'DELEGATE' ? 'text-bold' : 'app-text-muted'
                "
              >
                {{ $t('personnel.DELEGATE') }}
              </div>
            </q-tab>
            <q-tab
              name="AGENCY"
              @click="
                async () => {
                  currentTab = 'AGENCY';
                  statusFilter = 'all';
                  currentPage = 1;
                  inputSearch = '';
                  flowStore.rotate();
                }
              "
            >
              <div
                class="row text-capitalize"
                :class="
                  currentTab === 'AGENCY' ? 'text-bold' : 'app-text-muted'
                "
              >
                {{ $t('personnel.AGENCY') }}
              </div>
            </q-tab>
          </q-tabs>
        </div>
      </div>

      <div
        class="flex full-width full-height q-pa-md surface-2 column col scroll"
      >
        <template v-if="userData && userData.total > 0">
          <q-table
            flat
            bordered
            :grid="modeView"
            :rows="userData.result"
            :columns="columns"
            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',
                }"
                :props="props"
                :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')"
                >
                  {{ (currentPage - 1) * pageSize + props.rowIndex + 1 }}
                </q-td>

                <q-td v-if="fieldSelected.includes('name')">
                  <div class="row items-center" style="flex-wrap: nowrap">
                    <div style="display: flex">
                      <div class="q-mr-md">
                        <div
                          :style="`
                                  border-radius: 50%;
                                  border-style: solid;
                                  border-width: 2px;
                                  border-color: hsl(var(${
                                    {
                                      USER: '--cyan-7-hsl',
                                      MESSENGER: '--orange-4-hsl',
                                      DELEGATE: '--red-6-hsl',
                                      AGENCY: '--pink-8-hsl',
                                    }[props.row.userType as string] ||
                                    '--pink-8-hsl'
                                  }
                                `"
                          class="q-pa-xs"
                        >
                          <q-avatar size="md">
                            <q-img
                              class="text-center"
                              :ratio="1"
                              :src="`${baseUrl}/user/${props.row.id}/profile-image/${props.row.selectedImage}?ts=${Date.now()}`"
                            >
                              <template #error>
                                <div
                                  class="no-padding full-width full-height flex items-center justify-center"
                                  :style="`${props.row.gender ? 'background: white' : 'background: linear-gradient(135deg,rgba(43, 137, 223, 1) 0%, rgba(230, 51, 81, 1) 100%);'}`"
                                >
                                  <q-img
                                    v-if="props.row.gender"
                                    :src="
                                      props.row.gender === 'male'
                                        ? '/no-img-man.png'
                                        : '/no-img-female.png'
                                    "
                                  />
                                  <q-icon
                                    v-else
                                    size="sm"
                                    name="mdi-account-outline"
                                    style="color: white"
                                  />
                                </div>
                              </template>
                            </q-img>

                            <q-badge
                              class="absolute-bottom-right no-padding"
                              style="
                                border-radius: 50%;
                                min-width: 8px;
                                min-height: 8px;
                              "
                              :style="{
                                background: `var(--${props.row.status === 'INACTIVE' ? 'stone-5' : 'green-6'})`,
                              }"
                            ></q-badge>
                          </q-avatar>
                        </div>
                      </div>
                    </div>
                    <div class="column">
                      <div class="col ellipsis" style="max-width: 20vw">
                        {{
                          locale === 'eng'
                            ? `${props.row.firstNameEN} ${props.row.lastNameEN}`.trim()
                            : `${props.row.firstName} ${props.row.lastName}`.trim()
                        }}
                        <q-tooltip
                          anchor="bottom left"
                          self="center left"
                          :delay="300"
                        >
                          {{
                            locale === 'eng'
                              ? `${props.row.firstNameEN} ${props.row.lastNameEN}`.trim()
                              : `${props.row.firstName} ${props.row.lastName}`.trim()
                          }}
                        </q-tooltip>

                        <q-icon
                          class="q-pl-xs"
                          :class="{
                            'symbol-gender': props.row.gender,
                            'symbol-gender__male': props.row.gender === 'male',
                            'symbol-gender__female':
                              props.row.gender === 'female',
                          }"
                          :name="`mdi-gender-${props.row.gender === 'male' ? 'male' : 'female'}`"
                          width="24px"
                        />
                      </div>
                      <div class="app-text-muted">
                        {{ props.row.code || '-' }}
                      </div>
                    </div>
                  </div>
                </q-td>

                <q-td v-if="fieldSelected.includes('type')">
                  <span
                    class="tags"
                    :class="{
                      [`tags__${
                        {
                          USER: 'cyan',
                          MESSENGER: 'yellow',
                          DELEGATE: 'red',
                          AGENCY: 'magenta',
                        }[props.row.userType as string] || 'pink'
                      } }`]: true,
                    }"
                  >
                    {{
                      $t(
                        `personnel.${
                          {
                            USER: 'USER',
                            MESSENGER: 'MESSENGER',
                            DELEGATE: 'DELEGATE',
                            AGENCY: 'AGENCY',
                          }[props.row.userType as string] || 'USER'
                        }`,
                      )
                    }}
                  </span>
                </q-td>

                <q-td v-if="fieldSelected.includes('telephoneNo')">
                  {{ props.row.telephoneNo || '-' }}
                </q-td>

                <q-td v-if="fieldSelected.includes('birthDate')">
                  {{ calculateAge(props.row.birthDate) || '-' }}
                </q-td>

                <q-td v-if="fieldSelected.includes('email')">
                  {{ props.row.email || '-' }}
                </q-td>

                <q-td v-if="fieldSelected.includes('userRole')">
                  <span class="tags tags__purple">
                    {{ mapRole(props.row.userRole) }}
                  </span>
                </q-td>

                <q-td>
                  <q-btn
                    :id="`btn-view-${props.row.username}`"
                    icon="mdi-eye-outline"
                    size="sm"
                    dense
                    round
                    flat
                    @click.stop="
                      () => {
                        openDialog('INFO', props.row.id);
                      }
                    "
                  />
                  <KebabAction
                    :id-name="props.row.username"
                    :status="props.row.status"
                    @view="
                      () => {
                        openDialog('INFO', props.row.id);
                      }
                    "
                    @edit="
                      () => {
                        openDialog('INFO', props.row.id, true);
                      }
                    "
                    @delete="onDelete(props.row.id)"
                    @change-status="
                      async () => {
                        triggerChangeStatus(props.row.id, props.row.status);
                      }
                    "
                  />
                </q-td>
              </q-tr>
            </template>

            <template v-slot:item="props">
              <div class="col-md-3 col-sm-6 col-12">
                <PersonCard
                  :prefix-id="props.row.username"
                  :data="{
                    code: props.row.code,
                    name:
                      locale === 'eng'
                        ? `${props.row.firstNameEN} ${props.row.lastNameEN}`.trim()
                        : `${props.row.firstName} ${props.row.lastName}`.trim(),
                    img: props.row.profileImageUrl
                      ? props.row.profileImageUrl
                      : props.row.userRole.includes('system')
                        ? '/img-admin.png'
                        : props.row.gender === 'male'
                          ? '/no-img-man.png'
                          : '/no-img-female.png',
                    male: props.row.gender === 'male',
                    female: props.row.gender === 'female',
                    detail: [
                      {
                        icon: 'mdi-phone-outline',
                        value: props.row.telephoneNo,
                      },
                      {
                        icon: 'mdi-clock-outline',
                        value:
                          (props.row.birthDate &&
                            calculateAge(props.row.birthDate)) ||
                          '-',
                      },
                    ],
                  }"
                  :tag="[
                    {
                      color:
                        {
                          USER: 'cyan',
                          MESSENGER: 'yellow',
                          DELEGATE: 'red',
                          AGENCY: 'magenta',
                        }[props.row.userType as string] || 'pink',
                      value: $t(`personnel.${props.row.userType}`),
                    },
                  ]"
                  :disabled="props.row.status === 'INACTIVE'"
                  @update-card="(a, b) => openDialog(a, props.row.id, b)"
                  @delete-card="onDelete(props.row.id)"
                  @enter-card="(a) => openDialog(a, props.row.id)"
                  @toggle-status="
                    triggerChangeStatus(props.row.id, props.row.status)
                  "
                >
                  <template #img>
                    <q-img
                      class="text-center"
                      :ratio="1"
                      :src="`${baseUrl}/user/${props.row.id}/profile-image/${props.row.selectedImage}?ts=${Date.now()}`"
                      style="
                        object-fit: cover;
                        width: 100%;
                        height: 100%;
                        border-radius: 50%;
                      "
                    >
                      <template #error>
                        <div
                          class="no-padding full-width full-height flex items-center justify-center"
                          style="
                            background: linear-gradient(
                              135deg,
                              rgba(43, 137, 223, 1) 0%,
                              rgba(230, 51, 81, 1) 100%
                            );
                          "
                        >
                          <q-img
                            v-if="props.row.gender"
                            :src="
                              props.row.gender === 'male'
                                ? '/no-img-man.png'
                                : '/no-img-female.png'
                            "
                          />
                          <q-icon
                            v-else
                            size="lg"
                            name="mdi-account-outline"
                            style="color: white"
                          />
                        </div>
                      </template>
                    </q-img>
                  </template>
                </PersonCard>
              </div>
            </template>
          </q-table>
        </template>

        <div
          v-if="userData && userData.total === 0 && !inputSearch"
          class="full-height column"
        >
          <div class="flex justify-end">
            <TooltipComponent
              title="personnel.tooltipTitle"
              caption="personnel.tooltipCaption"
              imgSrc="personnel-table-"
            />
          </div>

          <div class="col items-center flex justify-center">
            <AddButton
              :label="'personnel.addTitle'"
              :cyanOn="true"
              @trigger="openDialog('FORM')"
            />
          </div>
        </div>

        <div
          v-if="userData?.total === 0 && !!inputSearch"
          class="row col full-width items-center justify-center"
          style="min-height: 250px"
        >
          <NoData :not-found="!!inputSearch" />
        </div>
      </div>

      <div
        class="row justify-between items-center q-px-md q-py-sm"
        v-if="currentMaxPage > 0"
      >
        <div class="col-4">
          <div class="row items-center no-wrap">
            <div class="app-text-muted q-mr-sm" v-if="$q.screen.gt.sm">
              {{ $t('general.recordPerPage') }}
            </div>
            <div>
              <q-btn-dropdown
                dense
                unelevated
                :label="pageSize"
                class="bordered q-pl-md"
              >
                <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 fetchUserList();
                      }
                    "
                  >
                    <q-item-section>
                      <q-item-label>{{ v }}</q-item-label>
                    </q-item-section>
                  </q-item>
                </q-list>
              </q-btn-dropdown>
            </div>
          </div>
        </div>

        <div class="col-4 row justify-center app-text-muted">
          {{
            $t('general.recordsPage', {
              resultcurrentPage: userData?.result.length,
              total: userData?.total,
            })
          }}
        </div>
        <div class="col-4 row justify-end">
          <PaginationComponent
            v-model:current-page="currentPage"
            v-model:max-page="currentMaxPage"
            :fetch-data="async () => await fetchUserList()"
          />
        </div>
      </div>
    </div>
  </div>

  <DrawerInfo
    v-if="currentUser"
    :category="$t('personnel.personnel')"
    bg-on
    hide-action
    :is-edit="infoDrawerEdit"
    :title="
      locale === 'eng'
        ? `${currentUser.firstNameEN} ${currentUser.lastNameEN}`
        : `${currentUser.firstName} ${currentUser.lastName}`
    "
    v-model:drawerOpen="infoDrawer"
    :submit="() => onSubmit()"
    :close="
      () => {
        onClose();
        resetScrollBar('user-form-content');
      }
    "
  >
    <InfoForm>
      <div
        :class="{
          'q-mx-lg q-my-md': $q.screen.gt.sm,
          'q-mx-md q-my-sm': !$q.screen.gt.sm,
        }"
      >
        <ProfileBanner
          :active="formData.status !== 'INACTIVE'"
          useToggle
          color="white"
          icon="mdi-account-outline"
          :bgColor="
            formData.gender
              ? 'white'
              : 'linear-gradient(135deg, rgba(43,137,223,1) 0%, rgba(230,51,81,1) 100%)'
          "
          v-model:toggle-status="formData.status"
          hideFade
          :toggle-title="$t('status.title')"
          :title="`${locale === 'eng' ? `${formData.firstNameEN} ${formData.lastNameEN}` : `${formData.firstName} ${formData.lastName}`}`"
          :caption="userCode"
          :img="
            `${baseUrl}/user/${currentUser.id}/profile-image/${formData.selectedImage}`.concat(
              refreshImageState ? `?ts=${Date.now()}` : '',
            ) ||
            {
              male: '/no-img-man.png',
              female: '/no-img-female.png',
            }[formData.gender]
          "
          :fallback-img="
            {
              male: '/no-img-man.png',
              female: '/no-img-female.png',
            }[formData.gender]
          "
          @view="
            () => {
              imageDialog = true;
              isImageEdit = false;
            }
          "
          @edit="imageDialog = isImageEdit = true"
          @update:toggle-status="
            async (v) => {
              if (!currentUser) return;
              await triggerChangeStatus(currentUser.id, v);
            }
          "
        />
      </div>
      <!-- ย้อนกลับ -->

      <div
        style="flex: 1; width: 100%; overflow-y: auto"
        id="drawer-user-form"
        :class="{
          'q-px-lg q-pb-lg': $q.screen.gt.sm,
          'q-px-md q-pb-sm': !$q.screen.gt.sm,
        }"
      >
        <div
          class="col surface-1 full-height rounded bordered scroll row relative-position"
        >
          <div
            class="rounded row"
            :class="{
              'q-py-md q-px-lg': $q.screen.gt.sm,
              'q-py-sm q-px-lg': !$q.screen.gt.sm,
            }"
            style="position: absolute; z-index: 999; top: 0; right: 0"
          >
            <div
              v-if="formData.status !== 'INACTIVE'"
              class="surface-1 row rounded"
            >
              <UndoButton
                v-if="infoDrawerEdit"
                id="btn-info-basic-undo"
                icon-only
                @click="
                  () => {
                    undo();
                  }
                "
                type="button"
              />
              <SaveButton
                v-if="infoDrawerEdit"
                id="btn-info-basic-save"
                icon-only
                type="submit"
              />
              <EditButton
                v-if="!infoDrawerEdit"
                id="btn-info-basic-edit"
                icon-only
                @click="
                  () => {
                    infoDrawerEdit = true;
                    isImageEdit = true;
                  }
                "
                type="button"
              />
              <DeleteButton
                v-if="!infoDrawerEdit"
                id="btn-info-basic-delete"
                icon-only
                @click="
                  () => {
                    if (!currentUser) return;
                    onDelete(currentUser.id);
                  }
                "
                type="button"
              />
            </div>
          </div>
          <div
            class="col"
            style="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: 'info-information',
                    },
                    {
                      name: $t('personnel.form.personalInformation'),
                      anchor: 'info-personal',
                    },
                    {
                      name: $t('personnel.form.addressInformation'),
                      anchor: 'info-address',
                    },
                  ].concat(
                    !!formData.userType
                      ? [
                          {
                            name: $t('personnel.form.workInformation'),
                            anchor: 'info-work',
                          },
                        ]
                      : [],
                  )
                "
                background="transparent"
                :active="{
                  background: 'hsla(var(--blue-6-hsl) / .2)',
                  foreground: 'var(--blue-6)',
                }"
                scroll-element="#user-form-content"
              />
            </div>
          </div>

          <div
            class="col-12 col-md-10 relative-position"
            :class="{
              'q-py-md q-pr-md ': $q.screen.gt.sm,
              'q-py-md q-px-lg': !$q.screen.gt.sm,
            }"
            id="user-form-content"
            style="height: 100%; max-height: 100; overflow-y: auto"
          >
            <FormInformation
              id="info-information"
              v-model:hq-id="hqId"
              v-model:br-id="brId"
              v-model:user-type="formData.userType"
              v-model:user-role="formData.userRole"
              v-model:username="formData.username"
              v-model:user-code="userCode"
              dense
              outlined
              separator
              :title="'form.field.basicInformation'"
              :readonly="!infoDrawerEdit"
              :username-readonly="isEdit"
              class="q-mb-xl"
            />

            <FormPerson
              id="info-personal"
              v-model:first-name="formData.firstName"
              v-model:last-name="formData.lastName"
              v-model:mid-name="formData.middleName"
              v-model:mid-name-en="formData.middleNameEN"
              v-model:prefix-name="formData.namePrefix"
              v-model:prefix-name-en="formData.namePrefix"
              v-model:first-name-en="formData.firstNameEN"
              v-model:last-name-en="formData.lastNameEN"
              v-model:telephone-no="formData.telephoneNo"
              v-model:email="formData.email"
              v-model:gender="formData.gender"
              v-model:birth-date="formData.birthDate"
              v-model:citizen-id="formData.citizenId"
              v-model:citizen-issue="formData.citizenIssue"
              v-model:citizen-expire="formData.citizenExpire"
              :title="'personnel.form.personalInformation'"
              prefix-id="drawer-info-personnel"
              dense
              outlined
              separator
              :readonly="!infoDrawerEdit"
              class="q-mb-xl"
            />

            <AddressForm
              id="info-address"
              v-model:address="formData.address"
              v-model:address-en="formData.addressEN"
              v-model:moo="formData.moo"
              v-model:moo-en="formData.mooEN"
              v-model:soi="formData.soi"
              v-model:soi-en="formData.soiEN"
              v-model:street="formData.street"
              v-model:street-en="formData.streetEN"
              v-model:province-id="formData.provinceId"
              v-model:district-id="formData.districtId"
              v-model:sub-district-id="formData.subDistrictId"
              v-model:zip-code="formData.zipCode"
              :readonly="!infoDrawerEdit"
              prefix-id="drawer-info-personnel"
              :title="'personnel.form.addressInformation'"
              dense
              class="q-mb-xl"
            />
            <FormByType
              dense
              outlined
              separator
              id="info-work"
              :readonly="!infoDrawerEdit"
              v-model:user-type="formData.userType"
              v-model:registration-no="formData.registrationNo"
              v-model:start-date="formData.startDate"
              v-model:retire-date="formData.retireDate"
              v-model:responsible-area="formData.responsibleArea"
              v-model:discount-condition="formData.discountCondition"
              v-model:source-nationality="formData.sourceNationality"
              v-model:import-nationality="formData.importNationality"
              v-model:training-place="formData.trainingPlace"
              v-model:checkpoint="formData.checkpoint"
              v-model:checkpoint-en="formData.checkpointEN"
              v-model:agency-file="agencyFile"
              v-model:agency-file-list="agencyFileList"
              v-model:user-id="currentUser.id"
            />
          </div>
        </div>
      </div>
    </InfoForm>
  </DrawerInfo>

  <!-- form -->
  <DialogForm
    hideFooter
    removeDialog
    :badgeClass="formData.gender === 'male' ? 'app-bg-male' : 'app-bg-female'"
    :badgeLabel="userCode"
    :title="$t('personnel.addTitle')"
    v-model:modal="modal"
    :addressSeparator="formData.userType !== ''"
    :submit="() => onSubmit()"
    :close="() => onClose()"
  >
    <!-- :title="formData.name"
  :caption="formData.nameEN" -->
    <div
      :class="{
        'q-mx-lg q-my-md': $q.screen.gt.sm,
        'q-mx-md q-my-sm': !$q.screen.gt.sm,
      }"
    >
      <ProfileBanner
        active
        useToggle
        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:toggle-status="formData.status"
        :img="
          urlProfile ||
          {
            male: '/no-img-man.png',
            female: '/no-img-female.png',
          }[formData.gender]
        "
        :toggleTitle="$t('status.title')"
        :title="`${locale === 'eng' ? `${formData.firstNameEN} ${formData.lastNameEN}` : `${formData.firstName} ${formData.lastName}`}`"
        :fallbackImg="
          {
            male: '/no-img-man.png',
            female: '/no-img-female.png',
          }[formData.gender]
        "
        hideFade
        @view="
          () => {
            imageDialog = true;
            isImageEdit = false;
          }
        "
        @edit="imageDialog = isImageEdit = true"
        @update:toggle-status="
          () => {
            formData.status =
              formData.status === 'CREATED' ? 'INACTIVE' : 'CREATED';
          }
        "
      />
    </div>

    <div
      class="col"
      id="personnel-form"
      :class="{
        'q-px-lg q-pb-lg': $q.screen.gt.sm,
        'q-px-md q-pb-sm': !$q.screen.gt.sm,
      }"
    >
      <div
        style="overflow-y: auto"
        class="row full-width full-height surface-1 rounded bordered relative-position"
      >
        <div
          class="rounded row"
          style="position: absolute; z-index: 999; right: 0; top: 0"
          :class="{
            'q-py-md q-px-lg': $q.screen.gt.sm,
            'q-py-sm q-px-lg': !$q.screen.gt.sm,
          }"
        >
          <div
            v-if="formData.status !== 'INACTIVE'"
            class="surface-1 row rounded"
          >
            <SaveButton id="btn-info-basic-save" icon-only type="submit" />
          </div>
        </div>
        <div class="col full-height scroll" v-if="$q.screen.gt.sm">
          <div style="position: sticky; top: 0" class="q-pa-sm">
            <SideMenu
              :menu="
                [
                  {
                    name: $t('form.field.basicInformation'),
                    anchor: 'dialog-form-information',
                  },
                  {
                    name: $t('personnel.form.personalInformation'),
                    anchor: 'dialog-form-personal',
                  },
                  {
                    name: $t('personnel.form.addressInformation'),
                    anchor: 'dialog-form-address',
                  },
                ].concat(
                  !!formData.userType
                    ? [
                        {
                          name: $t('personnel.form.workInformation'),
                          anchor: 'dialog-info-work',
                        },
                      ]
                    : [],
                )
              "
              background="transparent"
              :active="{
                background: 'hsla(var(--blue-6-hsl) / .2)',
                foreground: 'var(--blue-6)',
              }"
              scroll-element="#personnel-form"
            />
          </div>
        </div>
        <div
          class="col-md-10 col-12 full-height scroll"
          :class="{
            'q-py-md q-pr-md ': $q.screen.gt.sm,
            'q-py-md q-px-lg': !$q.screen.gt.sm,
          }"
        >
          <FormInformation
            id="dialog-form-information"
            dense
            outlined
            separator
            :title="'form.field.basicInformation'"
            :usernameReadonly="isEdit"
            v-model:hq-id="hqId"
            v-model:br-id="brId"
            v-model:user-type="formData.userType"
            v-model:user-role="formData.userRole"
            v-model:username="formData.username"
            v-model:user-code="userCode"
            class="q-mb-xl"
          />
          <FormPerson
            id="dialog-form-personal"
            prefix-id="form-dialog-personnel"
            dense
            outlined
            separator
            :title="'personnel.form.personalInformation'"
            v-model:first-name="formData.firstName"
            v-model:last-name="formData.lastName"
            v-model:mid-name="formData.middleName"
            v-model:mid-name-en="formData.middleNameEN"
            v-model:prefix-name="formData.namePrefix"
            v-model:prefix-name-en="formData.namePrefix"
            v-model:first-name-en="formData.firstNameEN"
            v-model:last-name-en="formData.lastNameEN"
            v-model:telephone-no="formData.telephoneNo"
            v-model:email="formData.email"
            v-model:gender="formData.gender"
            v-model:birth-date="formData.birthDate"
            v-model:citizen-id="formData.citizenId"
            v-model:citizen-issue="formData.citizenIssue"
            v-model:citizen-expire="formData.citizenExpire"
            class="q-mb-xl"
          />
          <AddressForm
            id="dialog-form-address"
            v-model:address="formData.address"
            v-model:address-en="formData.addressEN"
            v-model:moo="formData.moo"
            v-model:moo-en="formData.mooEN"
            v-model:soi="formData.soi"
            v-model:soi-en="formData.soiEN"
            v-model:street="formData.street"
            v-model:street-en="formData.streetEN"
            v-model:province-id="formData.provinceId"
            v-model:district-id="formData.districtId"
            v-model:sub-district-id="formData.subDistrictId"
            v-model:zip-code="formData.zipCode"
            prefix-id="drawer-info-personnel"
            dense
            class="q-mb-xl"
          />
          <FormByType
            id="dialog-form-work"
            dense
            outlined
            separator
            v-model:user-type="formData.userType"
            v-model:registration-no="formData.registrationNo"
            v-model:start-date="formData.startDate"
            v-model:retire-date="formData.retireDate"
            v-model:responsible-area="formData.responsibleArea"
            v-model:discount-condition="formData.discountCondition"
            v-model:source-nationality="formData.sourceNationality"
            v-model:import-nationality="formData.importNationality"
            v-model:training-place="formData.trainingPlace"
            v-model:checkpoint="formData.checkpoint"
            v-model:checkpoint-en="formData.checkpointEN"
            v-model:agency-file="agencyFile"
          />
        </div>
      </div>
    </div>
  </DialogForm>

  <ImageUploadDialog
    v-model:dialog-state="imageDialog"
    v-model:file="profileFileImg"
    v-model:image-url="urlProfile"
    v-model:data-list="imageList"
    v-model:on-create-data-list="onCreateImageList"
    :on-create="modal"
    :hiddenFooter="!isImageEdit"
    @add-image="
      async (v) => {
        if (!v) return;
        if (!currentUser) return;
        const res = await userStore.addImageList(
          v,
          currentUser?.id,
          Date.now(),
        );
        await fetchImageList(currentUser?.id, res);
      }
    "
    @remove-image="
      async (v) => {
        if (!v) return;
        if (!currentUser) return;
        const name = v.split('/').pop() || '';
        await userStore.deleteImageByName(currentUser?.id, name);
        await fetchImageList(currentUser?.id, currentUser.selectedImage || '');
      }
    "
    @submit="
      async (v) => {
        if (modal) {
          urlProfile = v;
          imageDialog = false;
        } else {
          refreshImageState = true;
          formData.selectedImage = v;
          imageList ? (imageList.selectedImage = v) : '';
          urlProfile = `${baseUrl}/user/${currentUser && currentUser.id}/profile-image/${v}`;
          await onSubmit(true);
          imageDialog = false;
          refreshImageState = false;
        }
      }
    "
  >
    <template #title>
      <span v-if="!modal" class="justify-center flex text-bold">
        {{ $t('general.image') }}
        {{
          locale === 'eng'
            ? `${formData.firstNameEN} ${formData.lastNameEN}`
            : `${formData.firstName} ${formData.lastName}`
        }}
      </span>
    </template>
    <template #error>
      <div class="full-height full-width" style="background: white">
        <div
          class="full-height full-width flex justify-center items-center"
          :style="`background: ${
            formData.gender
              ? formData.gender === 'male'
                ? '#78afb0'
                : '#c0bfe2'
              : 'linear-gradient(135deg,rgba(43, 137, 223, 1) 0%,rgba(230, 51, 81, 1) 100%)'
          }`"
        >
          <q-img
            v-if="formData.gender"
            fit="contain"
            :src="`/no-img-${formData.gender === 'male' ? 'man' : 'female'}.png`"
            style="height: 100%"
          />
          <q-icon
            v-else
            size="3rem"
            :name="
              infoDrawer ? 'mdi-account-outline' : 'mdi-account-plus-outline'
            "
            style="color: white"
          />
        </div>
      </div>
    </template>
  </ImageUploadDialog>
</template>
<style scoped>
.upload-img-preview {
  border: 1px solid var(--border-color);
  border-radius: var(--radius-2);
  height: 12vw;
  background-color: var(--surface-1);
}

.upload-img-btn {
  color: hsl(var(--info-bg));
  border: 1px solid hsl(var(--info-bg));
  background-color: hsla(var(--info-bg) / 0.1);
  border-radius: var(--radius-2);

  &.dark {
    background-color: transparent;
  }
}

.edit-img-btn {
  color: hsl(var(--info-bg));
  border: 1px solid hsl(var(--info-bg));
  background-color: transparent;
  border-radius: var(--radius-2);
}

.cancel-img-btn {
  color: hsl(var(--negative-bg));
  border: 1px solid hsl(var(--negative-bg));
  background-color: transparent;
  border-radius: var(--radius-2);
}

.submit-img-btn {
  color: var(--surface-1);
  border: 1px solid hsl(var(--positive-bg));
  background-color: hsl(var(--positive-bg));
  border-radius: var(--radius-2);
}

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

.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%;

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

.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__cyan {
  --_color: var(--cyan-7-hsl);
}

.dark .tags__cyan {
  --_color: var(--cyan-4-hsl);
}

.tags__yellow {
  --_color: var(--orange-4-hsl);
}

.tags__red {
  --_color: var(--red-6-hsl);
}

.tags__magenta {
  --_color: var(--pink-8-hsl);
}

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

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

.tags__purple {
  --_color: var(--indigo-8-hsl);
}

.dark .tags__purple {
  --_color: var(--indigo-3-hsl);
}

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

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

  &.symbol-gender__female {
    --_fg: var(--gender-female);
  }
}
</style>
