<script setup lang="ts">
import { ref } from 'vue';
import { CustomerBranchCreate } from 'stores/customer/types';
import { onMounted } from 'vue';
import { checkTabBeforeAdd } from 'stores/utils';

const props = defineProps<{
  readonly?: boolean;
  edit?: boolean;
  prefixId: string;
}>();

const customerBranch = defineModel<CustomerBranchCreate[]>('customerBranch', {
  default: [],
});

const statBranchNo = defineModel<number>('statBranchNo', {
  default: 0,
});

const tab = defineModel<number>('tabIndex', { required: true });

function addData() {
  const canAdd = checkTabBeforeAdd(customerBranch.value || [], [
    'branchNo',
    'payDate',
    'registerDate',
    'status',
    'wageRate',
  ]);
  if (canAdd) {
    const currentNo = (customerBranch.value.at(-1)?.branchNo || 0) + 1;
    customerBranch.value.push({
      code: '',
      branchNo: currentNo,
      address: '',
      addressEN: '',
      provinceId: '',
      districtId: '',
      subDistrictId: '',
      zipCode: '',
      email: '',
      telephoneNo: '',
      name: '',
      status: 'CREATED',
      taxNo: '',
      nameEN: '',
      legalPersonNo: '',
      registerName: '',
      registerDate: new Date(),
      authorizedCapital: '',
      employmentOffice: '',
      bussinessType: '',
      bussinessTypeEN: '',
      jobPosition: '',
      jobPositionEN: '',
      jobDescription: '',
      saleEmployee: '',
      payDate: new Date(),
      wageRate: 0,
    });

    tab.value = customerBranch.value.length - 1;
  }
}

function close(index: number) {
  if (customerBranch.value.length < 2) return;

  if (
    customerBranch.value.length === index + 1 &&
    tab.value + 1 === customerBranch.value.length
  ) {
    tab.value = tab.value - 1;
  } else if (tab.value >= index) {
    if (tab.value !== 0) {
      tab.value = tab.value - 1;
    }
  }
  customerBranch.value.splice(index, 1);
}

onMounted(() => {
  customerBranch.value[0].branchNo =
    statBranchNo.value !== 0 ? statBranchNo.value : 1;
});
</script>
<template>
  <div class="row no-wrap full-width">
    <q-btn
      :id="`${prefixId}-btn-add`"
      class="q-px-lg bordered-b bordered-r app-text-muted"
      flat
      :color="$q.dark.isActive ? 'primary' : ''"
      style="background-color: var(--_body-bg)"
      @click="addData()"
      icon="mdi-plus"
      :disable="
        readonly ||
        !checkTabBeforeAdd(customerBranch || [], [
          'branchNo',
          'payDate',
          'registerDate',
          'status',
          'wageRate',
        ])
      "
    ></q-btn>
    <q-tabs
      :active-bg-color="$q.dark.isActive ? 'dark' : 'white'"
      :active-color="$q.dark.isActive ? 'white' : 'primary'"
      indicator-color="transparent"
      active-class="bordered-r"
      dense
      v-model="tab"
      align="left"
      inline-label
      mobile-arrows
      class="text-grey col"
      :breakpoint="0"
      style="background-color: var(--_body-bg); max-width: 55vw"
    >
      <q-tab
        :id="`${prefixId}-tab-branch-${index}`"
        v-for="(v, index) in customerBranch"
        :key="index"
        :name="index"
        :label="`${customerBranch[index].name !== '' ? customerBranch[index].name : $t('customerBranchFormTab')} `"
        :disable="tab !== index && edit"
        @click="tab = index"
        no-caps
        :class="tab === index ? '' : 'bordered-b bordered-r'"
      >
        <q-btn
          v-if="!readonly && customerBranch?.length !== 1"
          round
          flat
          :id="`${prefixId}-close-tab-${index}`"
          icon="mdi-close"
          size="sm"
          padding="xs"
          color="red"
          class="q-ml-sm"
          :class="{ dark: $q.dark.isActive }"
          @click.stop="
            () => {
              if (v.statusSave) {
                $emit('remove', index, v.id);
              } else {
                close(index);
              }
            }
          "
        />
      </q-tab>
    </q-tabs>
  </div>
  <div class="column seprarator-fix">
    <q-tab-panels v-model="tab" class="rounded-borders">
      <q-tab-panel
        :id="`${prefixId}-tab-branch-${index}`"
        v-for="(v, index) in customerBranch.sort(
          (a, b) => (a.branchNo ?? 0) - (b.branchNo ?? 0),
        )"
        :key="index"
        :name="index"
      >
        <slot name="about"></slot>
        <slot name="address"></slot>
        <slot name="businessInformation"></slot>
        <slot name="contactInformation"></slot>

        <slot name="otherDocuments"></slot>
        <div class="row col-12 justify-end">
          <q-btn
            v-if="!readonly"
            dense
            unelevated
            id="save-basic-info"
            color="primary"
            class="q-px-md"
            :label="$t('save')"
            @click="$emit('save')"
          />
        </div>
      </q-tab-panel>
    </q-tab-panels>
  </div>
</template>

<style scoped lang="scss">
.active-tab {
  border: 1px solid #e0dcdc;
  border-bottom: none;
  border-top: none;
  border-left: none;
}

.tab-style {
  border: 1px solid #e0dcdc;
  border-left: none;
  border-top: none;
}

:deep(.q-separator) {
  padding-block: 0px !important;
}
</style>
