<script setup lang="ts">
import { ref, onMounted, watch, computed } from 'vue';
import useUtilsStore, { baseUrl, dialog } from 'stores/utils';
import { calculateAge } from 'src/utils/datetime';
import { useQuasar, type QTableProps } from 'quasar';
import { storeToRefs } from 'pinia';
import { useI18n } from 'vue-i18n';
import useFlowStore from 'stores/flow';
import useUserStore from 'stores/user';
import useBranchStore from 'stores/branch';

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

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

import { BranchUserStats } from 'stores/branch/types';
import useAddressStore from 'stores/address';
import ButtonAddComponent from 'components/ButtonAddCompoent.vue';
import PersonCard from 'components/shared/PersonCard.vue';
import StatCardComponent from 'components/StatCardComponent.vue';
import AddButton from 'components/AddButton.vue';
import TooltipComponent from 'components/TooltipComponent.vue';
import FormInformation from 'components/02_personnel-management/FormInformation.vue';
import FormPerson from 'components/02_personnel-management/FormPerson.vue';
import FormByType from 'components/02_personnel-management/FormByType.vue';
import DrawerInfo from 'components/DrawerInfo.vue';
import InfoForm from 'components/02_personnel-management/InfoForm.vue';
import NoData from 'components/NoData.vue';
import PaginationComponent from 'components/PaginationComponent.vue';
import useOptionStore from 'stores/options';
import ProfileBanner from 'components/ProfileBanner.vue';
import SideMenu from 'components/SideMenu.vue';
import ImageUploadDialog from 'components/ImageUploadDialog.vue';
import { AddressForm } from 'components/form';
import DialogForm from 'components/DialogForm.vue';
import KebabAction from 'src/components/shared/KebabAction.vue';

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

const optionStore = useOptionStore();
const utilsStore = useUtilsStore();
const flowStore = useFlowStore();
const userStore = useUserStore();
const branchStore = useBranchStore();
const adrressStore = useAddressStore();
const { data: userData } = storeToRefs(userStore);
const apiBaseUrl = import.meta.env.VITE_API_BASE_URL;

const defaultFormData = {
  provinceId: null,
  districtId: null,
  subDistrictId: null,
  telephoneNo: '',
  email: '',
  zipCode: '',
  gender: '',
  addressEN: '',
  address: '',
  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: '',
  profileImage: null,
  birthDate: null,
  responsibleArea: null,
  username: '',
  status: 'CREATED',
  checkpoint: null,
  checkpointEN: null,
};

const modeView = ref(false);

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 formMenuIcon = ref<{ icon: string; color: string; bgColor: string }[]>([
  {
    icon: 'mdi-account-outline',
    color: 'hsl(var(--info-bg))',
    bgColor: 'var(--surface-1)',
  },

  {
    icon: 'mdi-map-marker-radius-outline',
    color: 'hsl(var(--info-bg))',
    bgColor: 'var(--surface-1)',
  },
  {
    icon: 'mdi-briefcase-outline',
    color: 'hsl(var(--info-bg))',
    bgColor: 'var(--surface-1)',
  },
]);

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

const refImageUpload = ref<InstanceType<typeof ImageUploadDialog>>();
const fieldDisplay = ref();
const hideStat = ref(false);
const userCode = ref<string>();
const currentUser = ref<User>();
const infoDrawerEdit = ref(false);
const infoPersonId = ref<string>('');
const infoPersonCard = ref();
const infoDrawer = ref(false);
const profileSubmit = ref(false);
const urlProfile = ref<string>();
const isEdit = ref(false);
const modal = ref(false);
const statusToggle = ref(true);
const statusFilter = ref<'all' | 'statusACTIVE' | 'statusINACTIVE'>('all');
const inputSearch = ref('');
const userId = ref<string>();
const selectorLabel = ref<string>('ALL');
const hqId = ref<string>();
const brId = ref<string>();
const formDialogRef = ref();
const userStats = ref<BranchUserStats[]>();
const sortedUserStats = computed(() => {
  return userStats.value?.slice().sort((a, b) => b.count - a.count);
});
const typeStats = ref<UserTypeStats>();
const agencyFile = ref<File[]>([]);
const agencyFileList = ref<{ name: string; url: string }[]>([]);
const formData = ref<UserCreate>({
  branchId: '',
  provinceId: null,
  districtId: null,
  subDistrictId: null,
  telephoneNo: '',
  email: '',
  zipCode: '',
  gender: '',
  addressEN: '',
  address: '',
  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: '',
  profileImage: null,
  birthDate: null,
  responsibleArea: null,
  checkpoint: null,
  checkpointEN: null,
  username: '',
  status: 'CREATED',
});

const isImageEdit = ref<boolean>(false);
const imageUrl = ref<string>('');
const profileFileImg = ref<File | null>(null);
const imageDialog = ref(false);

// const inputFile = document.createElement('input');
// inputFile.type = 'file';
// inputFile.accept = 'image/*';

const reader = new FileReader();

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'];

// reader.addEventListener('load', () => {
//   if (typeof reader.result === 'string') {
//     urlProfile.value = reader.result;
//   }

//   if (infoDrawerEdit.value) infoPersonCard.value[0].img = urlProfile.value;
// });

watch(profileFileImg, () => {
  if (profileFileImg.value) reader.readAsDataURL(profileFileImg.value);
});

const selectorList = computed(() => [
  { label: 'USER', count: typeStats.value?.USER || 0 },
  { label: 'MESSENGER', count: typeStats.value?.MESSENGER || 0 },
  { label: 'DELEGATE', count: typeStats.value?.DELEGATE || 0 },
  { label: 'AGENCY', count: typeStats.value?.AGENCY || 0 },
]);

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) {
    console.log('no hq');

    dialog({
      color: 'warning',
      icon: 'mdi-alert',
      title: t('warning'),
      actionText: t('agree'),
      persistent: true,
      message: t('headquartersNotEstablished'),
      action: async () => {},
    });

    return;
  }

  if (action === 'FORM') {
    modal.value = true;
  } else if (action === 'INFO') {
    if (!userData.value) return;

    infoDrawerEdit.value = isPersonEdit ? true : false;
    infoDrawer.value = true;
    const user = userData.value.result.find((x) => x.id === id);
    infoPersonCard.value = user
      ? [
          {
            id: user.id,
            img: `${user.profileImageUrl}`,
            name:
              locale.value === 'eng'
                ? `${user.firstNameEN} ${user.lastNameEN}`
                : `${user.firstName} ${user.lastName}`,
            male: user.gender === 'male',
            female: user.gender === 'female',
            badge: user.code,
            disabled: user.status === 'INACTIVE',
          },
        ]
      : [];
  }

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

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

function onClose() {
  hqId.value = '';
  brId.value = '';
  userId.value = '';
  userCode.value = '';
  urlProfile.value = '';
  profileFileImg.value = null;
  infoDrawerEdit.value = false;
  agencyFile.value = [];
  modal.value = false;
  isEdit.value = false;
  infoDrawer.value = false;
  profileSubmit.value = false;
  statusToggle.value = true;
  isImageEdit.value = false;
  Object.assign(formData.value, defaultFormData);
  mapUserType(selectorLabel.value);
  flowStore.rotate();
}
async function onSubmit() {
  if (profileSubmit.value) {
    formData.value.profileImage = profileFileImg.value as File;
  } else {
    formData.value.profileImage = null;
  }

  if (isEdit.value && userId.value) {
    if (!userId.value) 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(userId.value, formDataEdit);

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

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

    await fetchUserList();
    typeStats.value = await userStore.typeStats();
    const res = await branchStore.userStats(formData.value.userType);
    if (res) {
      userStats.value = res;
    }
    onClose();
  } 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);

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

    selectorLabel.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();
      flowStore.rotate();
    },
  });
}

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

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;
    if (currentUser.value) {
      infoPersonId.value = currentUser.value.id;
      imageUrl.value = currentUser.value.profileImageUrl;
    }
    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,
      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,
      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,
    };

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

    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 = `${apiBaseUrl}/user/${foundUser.id}/image`;

    isEdit.value = true;
    profileSubmit.value = true;
    hqId.value && (await userStore.fetchBrOption(hqId.value));
    if (infoPersonCard.value) {
      infoPersonCard.value[0].img = foundUser.profileImageUrl;
    }
    if (formData.value.districtId) {
      await adrressStore.fetchSubDistrictByProvinceId(
        formData.value.districtId,
      );
    }
  }
}

function openImageDialog() {
  imageDialog.value = true;
}

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

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

watch(
  () => selectorLabel.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 = [];
  },
);

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

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

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">
    <q-fab-action
      id="btn-add-personne"
      :label="$t('personnel.addTitle')"
      external-label
      label-position="left"
      @click="openDialog('FORM')"
      color="primary"
      padding="xs"
      icon="mdi-account-plus-outline"
    ></q-fab-action>
  </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));
        "
      >
        {{
          selectorLabel === 'ALL'
            ? Object.values(typeStats).reduce((acc, val) => acc + val, 0)
            : typeStats[selectorLabel]
        }}
      </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"
            labelI18n
            :branch="
              selectorLabel === '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.${selectorLabel}`,
                      count: typeStats[selectorLabel],
                      icon: 'mdi-account-outline',
                      color:
                        selectorLabel === 'USER'
                          ? 'cyan'
                          : selectorLabel === 'MESSENGER'
                            ? 'yellow'
                            : selectorLabel === '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
              lazy-rules="ondemand"
              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
                lazy-rules="ondemand"
                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
                lazy-rules="ondemand"
                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="selectorLabel"
            align="left"
            class="full-width"
            active-color="info"
          >
            <q-tab
              name="ALL"
              @click="
                async () => {
                  currentPage = 1;
                  inputSearch = '';
                  selectorLabel = 'ALL';
                  statusFilter = 'all';
                  flowStore.rotate();
                }
              "
            >
              <div
                class="row text-capitalize"
                :class="
                  selectorLabel === 'ALL' ? 'text-bold' : 'app-text-muted'
                "
              >
                {{ $t('general.all') }}
              </div>
            </q-tab>
            <q-tab
              name="USER"
              @click="
                async () => {
                  selectorLabel = 'USER';
                  statusFilter = 'all';
                  currentPage = 1;
                  inputSearch = '';
                  flowStore.rotate();
                }
              "
            >
              <div
                class="row text-capitalize"
                :class="
                  selectorLabel === 'USER' ? 'text-bold' : 'app-text-muted'
                "
              >
                {{ $t('personnel.USER') }}
              </div>
            </q-tab>
            <q-tab
              name="MESSENGER"
              @click="
                async () => {
                  selectorLabel = 'MESSENGER';
                  statusFilter = 'all';
                  currentPage = 1;
                  inputSearch = '';
                  flowStore.rotate();
                }
              "
            >
              <div
                class="row text-capitalize"
                :class="
                  selectorLabel === 'MESSENGER' ? 'text-bold' : 'app-text-muted'
                "
              >
                {{ $t('personnel.MESSENGER') }}
              </div>
            </q-tab>
            <q-tab
              name="DELEGATE"
              @click="
                async () => {
                  selectorLabel = 'DELEGATE';
                  statusFilter = 'all';
                  currentPage = 1;
                  inputSearch = '';
                  flowStore.rotate();
                }
              "
            >
              <div
                class="row text-capitalize"
                :class="
                  selectorLabel === 'DELEGATE' ? 'text-bold' : 'app-text-muted'
                "
              >
                {{ $t('personnel.DELEGATE') }}
              </div>
            </q-tab>
            <q-tab
              name="AGENCY"
              @click="
                async () => {
                  selectorLabel = 'AGENCY';
                  statusFilter = 'all';
                  currentPage = 1;
                  inputSearch = '';
                  flowStore.rotate();
                }
              "
            >
              <div
                class="row text-capitalize"
                :class="
                  selectorLabel === '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 && !inputSearch">
          <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">
                        <q-avatar size="md">
                          <q-img
                            class="text-center"
                            :ratio="1"
                            :src="`${apiBaseUrl}/user/${props.row.id}/image?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 class="column">
                      <div class="col ellipsis" style="max-width: 20vw">
                        {{
                          $i18n.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"
                        >
                          {{
                            $i18n.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:
                      $i18n.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="`${apiBaseUrl}/user/${props.row.id}/image?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
    :isEdit="infoDrawerEdit"
    :title="
      $i18n.locale === 'eng'
        ? `${currentUser.firstNameEN} ${currentUser.lastNameEN}`
        : `${currentUser.firstName} ${currentUser.lastName}`
    "
    v-model:drawerOpen="infoDrawer"
    :submit="() => onSubmit()"
    :close="() => onClose()"
  >
    <InfoForm>
      <div class="q-px-lg q-pt-lg surface-2">
        <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
          :menu="formMenuIcon"
          :readonly="!infoDrawerEdit"
          :toggleTitle="$t('status.title')"
          :title="`${$i18n.locale === 'eng' ? `${formData.firstNameEN} ${formData.lastNameEN}` : `${formData.firstName} ${formData.lastName}`}`"
          :caption="userCode"
          :img="
            urlProfile ||
            {
              male: '/no-img-man.png',
              female: '/no-img-female.png',
            }[formData.gender]
          "
          :fallbackImg="
            {
              male: '/no-img-man.png',
              female: '/no-img-female.png',
            }[formData.gender]
          "
          @view="openImageDialog"
          @edit="refImageUpload && refImageUpload.browse()"
          @update:toggle-status="
            async (v) => {
              await triggerChangeStatus(infoPersonId, v);
            }
          "
        />
      </div>
      <!-- ย้อนกลับ -->

      <div
        style="flex: 1; width: 100%; overflow-y: auto"
        class="surface-2 q-pa-lg"
        id="drawer-user-form"
      >
        <div
          class="col surface-1 full-height rounded bordered scroll row relative-position"
        >
          <div
            class="surface-1 rounded q-my-md q-mx-lg row"
            style="position: absolute; z-index: 999; top: 0; right: 0"
          >
            <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="() => onDelete(infoPersonId)"
              type="button"
            />
          </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 q-py-md q-pr-md relative-position"
            id="user-form-content"
            :class="$q.screen.xs ? 'q-pl-md' : 'q-pl-sm'"
            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"
              :usernameReadonly="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"
              :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:addressEN="formData.addressEN"
              v-model:provinceId="formData.provinceId"
              v-model:districtId="formData.districtId"
              v-model:subDistrictId="formData.subDistrictId"
              v-model:zipCode="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:userType="formData.userType"
              v-model:registrationNo="formData.registrationNo"
              v-model:startDate="formData.startDate"
              v-model:retireDate="formData.retireDate"
              v-model:responsibleArea="formData.responsibleArea"
              v-model:discountCondition="formData.discountCondition"
              v-model:sourceNationality="formData.sourceNationality"
              v-model:importNationality="formData.importNationality"
              v-model:trainingPlace="formData.trainingPlace"
              v-model:checkpoint="formData.checkpoint"
              v-model:checkpointEN="formData.checkpointEN"
              v-model:agencyFile="agencyFile"
              v-model:agencyFileList="agencyFileList"
              v-model:userId="userId"
            />
          </div>
        </div>
      </div>
    </InfoForm>
  </DrawerInfo>

  <!-- form -->
  <DialogForm
    hideFooter
    removeDialog
    ref="formDialogRef"
    :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-mt-lg">
      <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"
        :menu="formMenuIcon"
        :img="
          urlProfile ||
          {
            male: '/no-img-man.png',
            female: '/no-img-female.png',
          }[formData.gender]
        "
        :toggleTitle="$t('status.title')"
        :title="`${$i18n.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"
        @edit="refImageUpload && refImageUpload.browse()"
        @update:toggle-status="
          () => {
            formData.status =
              formData.status === 'CREATED' ? 'INACTIVE' : 'CREATED';
          }
        "
      />
    </div>

    <div
      class="col surface-1 q-ma-lg rounded bordered row relative-position"
      id="personnel-form"
    >
      <div
        class="surface-1 rounded q-my-md q-mx-lg row"
        style="position: absolute; z-index: 999; right: 0; top: 0"
      >
        <SaveButton id="btn-info-basic-save" icon-only type="submit" />
      </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 q-pa-md full-height scroll">
        <FormInformation
          id="dialog-form-information"
          dense
          outlined
          separator
          :title="'form.field.basicInformation'"
          :usernameReadonly="isEdit"
          v-model:hqId="hqId"
          v-model:brId="brId"
          v-model:userType="formData.userType"
          v-model:userRole="formData.userRole"
          v-model:username="formData.username"
          v-model:userCode="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"
          class="q-mb-xl"
        />
        <AddressForm
          id="dialog-form-address"
          v-model:address="formData.address"
          v-model:addressEN="formData.addressEN"
          v-model:provinceId="formData.provinceId"
          v-model:districtId="formData.districtId"
          v-model:subDistrictId="formData.subDistrictId"
          v-model:zipCode="formData.zipCode"
          prefix-id="drawer-info-personnel"
          dense
          class="q-mb-xl"
        />
        <FormByType
          id="dialog-form-work"
          dense
          outlined
          separator
          v-model:userType="formData.userType"
          v-model:registrationNo="formData.registrationNo"
          v-model:startDate="formData.startDate"
          v-model:retireDate="formData.retireDate"
          v-model:responsibleArea="formData.responsibleArea"
          v-model:discountCondition="formData.discountCondition"
          v-model:sourceNationality="formData.sourceNationality"
          v-model:importNationality="formData.importNationality"
          v-model:trainingPlace="formData.trainingPlace"
          v-model:checkpoint="formData.checkpoint"
          v-model:checkpointEN="formData.checkpointEN"
          v-model:agencyFile="agencyFile"
        />
      </div>
    </div>
  </DialogForm>

  <!-- :default-url="`${baseUrl}/user/${currentUser?.id}/image`" -->
  <ImageUploadDialog
    ref="refImageUpload"
    v-model:dialogState="imageDialog"
    v-model:file="profileFileImg"
    v-model:image-url="urlProfile"
    :hiddenFooter="!isImageEdit"
    :changeDisabled="!isImageEdit"
    @save="imageDialog = false"
    clearButton
  >
    <template #error>
      <div class="full-height full-width" style="background: white">
        <div
          class="full-height full-width flex justify-center items-center"
          :style="`background: ${
            modal || !formData.gender
              ? 'linear-gradient(135deg,rgba(43, 137, 223, 1) 0%,rgba(230, 51, 81, 1) 100%)'
              : formData.gender === 'male'
                ? '#78afb0'
                : '#c0bfe2'
          }`"
        >
          <q-img
            v-if="infoDrawer && formData.gender"
            fit="contain"
            :src="`/no-img-${formData.gender === 'male' ? 'man' : 'female'}.png`"
            style="height: 100%"
          />
          <q-icon
            v-else
            size="15rem"
            :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>
