<script setup lang="ts">
import { storeToRefs } from 'pinia';
import { ref, onMounted, computed } from 'vue';
import { Icon } from '@iconify/vue';

import useBranchStore from 'stores/branch';

import { dialog } from 'src/stores/utils';
import AppBox from 'components/app/AppBox.vue';
import AddButton from 'components/AddButton.vue';
import TooltipComponent from 'components/TooltipComponent.vue';
import StatCard from 'components/StatCardComponent.vue';
import BranchCard from 'src/components/01_branch-management/BranchCard.vue';
import FormDialog from 'src/components/FormDialog.vue';
import FormBranchInformation from 'src/components/01_branch-management/FormBranchInformation.vue';
import FormLocation from 'src/components/01_branch-management/FormLocation.vue';
import FormQr from 'src/components/01_branch-management/FormQr.vue';
import FormBranchContact from 'src/components/01_branch-management/FormBranchContact.vue';
import FormImage from 'src/components/01_branch-management/FormImage.vue';
import DrawerInfo from 'src/components/DrawerInfo.vue';
import InfoForm from 'src/components/02_personnel-management/InfoForm.vue';

import { BranchWithChildren, BranchCreate } from 'stores/branch/types';
import { watch } from 'vue';
import { useI18n } from 'vue-i18n';
import useFlowStore from 'src/stores/flow';

const { t } = useI18n();

const modal = ref<boolean>(false);

const profileFileImg = ref<File | undefined>(undefined);
const imageUrl = ref<string | null>('');

const inputFileImg = (() => {
  const element = document.createElement('input');
  element.type = 'file';
  element.accept = 'image/*';

  const reader = new FileReader();
  reader.addEventListener('load', () => {
    if (typeof reader.result === 'string') imageUrl.value = reader.result;
  });

  element.addEventListener('change', () => {
    profileFileImg.value = element.files?.[0];
    if (profileFileImg.value) {
      reader.readAsDataURL(profileFileImg.value);
    }
  });

  return element;
})();

const profileFile = ref<File | undefined>(undefined);
const qrCodeimageUrl = ref<string | null>('');

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

  const reader = new FileReader();
  reader.addEventListener('load', () => {
    if (typeof reader.result === 'string') qrCodeimageUrl.value = reader.result;
  });

  element.addEventListener('change', () => {
    profileFile.value = element.files?.[0];
    if (profileFile.value) {
      reader.readAsDataURL(profileFile.value);
    }
  });

  return element;
})();

const branchStore = useBranchStore();
const flowStore = useFlowStore();
const { locale } = useI18n();

const { data: branchData } = storeToRefs(branchStore);

const treeData = computed(() => {
  const arr: BranchWithChildren[] = [];

  branchData.value?.result.forEach((a) => {
    if (a.isHeadOffice) arr.push(Object.assign(a, { branch: [] }));
    else arr.find((b) => b.id === a.headOfficeId)?.branch.push(a);
  });

  return arr;
});

onMounted(async () => {
  await branchStore.fetchList({ pageSize: 99999 });

  const _stats = await branchStore.stats();

  if (_stats) {
    stats.value.push(
      { count: _stats.hq, label: 'branchHQLabel', color: 'pink' },
      { count: _stats.br, label: 'branchLabel', color: 'purple' },
    );
  }

  flowStore.rotate();
});

const statusFilter = ref<'all' | 'statusACTIVE' | 'statusINACTIVE'>('all');

const beforeBranch = ref<{ id: string; code: string }>({
  id: '',
  code: '',
});

const inputSearch = ref<string>('');
const fieldBranch = ref(['all', 'branchHQLabel', 'branchLabel']);
const fieldDisplay = ref([
  'branchLabelName',
  'branchLabelTel',
  'branchLabelAddress',
  'branchLabelType',
  'branchLabelStatus',
]);
const fieldSelected = ref<string[]>(fieldDisplay.value);
const fieldSelectedBranch = ref<{
  label: string;
  value: string;
}>({
  label: t('branchHQLabel'),
  value: 'branchHQLabel',
});

const stats = ref<{ count: number; label: string; color: 'pink' | 'purple' }[]>(
  [],
);

const defaultFormData = {
  headOfficeId: null,
  taxNo: '',
  nameEN: '',
  name: '',
  addressEN: '',
  address: '',
  zipCode: '',
  email: '',
  contactName: '',
  contact: '',
  telephoneNo: '',
  longitude: '',
  latitude: '',
  subDistrictId: '',
  districtId: '',
  provinceId: '',
  lineId: '',
};

const formDialogRef = ref();

const formType = ref<'create' | 'edit' | 'delete' | 'view'>('create');
const formTypeBranch = ref<'headOffice' | 'subBranch'>('headOffice');
const currentHq = ref<{ id: string; code: string }>({ id: '', code: '' });
const currentEdit = ref<{ id: string; code: string }>({ id: '', code: '' });
const formData = ref<Omit<BranchCreate, 'qrCodeImage' | 'imageUrl'>>(
  structuredClone(defaultFormData),
);

const prevFormData = ref<Omit<BranchCreate, 'qrCodeImage' | 'imageUrl'>>(
  structuredClone(defaultFormData),
);

const modalDrawer = ref<boolean>(false);

function openDrawer() {
  modalDrawer.value = true;
}

function openDialog() {
  modal.value = true;
}

async function fetchBranchById(id: string) {
  const res = await branchStore.fetchById(id, { includeContact: true });

  if (res) {
    qrCodeimageUrl.value = res.qrCodeImageUrl;
    imageUrl.value = res.imageUrl;

    formData.value = {
      headOfficeId: res.headOfficeId,
      taxNo: res.taxNo,
      nameEN: res.nameEN,
      name: res.name,
      addressEN: res.addressEN,
      address: res.address,
      zipCode: res.zipCode,
      email: res.email,
      contactName: res.contactName,
      contact: res.contact.length > 0 ? res.contact[0].telephoneNo : ' ',
      telephoneNo: res.telephoneNo,
      longitude: res.longitude,
      latitude: res.latitude,
      subDistrictId: res.subDistrictId,
      districtId: res.districtId,
      provinceId: res.provinceId,
      lineId: res.lineId,
      status: res.status,
    };
  }
}

function clearData() {
  formData.value = structuredClone(defaultFormData);
  imageUrl.value = null;
  qrCodeimageUrl.value = null;
  currentEdit.value = {
    id: '',
    code: '',
  };
  profileFile.value = undefined;
}

async function undo() {
  formType.value = 'view';
  formData.value = prevFormData.value;
}

function triggerCreate(
  type: 'headOffice' | 'subBranch',
  id?: string,
  code?: string,
) {
  clearData();

  formTypeBranch.value = type;

  if (type === 'headOffice') {
    currentHq.value = {
      id: id ?? '',
      code: code ?? '',
    };
  }

  formType.value = 'create';
  openDialog();
}

function drawerEdit() {
  formType.value = 'edit';
  prevFormData.value = {
    ...formData.value,
  };
}

async function triggerEdit(
  openFormType: string,
  id: string,
  typeBranch: 'headOffice' | 'subBranch',
) {
  await fetchBranchById(id);
  if (openFormType === 'form') {
    formType.value = 'edit';
    openDialog();
  }
  if (openFormType === 'drawer') {
    formType.value = 'view';
    openDrawer();
  }

  const currentRecord = branchData.value.result.find((x) => x.id === id);

  if (!currentRecord) return;

  currentEdit.value = {
    id: currentRecord.id,
    code: currentRecord.code,
  };

  if (typeBranch === 'subBranch') {
    const currentRecordHead = branchData.value.result.find(
      (x) => x.id === currentRecord.headOfficeId,
    );

    if (currentRecordHead) {
      currentHq.value.id = currentRecordHead.id;
      currentHq.value.code = currentRecordHead.code;
    } else {
      currentHq.value = currentEdit.value;
    }
  }
  formTypeBranch.value = typeBranch;
}

function triggerDelete(id: string) {
  if (id) {
    dialog({
      color: 'negative',
      icon: 'mdi-alert',
      title: t('deleteConfirmTitle'),
      actionText: t('agree'),
      persistent: true,
      message: t('deleteConfirmMessage'),
      action: async () => {
        await branchStore.deleteById(id);
        await branchStore.fetchList({ pageSize: 99999 });
        modalDrawer.value = false;
        stats.value[0].count = stats.value[0].count - 1;
        flowStore.rotate();
      },
      cancel: () => {},
    });
  }
}

async function onSubmit() {
  if (formType.value === 'edit') {
    await branchStore.editById(
      currentEdit.value.id,
      {
        ...formData.value,
        status: undefined,
      },
      profileFile.value,
      profileFileImg.value,
    );

    await branchStore.fetchList({ pageSize: 99999 });
    modal.value = false;
    modalDrawer.value = false;
  }

  if (formType.value === 'create') {
    if (formTypeBranch.value === 'subBranch') {
      formData.value.headOfficeId = currentHq.value.id;
    }

    await branchStore.create({
      ...formData.value,
      qrCodeImage: profileFile.value,
      imageUrl: profileFileImg.value,
    });

    await branchStore.fetchList({ pageSize: 99999 });
    modal.value = false;
  }

  const _stats = await branchStore.stats();

  if (_stats) {
    stats.value = [
      {
        count: _stats.hq,
        label: 'branchHQLabel',
        color: 'pink',
      },
      {
        count: _stats.br,
        label: 'branchLabel',
        color: 'purple',
      },
    ];
  }
  flowStore.rotate();
}

function changeTitle(
  formType: 'edit' | 'create' | 'delete' | 'view',
  typeBranch: 'headOffice' | 'subBranch',
) {
  if (typeBranch === 'headOffice') {
    return formType === 'create'
      ? t('formDialogTitleCreateHeadOffice')
      : formType === 'view'
        ? t('formDialogTitleViewHeadOffice')
        : t('formDialogTitleEditHeadOffice');
  }
  if (typeBranch === 'subBranch') {
    return formType === 'create'
      ? t('formDialogTitleCreateSubBranch')
      : formType === 'view'
        ? t('formDialogTitleViewSubBranch')
        : t('formDialogTitleEditSubBranch');
  }
  return '';
}

watch(locale, () => {
  fieldSelectedBranch.value = {
    label: t(`${fieldSelectedBranch.value.label}`),
    value: fieldSelectedBranch.value.value,
  };
});
</script>

<template>
  <div class="column">
    <div class="row text-h6 text-weight-bold q-mb-md">
      {{ $t('branchManagement') }}
    </div>

    <AppBox bordered class="q-mb-md">
      <StatCard label-i18n :branch="stats" :dark="$q.dark.isActive" />
    </AppBox>

    <AppBox
      class="column"
      :no-padding="!!branchData.total"
      bordered
      style="min-height: 70vh"
    >
      <template v-if="!branchData.total">
        <TooltipComponent
          class="self-end"
          title="branchNoMainOfficeYet"
          caption="branchClickToCreateMainOffice"
          imgSrc="personnel-table-"
        />

        <div class="row items-center justify-center" style="flex-grow: 1">
          <AddButton
            label="branchAdd"
            @trigger="() => triggerCreate('headOffice')"
          />
        </div>
      </template>
      <template v-else>
        <div class="row" style="flex-grow: 1; flex-wrap: nowrap">
          <div class="tree-container q-pa-md bordered-r surface-2">
            <div class="row">
              <button
                style="border: none; background: transparent"
                :class="{ 'cursor-pointer': !!currentHq.id }"
                id="br-prev"
              >
                <Icon
                  icon="ep:arrow-left-bold"
                  width="21px"
                  :class="{ 'app-text-muted': !currentHq.id }"
                  @click="
                    () => {
                      if (currentHq.id) {
                        beforeBranch = currentHq;
                        currentHq = { id: '', code: '' };
                        fieldSelectedBranch = {
                          label: $t('branchHQLabel'),
                          value: 'branchHQLabel',
                        };
                      }
                    }
                  "
                />
              </button>

              <button
                style="border: none; background: transparent; padding: 0"
                :class="{ 'cursor-pointer': !!beforeBranch.id }"
                id="br-next"
              >
                <Icon
                  icon="ep:arrow-right-bold"
                  width="21px"
                  :class="{
                    'app-text-muted': !beforeBranch.id,
                  }"
                  @click="
                    () => {
                      if (beforeBranch.id) {
                        currentHq = beforeBranch;
                        beforeBranch = { id: '', code: '' };
                        fieldSelectedBranch = {
                          label: '',
                          value: '',
                        };
                      }
                    }
                  "
                />
              </button>

              <q-space />

              <button
                id="hq-add-btn"
                style="border: none; background: transparent"
              >
                <Icon
                  icon="pixelarticons:plus"
                  height="26"
                  class="color-icon-plus cursor-pointer"
                  @click="
                    () => {
                      if (!currentHq.id) {
                        triggerCreate('headOffice');
                      } else {
                        triggerCreate('subBranch');
                      }
                    }
                  "
                />
              </button>
            </div>

            <div class="bordered rounded q-mt-sm surface-1">
              <div
                class="bordered-b q-pl-sm text-weight-bold surface-3"
                style="height: 50px; display: flex; align-items: center"
              >
                <Icon icon="flowbite:home-solid" width="24px" class="q-mr-md" />
                {{ $t('all') }}
              </div>

              <q-tree
                :nodes="treeData"
                node-key="id"
                label-key="name"
                children-key="branch"
              >
                <template #default-header="{ node }">
                  <div
                    class="row items-center justify-between full-width no-wrap"
                  >
                    <span>{{ node.name }}</span>
                    <div class="q-gutter-xs flex no-wrap" @click.stop>
                      <q-btn
                        v-if="node.isHeadOffice"
                        :id="`create-sub-branch-btn-${node.name}`"
                        @click.stop="
                          triggerCreate('subBranch', node.id, node.code)
                        "
                        icon="mdi-file-plus-outline"
                        fab-mini
                        unelevated
                      />

                      <q-btn
                        :id="`view-detail-btn-${node.name}`"
                        icon="mdi-dots-vertical"
                        fab-mini
                        unelevated
                        flat
                      >
                        <q-menu class="bordered">
                          <q-list v-close-popup>
                            <q-item
                              :id="`view-detail-btn-${node.name}-view`"
                              @click.stop="
                                if (node.isHeadOffice) {
                                  triggerEdit('drawer', node.id, 'headOffice');
                                } else {
                                  triggerEdit('drawer', node.id, 'subBranch');
                                }
                              "
                              clickable
                              dense
                              class="row q-py-sm"
                              style="white-space: nowrap"
                            >
                              <q-icon
                                name="mdi-eye-outline"
                                class="col-3"
                                size="xs"
                                style="color: hsl(var(--green-6-hsl))"
                              />
                              <span class="col-9 q-px-md flex items-center">
                                {{ $t('viewDetail') }}
                              </span>
                            </q-item>
                            <q-item
                              :id="`view-detail-btn-${node.name}-edit`"
                              clickable
                              dense
                              class="row q-py-sm"
                              style="white-space: nowrap"
                              @click="
                                () => {
                                  if (node.isHeadOffice) {
                                    triggerEdit('form', node.id, 'headOffice');
                                  } else {
                                    triggerEdit('form', node.id, 'subBranch');
                                  }
                                }
                              "
                            >
                              <q-icon
                                name="mdi-pencil-outline"
                                class="col-3"
                                size="xs"
                                style="color: hsl(var(--cyan-6-hsl))"
                              />
                              <span class="col-9 q-px-md flex items-center">
                                {{ $t('edit') }}
                              </span>
                            </q-item>
                            <q-item
                              :id="`view-detail-btn-${node.name}-delete`"
                              dense
                              :clickable="node.status === 'CREATED'"
                              class="row"
                              :class="{
                                'surface-3': node.status !== 'CREATED',
                                'app-text-muted': node.status !== 'CREATED',
                              }"
                              style="white-space: nowrap"
                              @click="triggerDelete(node.id)"
                            >
                              <q-icon
                                name="mdi-trash-can-outline"
                                size="xs"
                                class="col-3"
                                :class="{
                                  'app-text-negative':
                                    node.status === 'CREATED',
                                }"
                              />
                              <span class="col-9 q-px-md flex items-center">
                                {{ $t('delete') }}
                              </span>
                            </q-item>

                            <q-item dense>
                              <q-item-section class="q-py-sm">
                                <div class="q-pa-sm surface-2 rounded">
                                  <q-toggle
                                    :id="`view-detail-btn-${node.name}-status`"
                                    dense
                                    size="sm"
                                    :label="
                                      node.status !== 'INACTIVE'
                                        ? $t('switchOnLabel')
                                        : $t('switchOffLabel')
                                    "
                                    @click="
                                      async () => {
                                        const res = await branchStore.editById(
                                          node.id,
                                          {
                                            status:
                                              node.status !== 'INACTIVE'
                                                ? 'INACTIVE'
                                                : 'ACTIVE',
                                          },
                                        );
                                        if (res) node.status = res.status;
                                      }
                                    "
                                    :model-value="
                                      node.status === 'CREATED' ||
                                      node.status === 'ACTIVE'
                                    "
                                  />
                                </div>
                              </q-item-section>
                            </q-item>
                          </q-list>
                        </q-menu>
                      </q-btn>
                    </div>
                  </div>
                </template>
              </q-tree>
            </div>
          </div>
          <div class="branch-wrapper q-pa-md">
            <div class="q-mb-md flex" style="gap: var(--size-4)">
              <div
                style="
                  flex-grow: 1;
                  display: flex;
                  align-items: stretch;
                  gap: var(--size-2);
                "
              >
                <template v-if="!currentHq.id">
                  <q-select
                    id="select-branch"
                    for="select-branch"
                    v-model="fieldSelectedBranch"
                    style="min-width: 120px"
                    outlined
                    :options="
                      fieldBranch.map((v) => ({ label: $t(v), value: v }))
                    "
                    :label="$t('select')"
                    dense
                  />
                  <q-btn
                    id="btn-filter"
                    icon="mdi-tune-vertical-variant"
                    size="sm"
                    class="bordered rounded"
                    :class="{ 'app-text-info': statusFilter !== 'all' }"
                    unelevated
                  >
                    <q-menu class="bordered">
                      <q-list v-close-popup dense>
                        <q-item
                          id="btn-filter-all"
                          clickable
                          class="flex items-center"
                          :class="{ 'app-text-info': statusFilter === 'all' }"
                          @click="statusFilter = 'all'"
                        >
                          {{ $t('all') }}
                        </q-item>
                        <q-item
                          id="btn-filter-active"
                          clickable
                          class="flex items-center"
                          :class="{
                            'app-text-info': statusFilter === 'statusACTIVE',
                          }"
                          @click="statusFilter = 'statusACTIVE'"
                        >
                          {{ $t('statusACTIVE') }}
                        </q-item>
                        <q-item
                          id="btn-filter-inactive"
                          clickable
                          class="flex items-center"
                          :class="{
                            'app-text-info': statusFilter === 'statusINACTIVE',
                          }"
                          @click="statusFilter = 'statusINACTIVE'"
                        >
                          {{ $t('statusINACTIVE') }}
                        </q-item>
                      </q-list>
                    </q-menu>
                  </q-btn>
                </template>
                <div v-else class="text-weight-bold text">
                  {{ $t('branchInHQ') }}
                  {{ currentHq.code }}
                </div>
              </div>

              <div
                style="flex-grow: 1; display: flex; justify-content: flex-end"
              >
                <q-input
                  for="input-Search"
                  style="width: 250px"
                  outlined
                  dense
                  label="ค้นหา"
                  v-model="inputSearch"
                  debounce="500"
                ></q-input>
              </div>

              <div style="flex-grow: 1">
                <q-select
                  id="select-field"
                  for="select-field"
                  :options="
                    fieldDisplay.map((v) => ({ label: $t(v), value: v }))
                  "
                  :display-value="$t('displayField')"
                  v-model="fieldSelected"
                  option-label="label"
                  option-value="value"
                  map-options
                  emit-value
                  outlined
                  multiple
                  dense
                />
              </div>
            </div>
            <div class="branch-container">
              <BranchCard
                :id="`branch-card-${item.name}`"
                v-for="item in treeData
                  .flatMap((v) => [v, ...v.branch])
                  .filter((v) => {
                    if (
                      statusFilter === 'statusACTIVE' &&
                      v.status === 'INACTIVE'
                    ) {
                      return false;
                    }
                    if (
                      statusFilter === 'statusINACTIVE' &&
                      v.status !== 'INACTIVE'
                    ) {
                      return false;
                    }

                    const terms = `${v.code} ${$i18n.locale === 'en-US' ? v.nameEN : v.name} ${v.telephoneNo}`;
                    if (inputSearch && !terms.includes(inputSearch)) {
                      return false;
                    }

                    if (!!currentHq.id && currentHq.id === v.headOfficeId) {
                      console.log('ทำงาน');

                      return true;
                    }
                    if (fieldSelectedBranch.value === 'all') return true;
                    if (fieldSelectedBranch.value === 'branchHQLabel')
                      return v.isHeadOffice;
                    if (fieldSelectedBranch.value === 'branchLabel')
                      return !v.isHeadOffice;

                    return false;
                  })"
                @click="
                  () => {
                    if (item.isHeadOffice) {
                      fieldSelectedBranch.value = '';
                      inputSearch = '';
                      currentHq = { id: item.id, code: item.code };
                      beforeBranch = {
                        id: '',
                        code: '',
                      };
                    }
                  }
                "
                :metadata="item"
                :color="item.isHeadOffice ? 'hq' : 'br'"
                :key="item.id"
                :data="{
                  branchLabelCode: item.code,
                  branchLabelName:
                    $i18n.locale === 'en-US' ? item.nameEN : item.name,
                  branchLabelTel: item.contact
                    .map((c) => c.telephoneNo)
                    .join(','),
                  branchLabelAddress:
                    $i18n.locale === 'en-US'
                      ? `${item.addressEN || ''} ${item.subDistrict?.nameEN || ''} ${item.district?.nameEN || ''} ${item.province?.nameEN || ''}`
                      : `${item.address || ''} ${item.subDistrict?.name || ''} ${item.district?.name || ''} ${item.province?.name || ''}`,
                  branchLabelType: $t(
                    item.isHeadOffice ? 'branchHQLabel' : 'branchLabel',
                  ),
                  branchLabelStatus: $t(`status${item.status}`),
                }"
                :field-selected="fieldSelected"
                :badge-field="['branchLabelStatus']"
                :inactive="item.status === 'INACTIVE'"
                @view-detail="
                  (v) =>
                    triggerEdit(
                      'drawer',
                      v.id,
                      v.isHeadOffice ? 'headOffice' : 'subBranch',
                    )
                "
              />
            </div>
          </div>
        </div>
      </template>
    </AppBox>
  </div>

  <FormDialog
    ref="formDialogRef"
    v-model:modal="modal"
    v-model:address="formData.address"
    v-model:addressEN="formData.addressEN"
    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"
    :title="changeTitle(formType, formTypeBranch) + ' ' + currentEdit.code"
    :titleFormAddress="$t('formDialogTitleAddress')"
    :address-title="$t('formDialogAddress')"
    :address-title-EN="$t('formDialogAddressEN')"
    :addressSeparator="true"
    :submit="
      () => {
        onSubmit();
      }
    "
    :close="() => (modal = false)"
  >
    <template #information>
      <FormBranchInformation
        v-model:code="currentHq.code"
        v-model:code-sub-branch="currentEdit.code"
        v-model:taxNo="formData.taxNo"
        v-model:name="formData.name"
        v-model:nameEN="formData.nameEN"
        v-model:type-branch="formTypeBranch"
        :separator="true"
        :dense="true"
        :outlined="true"
        :readonly="formType === 'view'"
        :view="formType === 'view'"
        title="formDialogTitleInformation"
      />
    </template>

    <template #person>
      <FormBranchContact
        v-model:type-branch="formTypeBranch"
        v-model:telephone-no="formData.telephoneNo"
        v-model:contact="formData.contact"
        v-model:email="formData.email"
        v-model:contact-name="formData.contactName"
        v-model:line-id="formData.lineId"
        :separator="true"
        title="formDialogTitleContact"
        :dense="true"
        :outlined="true"
      />
    </template>

    <template #qr-code>
      <FormQr
        title="QR Code"
        :separator="true"
        :qr="qrCodeimageUrl"
        :readonly="formType === 'view'"
        @upload="
          () => {
            inputFile.click();
          }
        "
      />
    </template>

    <template #location>
      <FormLocation
        :readonly="formType === 'view'"
        :separator="true"
        v-model:latitude="formData.latitude"
        v-model:longitude="formData.longitude"
        title="formDialogTitleLocation"
      />
    </template>

    <template #by-type>
      <FormImage
        :readonly="formType === 'view'"
        v-model:image="imageUrl"
        @upload="
          () => {
            inputFileImg.click();
          }
        "
        :title="$t('formDialogTitleImg')"
      />
    </template>
  </FormDialog>

  <DrawerInfo
    ref="formDialogRef"
    v-model:drawerOpen="modalDrawer"
    :title="changeTitle(formType, formTypeBranch) + ' ' + currentEdit.code"
    :titleFormAddress="$t('formDialogTitleAddress')"
    :addressSeparator="true"
    :undo="() => undo()"
    :isEdit="formType === 'edit'"
    :editData="() => drawerEdit()"
    :submit="() => onSubmit()"
    :delete-data="() => triggerDelete(currentEdit.id)"
    :close="() => ((modalDrawer = false), flowStore.rotate())"
    :statusBranch="formData.status"
  >
    <template #info>
      <InfoForm
        v-model:address="formData.address"
        v-model:addressEN="formData.addressEN"
        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"
        :title-form-address="$t('formDialogTitleAddress')"
        :address-title="$t('formDialogAddress')"
        :address-title-e-n="$t('formDialogAddressEN')"
        :readonly="formType === 'view'"
      >
        <template #information>
          <FormBranchInformation
            v-model:code="currentHq.code"
            v-model:code-sub-branch="currentEdit.code"
            v-model:taxNo="formData.taxNo"
            v-model:name="formData.name"
            v-model:nameEN="formData.nameEN"
            v-model:type-branch="formTypeBranch"
            :separator="true"
            :dense="true"
            :outlined="true"
            :readonly="formType === 'view'"
            :view="formType === 'view'"
            title="formDialogTitleInformation"
          />
        </template>

        <template #person>
          <FormBranchContact
            title="formDialogTitleContact"
            v-model:telephone-no="formData.telephoneNo"
            v-model:contact="formData.contact"
            v-model:email="formData.email"
            v-model:contact-name="formData.contactName"
            v-model:line-id="formData.lineId"
            :readonly="formType === 'view'"
            :view="formType === 'view'"
            :separator="true"
            :dense="true"
            :outlined="true"
          />
        </template>

        <template #qr-code>
          <FormQr
            :readonly="formType === 'view'"
            title="QR Code"
            :separator="true"
            :qr="qrCodeimageUrl"
            @upload="
              () => {
                inputFile.click();
              }
            "
          />
        </template>

        <template #location>
          <FormLocation
            title="formDialogTitleLocation"
            v-model:latitude="formData.latitude"
            v-model:longitude="formData.longitude"
            :readonly="formType === 'view'"
            :separator="true"
          />
        </template>

        <template #by-type>
          <FormImage
            @upload="
              () => {
                inputFileImg.click();
              }
            "
            v-model:image="imageUrl"
            :title="$t('formDialogTitleImg')"
            :readonly="formType === 'view'"
          />
        </template>
      </InfoForm>
    </template>
  </DrawerInfo>
</template>

<style scoped>
.color-icon-arrow {
  color: var(--gray-3);
}

.color-icon-plus {
  color: var(--cyan-6);
}

.tree-container {
  width: 100%;
  min-width: 300px;
  max-width: 25%;
  max-height: 100%;
}

.branch-wrapper {
  flex-grow: 1;

  & > .branch-container {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    grid-template-rows: unset;
    gap: var(--size-4);
  }
}
</style>
