<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import useBranchStore from 'src/stores/branch';
import useCustomerStore from 'src/stores/customer';
import SelectInput from '../shared/SelectInput.vue';
import { QSelect } from 'quasar';

const { locale } = useI18n({ useScope: 'global' });
const branchStore = useBranchStore();
const customerStore = useCustomerStore();

const branch = defineModel<string>('branch');
const customer = defineModel<string>('customer');
const agentPrice = defineModel<boolean>('agentPrice');

const branchOption = ref();
const customerOption = ref();

defineProps<{
  outlined?: boolean;
  readonly?: boolean;
  separator?: boolean;
  employee?: boolean;
  title?: string;
  prefixId: string;
}>();

async function filter(
  val: string,
  update: (...args: unknown[]) => void,
  type: 'branch' | 'customer',
) {
  update(
    async () => {
      const res =
        type === 'branch'
          ? await branchStore.fetchList({
              query: val,
              pageSize: 30,
            })
          : await customerStore.fetchList({
              query: val,
              pageSize: 30,
            });
      if (res) {
        if (type === 'branch') {
          branchOption.value = res.result.map((v) => ({
            value: v.id,
            label: v.name,
            labelEN: v.nameEN,
          }));
        } else if (type === 'customer') {
          customerOption.value = res.result.map((v) => ({
            value: v.id,
            label:
              v.customerType === 'CORP'
                ? v.branch[0].registerName
                : `${v.branch[0].firstName} ${v.branch[0].lastName}`,
            labelEN:
              v.customerType === 'CORP'
                ? v.branch[0].registerNameEN
                : `${v.branch[0].firstNameEN} ${v.branch[0].lastNameEN}`,
          }));
        }
      }
    },

    (ref: QSelect) => {
      if (val !== '' && ref.options && ref.options?.length > 0) {
        ref.setOptionIndex(-1);
        ref.moveOptionSelection(1, true);
      }
    },
  );
}
</script>
<template>
  <div class="row col-12">
    <div class="col-12 row items-center q-pb-sm text-weight-bold text-body1">
      <q-icon
        flat
        size="xs"
        class="q-pa-sm rounded q-mr-sm"
        color="info"
        name="mdi-file-outline"
        style="background-color: var(--surface-3)"
      />
      {{ $t(`general.about`) }}
      <div class="q-ml-md text-weight-regular">
        <q-checkbox
          :label="$t('productService.product.agentPrice')"
          size="xs"
          v-model="agentPrice"
          style="font-size: 14px"
        />
      </div>
    </div>
    <div class="col-12 row q-col-gutter-sm">
      <SelectInput
        :readonly
        incremental
        v-model="branch"
        id="quotation-branch"
        class="col-md col-12"
        :option="branchOption"
        :label="$t('quotation.branch')"
        :option-label="locale === 'eng' ? 'labelEN' : 'label'"
        :rules="[(val: string) => !!val || $t('form.error.required')]"
        @filter="(val, update) => filter(val, update, 'branch')"
      />

      <SelectInput
        :readonly
        incremental
        v-model="customer"
        class="col-md col-12"
        id="quotation-customer"
        :option="customerOption"
        :label="$t('quotation.customer')"
        :option-label="locale === 'eng' ? 'labelEN' : 'label'"
        :rules="[(val: string) => !!val || $t('form.error.required')]"
        @filter="(val, update) => filter(val, update, 'customer')"
      >
        <template #option="{ scope }">
          <q-item clickable v-if="scope.index === 0">
            <q-item-section>
              {{ $t('general.add', { text: $t('quotation.newCustomer') }) }}
            </q-item-section>
          </q-item>
          <q-separator v-if="scope.index === 0" />

          <q-item clickable v-bind="scope.itemProps">
            <q-item-section>
              {{ locale === 'eng' ? scope.opt.labelEN : scope.opt.label }}
            </q-item-section>
          </q-item>
        </template>
      </SelectInput>
    </div>
  </div>
</template>
