<script setup lang="ts">
import { ref } from 'vue';
import { AddressForm } from 'components/form';
import EmployerFormBusiness from './EmployerFormBusiness.vue';
import EmployerFormContact from './EmployerFormContact.vue';
import { CustomerCreate } from 'stores/customer/types';
import EmployerFormAbout from './EmployerFormAbout.vue';
import EmployerFormAuthorized from './EmployerFormAuthorized.vue';
import { useCustomerForm } from 'src/pages/03_customer-management/form';
import { waitAll } from 'src/stores/utils';
import { FormCitizen } from 'components/upload-file/';

import useOcrStore from 'stores/ocr';
import useCustomerStore from 'stores/customer';

import {
  SaveButton,
  EditButton,
  DeleteButton,
  UndoButton,
} from 'components/button';
import { UploadFileGroup } from 'src/components/upload-file/';
import { uploadFileListCustomer, columnsAttachment } from '../../constant';
import { group } from 'node:console';

const ocrStore = useOcrStore();
const customerStore = useCustomerStore();
const item = defineModel<NonNullable<CustomerCreate['customerBranch']>[number]>(
  'customerBranch',
  { required: true },
);

const tab = ref('main');

defineEmits<{
  (e: 'edit'): void;
  (e: 'save'): void;
  (e: 'cancel'): void;
  (e: 'delete'): void;
}>();

withDefaults(
  defineProps<{
    index: number;
    customerName: string;
    readonly?: boolean;
    prefixId?: string;
    onCreate?: boolean;
    actionDisabled?: boolean;
    customerType?: 'CORP' | 'PERS';
    hideAction?: boolean;
  }>(),
  {
    hideAction: false,
  },
);
</script>

<template>
  <span
    class="col-12 text-weight-bold row items-center q-mb-sm"
    :style="{ opacity: actionDisabled ? '.5' : undefined }"
    :id="`form-branch-customer-no-${index}`"
    v-if="!hideAction"
  >
    {{
      index === 0
        ? $t('customer.form.headQuarters.title')
        : $t('customer.form.branch.title', { name: index || 0 })
    }}
    <div class="q-ml-auto row no-warp">
      <EditButton
        icon-only
        v-if="readonly"
        @click="$emit('edit')"
        class="q-ml-auto"
        type="button"
        :disabled="actionDisabled"
      />
      <DeleteButton
        icon-only
        v-if="readonly"
        @click="$emit('delete')"
        type="button"
        :disabled="actionDisabled"
      />
      <UndoButton
        icon-only
        v-if="!readonly && !onCreate"
        @click="$emit('cancel')"
        type="button"
        :disabled="actionDisabled"
      />
      <SaveButton
        v-if="!readonly"
        icon-only
        @click="$emit('save')"
        type="submit"
        :disabled="actionDisabled"
      />
    </div>
  </span>

  <div class="col-12" :style="{ opacity: actionDisabled ? '.5' : undefined }">
    <div class="rounded bordered">
      <q-tabs
        v-model="tab"
        dense
        align="left"
        class="bordered-b"
        active-color="primary"
        no-caps
        style="color: hsl(var(--text-mute))"
      >
        <q-tab name="main" :label="$t('customerBranch.tab.main')" />
        <q-tab name="business" :label="$t('customerBranch.tab.business')" />
        <q-tab
          v-if="customerType === 'CORP'"
          name="authorized"
          :label="$t('customerBranch.tab.authorized')"
        />
        <q-tab name="address" :label="$t('customerBranch.tab.address')" />
        <q-tab name="contact" :label="$t('customerBranch.tab.contact')" />
        <q-tab name="attachment" :label="$t('customerBranch.tab.attachment')" />
      </q-tabs>
      <q-tab-panels v-model="tab">
        <q-tab-panel name="main">
          <EmployerFormAbout
            :index="index.toString()"
            :readonly="readonly"
            :customer-type="customerType"
            v-model:citizen-id="item.citizenId"
            v-model:prefixName="item.namePrefix"
            v-model:firstName="item.firstName"
            v-model:lastName="item.lastName"
            v-model:firstNameEN="item.firstNameEN"
            v-model:lastNameEN="item.lastNameEN"
            v-model:gender="item.gender"
            v-model:birthDate="item.birthDate"
            v-model:customerName="item.customerName"
            v-model:legalPersonNo="item.legalPersonNo"
            v-model:branchCode="item.code"
            v-model:registerName="item.registerName"
            v-model:registerNameEN="item.registerNameEN"
            v-model:registerDate="item.registerDate"
            v-model:authorizedCapital="item.authorizedCapital"
            v-model:telephoneNo="item.telephoneNo"
            v-model:codeCustomer="item.codeCustomer"
          />
        </q-tab-panel>
        <q-tab-panel name="business">
          <EmployerFormBusiness
            dense
            outlined
            :prefix-id="prefixId || 'employer'"
            :readonly="readonly"
            v-model:bussiness-type="item.businessType"
            v-model:job-position="item.jobPosition"
            v-model:job-description="item.jobDescription"
            v-model:pay-date="item.payDate"
            v-model:pay-date-e-n="item.payDateEN"
            v-model:wage-rate="item.wageRate"
            v-model:wage-rate-text="item.wageRateText"
          />
        </q-tab-panel>
        <q-tab-panel v-if="customerType === 'CORP'" name="authorized">
          <EmployerFormAuthorized
            :prefix-id="prefixId || 'employer'"
            :readonly="readonly"
            v-model:authorized-name="item.authorizedName"
            v-model:authorized-name-e-n="item.authorizedNameEN"
          />
        </q-tab-panel>
        <q-tab-panel name="address">
          <AddressForm
            :prefix-id="prefixId || 'employer'"
            hide-title
            dense
            outlined
            use-employment
            :readonly="readonly"
            :title="$t('form.address')"
            v-model:homeCode="item.homeCode"
            v-model:employmentOffice="item.employmentOffice"
            v-model:employmentOfficeEN="item.employmentOfficeEN"
            v-model:address="item.address"
            v-model:addressEN="item.addressEN"
            v-model:street="item.street"
            v-model:streetEN="item.streetEN"
            v-model:moo="item.moo"
            v-model:mooEN="item.mooEN"
            v-model:soi="item.soi"
            v-model:soiEN="item.soiEN"
            v-model:province-id="item.provinceId"
            v-model:district-id="item.districtId"
            v-model:sub-district-id="item.subDistrictId"
            :addressTitle="$t('form.address')"
            :addressTitleEN="$t('form.address', { suffix: '(EN)' })"
          />
        </q-tab-panel>
        <q-tab-panel name="contact">
          <EmployerFormContact
            :readonly="readonly"
            v-model:contactName="item.contactName"
            v-model:email="item.email"
            v-model:contactTel="item.contactTel"
            v-model:officeTel="item.officeTel"
            v-model:agent="item.agent"
          />
        </q-tab-panel>
        <q-tab-panel name="attachment">
          <UploadFileGroup
            v-model:current-id="item.id"
            v-model="item.file"
            hide-action
            :ocr="
              async (group, file) => {
                const res = await ocrStore.sendOcr({
                  file: file,
                  category: group,
                });

                if (res) {
                  const tempValue = {
                    status: true,
                    group,
                    meta: res.fields,
                  };

                  return tempValue;
                }
                return { status: false, group, meta: [] };
              }
            "
            :menu="uploadFileListCustomer"
            :columns="columnsAttachment"
            :auto-save="item.id !== ''"
            :download="
              (obj) => {
                customerStore.getFile({
                  parentId: item.id || '',
                  group: obj.group,
                  fileId: obj._meta.id,
                  download: true,
                });
              }
            "
            :delete-item="
              async (obj) => {
                const res = await customerStore.delMeta({
                  parentId: item.id || '',
                  group: obj.group,
                  metaId: obj._meta.id,
                });

                if (res) {
                  return true;
                }
                return false;
              }
            "
            :save="
              async (
                group:
                  | 'citizen'
                  | 'house-registration'
                  | 'commercial-registration'
                  | 'vat-registration'
                  | 'power-of-attorney',
                _meta: any,
                file: File | undefined,
              ) => {
                if (file !== undefined && item.id) {
                  const res = await customerStore.postMeta({
                    parentId: item.id || '',
                    group,
                    meta: _meta,
                    file,
                  });

                  if (res) {
                    return true;
                  }
                } else {
                  const {
                    customerBranchId,
                    id,
                    employeeId,
                    createdAt,
                    updatedAt,
                    middleName,
                    middleNameEN,

                    ...payload
                  } = _meta;
                  const res = await customerStore.putMeta({
                    parentId: item.id || '',
                    group,
                    metaId: _meta.id,
                    meta: payload,
                    file,
                  });
                  if (res) {
                    return true;
                  }
                }

                return false;
              }
            "
            :get-file-list="
              async (
                group:
                  | 'citizen'
                  | 'house-registration'
                  | 'commercial-registration'
                  | 'vat-registration'
                  | 'power-of-attorney',
              ) => {
                if (!!item.id) {
                  if (group === 'citizen') {
                    const resMeta = await customerStore.getMetaList({
                      parentId: item.id,
                      group,
                    });

                    const tempValue = resMeta.map(async (v: any) => {
                      return {
                        _meta: { ...v },
                        name: v.id || '',
                        group: group,
                        url: await customerStore.getFile({
                          parentId: item.id || '',
                          group,
                          fileId: v.id,
                        }),
                        file: undefined,
                      };
                    });

                    return await waitAll(tempValue);
                  }
                }
                return [];
              }
            "
          >
            <template #form="{ mode, meta, isEdit }">
              <FormCitizen
                v-if="mode === 'citizen' && meta"
                orc
                ra
                :readonly="!isEdit"
                v-model:name-prefix="meta.namePrefix"
                v-model:citizen-id="meta.citizenId"
                v-model:birth-date="meta.birthDate"
                v-model:first-name="meta.firstName"
                v-model:first-name-en="meta.firstNameEN"
                v-model:last-name="meta.lastName"
                v-model:last-name-en="meta.lastNameEN"
                v-model:gender="meta.gender"
                v-model:religion="meta.religion"
                v-model:nationality="meta.nationality"
                v-model:expire-date="meta.expireDate"
                v-model:issue-date="meta.issueDate"
                v-model:homeCode="meta.homeCode"
                v-model:employmentOffice="meta.employmentOffice"
                v-model:employmentOfficeEN="meta.employmentOfficeEN"
                v-model:address="meta.address"
                v-model:addressEN="meta.addressEN"
                v-model:street="meta.street"
                v-model:streetEN="meta.streetEN"
                v-model:moo="meta.moo"
                v-model:mooEN="meta.mooEN"
                v-model:soi="meta.soi"
                v-model:soiEN="meta.soiEN"
                v-model:province-id="meta.provinceId"
                v-model:district-id="meta.districtId"
                v-model:sub-district-id="meta.subDistrictId"
                v-model:middle-name="meta.middleName"
                v-model:middle-name-en="meta.middleNameEN"
              />
              <FormEmployeePassport
                v-if="mode === 'passport' && meta"
                prefix-id="drawer-info-employee"
                id="form-passport"
                dense
                outlined
                separator
                ocr
                :title="$t('customerEmployee.form.group.passport')"
                :readonly="!isEdit"
                v-model:passport-type="meta.type"
                v-model:passport-number="meta.number"
                v-model:passport-issue-date="meta.issueDate"
                v-model:passport-expiry-date="meta.expireDate"
                v-model:passport-issuing-place="meta.issuePlace"
                v-model:passport-issuing-country="meta.issueCountry"
              />
              <FormEmployeeVisa
                v-if="mode === 'visa' && meta"
                prefix-id="drawer-info-employee"
                id="form-visa"
                ocr
                dense
                outlined
                title="customerEmployee.form.group.visa"
                :readonly="!isEdit"
                v-model:visa-type="meta.type"
                v-model:visa-number="meta.number"
                v-model:visa-issue-date="meta.issueDate"
                v-model:visa-expiry-date="meta.expireDate"
                v-model:visa-issuing-place="meta.issuePlace"
              />
            </template>
          </UploadFileGroup>

          <!-- <EmployerFormAttachment
            :readonly="readonly"
            v-model:attachment="item.file"
          /> -->
        </q-tab-panel>
      </q-tab-panels>
    </div>
  </div>
</template>
