import { ref, toRaw, watch } from 'vue';
import { defineStore } from 'pinia';
import { CustomerBranchCreate, CustomerCreate } from 'stores/customer/types';
import { Employee, EmployeeCreate } from 'stores/employee/types';
import { useI18n } from 'vue-i18n';

import useMyBranch from 'stores/my-branch';
import useCustomerStore from 'stores/customer';
import useEmployeeStore from 'stores/employee';
import useFlowStore from 'stores/flow';

import { baseUrl } from 'src/stores/utils';

export const useCustomerForm = defineStore('form-customer', () => {
  const { t } = useI18n();

  const customerStore = useCustomerStore();
  const branchStore = useMyBranch();

  const defaultFormData: CustomerCreate = {
    // code: '',
    // namePrefix: '',
    // firstName: '',
    // lastName: '',
    // firstNameEN: '',
    // lastNameEN: '',
    // gender: '',
    // birthDate: new Date(),
    customerBranch: [],
    selectedImage: '',
    status: 'CREATED',
    customerType: 'CORP',
    registeredBranchId: branchStore.currentMyBranch?.id || '',
    image: null,
  };
  let resetFormData = structuredClone(defaultFormData);

  const currentFormData = ref<CustomerCreate>(structuredClone(defaultFormData));
  const state = ref<{
    dialogType: 'info' | 'create' | 'edit';
    dialogOpen: boolean;
    dialogModal: boolean;
    drawerModal: boolean;
    branchIndex: number;
    customerImageUrl: string;
    defaultCustomerImageUrl: string;
    imageDialog: boolean;
    imageEdit: boolean;
    readonly: boolean;
    editCustomerId?: string;
    editCustomerCode?: string;
    editCustomerBranchId?: string;
    treeFile: { label: string; file: { label: string }[] }[];
    formDataOcr: Record<string, any>;
    isImageEdit: boolean;
  }>({
    dialogType: 'info',
    dialogOpen: false,
    dialogModal: false,
    drawerModal: false,
    imageDialog: false,
    branchIndex: -1,
    readonly: true,
    imageEdit: false,
    customerImageUrl: '',
    editCustomerId: '',
    editCustomerBranchId: '',
    defaultCustomerImageUrl: '',
    treeFile: [],
    formDataOcr: {},
    isImageEdit: false,
  });

  watch(
    currentFormData,
    (v) => (defaultFormData.customerType = v.customerType),
  );

  async function deleteAttachment(
    id: { branchId: string; customerId: string },
    filename: string,
  ) {
    const res = await customerStore.deleteAttachment(id.branchId, filename);
    if (res) {
      assignFormData(id.customerId);
    }
  }

  function isFormDataDifferent() {
    const { status: resetStatus, ...resetData } = resetFormData;
    const { status: currStatus, ...currData } = currentFormData.value;

    return JSON.stringify(resetData) !== JSON.stringify(currData);
  }

  function resetForm(clean = false) {
    state.value.branchIndex = -1;
    if (clean) {
      defaultFormData.customerType = currentFormData.value.customerType;
      currentFormData.value = structuredClone(defaultFormData);
      currentFormData.value.registeredBranchId =
        branchStore.currentMyBranch?.id || '';
      resetFormData = structuredClone(defaultFormData);
      resetFormData.registeredBranchId = branchStore.currentMyBranch?.id || '';
      state.value.editCustomerId = '';
      state.value.treeFile = [];

      return;
    }

    if (!resetFormData.registeredBranchId) {
      resetFormData.registeredBranchId = branchStore.currentMyBranch?.id || '';
    }

    if (state.value.dialogType === 'create') {
      state.value.editCustomerId = '';
    }
    const currentImg = currentFormData.value.selectedImage;
    currentFormData.value = structuredClone(resetFormData);
    currentFormData.value.selectedImage = currentImg;
  }

  async function assignFormData(id?: string) {
    state.value.readonly = true;

    if (!id) {
      resetFormData = structuredClone(defaultFormData);
      return;
    }

    const data = await customerStore.fetchById(id);

    if (!data) return;

    state.value.dialogType = 'edit';
    state.value.editCustomerId = id;
    state.value.editCustomerCode = data.code;
    state.value.customerImageUrl = `${baseUrl}/customer/${id}/image/${data.selectedImage}`;
    state.value.defaultCustomerImageUrl = `${baseUrl}/customer/${id}/image/${data.selectedImage}`;

    resetFormData.registeredBranchId = data.registeredBranchId;
    resetFormData.status = data.status;
    resetFormData.customerType = data.customerType;
    resetFormData.image = null;
    resetFormData.selectedImage = data.selectedImage;

    resetFormData.customerBranch = await Promise.all(
      data.branch.map(async (v) => ({
        firstName: v.firstName,
        firstNameEN: v.firstNameEN,
        lastName: v.lastName,
        lastNameEN: v.lastNameEN,
        gender: v.gender,
        birthDate: v.birthDate,
        namePrefix: v.namePrefix,
        wageRate: v.wageRate,
        wageRateText: v.wageRateText,
        payDate: v.payDate,
        jobDescription: v.jobDescription,
        jobPositionEN: v.jobPositionEN,
        jobPosition: v.jobPosition,
        businessTypeEN: v.businessTypeEN,
        businessType: v.businessType,
        employmentOffice: v.employmentOffice,
        employmentOfficeEN: v.employmentOfficeEN,
        telephoneNo: v.telephoneNo,
        contactName: v.contactName,
        email: v.email,
        subDistrictId: v.subDistrictId,
        districtId: v.districtId,
        provinceId: v.provinceId,
        streetEN: v.streetEN,
        street: v.street,
        mooEN: v.mooEN,
        moo: v.moo,
        soiEN: v.soiEN,
        soi: v.soi,
        addressEN: v.addressEN,
        address: v.address,
        authorizedCapital: v.authorizedCapital,
        registerDate: v.registerDate,
        registerNameEN: v.registerNameEN,
        registerName: v.registerName,
        legalPersonNo: v.legalPersonNo,
        citizenId: v.citizenId,
        codeCustomer: v.codeCustomer,
        updatedByUserId: v.updatedByUserId,
        updatedAt: v.updatedAt,
        createdByUserId: v.createdByUserId,
        createdAt: v.createdAt,
        code: v.code,
        statusOrder: v.statusOrder,
        status: v.status,
        customerId: v.customerId,
        id: v.id,
        homeCode: v.homeCode,
        contactTel: v.contactTel,
        officeTel: v.officeTel,
        agent: v.agent,
        customerName: v.customerName,
        authorizedName: v.authorizedName,
        authorizedNameEN: v.authorizedNameEN,

        payDateEN: v.payDateEN,
        statusSave: true,
        file: await customerStore.listAttachment(v.id).then(async (r) => {
          if (r) {
            return await Promise.all(
              r.map(async (item) => {
                const fragment = item.split('-');
                const group = fragment.length === 1 ? 'other' : fragment.at(0);

                return {
                  url: await customerStore.getAttachment(v.id, item),
                  name: item,
                  group: group,
                };
              }),
            );
          }
          return [];
        }),
      })),
    );

    currentFormData.value = structuredClone(resetFormData);
  }

  async function addCurrentCustomerBranch() {
    if (currentFormData.value.customerBranch?.some((v) => !v.id)) return;
    currentFormData.value.customerBranch?.push({
      id: '',
      customerId: '',
      branchCode:
        currentFormData.value.customerBranch.length !== 0
          ? currentFormData.value.customerBranch?.[0].branchCode === null
            ? ''
            : currentFormData.value.customerBranch?.[0].branchCode
          : '',
      codeCustomer: '',

      legalPersonNo:
        currentFormData.value.customerBranch.length !== 0
          ? currentFormData.value.customerBranch?.[0].legalPersonNo === null
            ? ''
            : currentFormData.value.customerBranch?.[0].legalPersonNo
          : '',
      citizenId:
        currentFormData.value.customerBranch.length !== 0
          ? currentFormData.value.customerBranch?.[0].citizenId === null
            ? ''
            : currentFormData.value.customerBranch?.[0].citizenId
          : '',
      namePrefix: '',
      firstName: '',
      lastName: '',
      firstNameEN: '',
      lastNameEN: '',
      telephoneNo: '',
      gender: '',
      birthDate: '',

      businessType: '',
      jobPosition: '',
      jobDescription: '',
      payDate: '',
      payDateEN: '',
      wageRate: 0,
      wageRateText: '',
      homeCode: '',
      employmentOffice: '',
      employmentOfficeEN: '',

      address: '',
      addressEN: '',
      street: '',
      streetEN: '',
      moo: '',
      mooEN: '',
      soi: '',
      soiEN: '',
      provinceId: '',
      districtId: '',
      subDistrictId: '',

      contactName: '',
      email: '',
      contactTel: '',
      officeTel: '',
      agent: '',
      status: 'CREATED',

      customerName: '',
      registerName: '',
      registerNameEN: '',
      registerDate: null,
      authorizedCapital: '',
      authorizedName: '',
      authorizedNameEN: '',
      file: [],
    });
    state.value.branchIndex =
      (currentFormData.value.customerBranch?.length || 0) - 1;
  }

  async function submitFormCustomer(imgList?: {
    selectedImage: string;
    list: { url: string; imgFile: File | null; name: string }[];
  }) {
    if (state.value.dialogType === 'info') return;

    if (state.value.dialogType === 'create') {
      const _data = await customerStore.create(currentFormData.value, imgList);

      if (_data) await assignFormData(_data.id);

      return;
    }

    if (!state.value.editCustomerId) {
      throw new Error(
        'Form mode is set to edit but no ID is provided. Make sure to set customer ID.',
      );
    }

    const { code: _, ...payload } = currentFormData.value;

    const _data = await customerStore.editById(state.value.editCustomerId, {
      ...payload,
      status:
        currentFormData.value.status !== 'CREATED'
          ? currentFormData.value.status
          : undefined,
      image: currentFormData.value.image || undefined,
      customerBranch: undefined,
    });

    if (_data) {
      await assignFormData(_data.id);
      state.value.dialogType = 'edit';
      state.value.readonly = true;
      state.value.editCustomerId = _data.id;
    }
  }

  return {
    state,
    resetFormData,
    currentFormData,
    isFormDataDifferent,
    resetForm,
    assignFormData,
    submitFormCustomer,
    addCurrentCustomerBranch,
    deleteAttachment,
  };
});

export const useCustomerBranchForm = defineStore('form-customer-branch', () => {
  const customerStore = useCustomerStore();
  const customerFormStore = useCustomerForm();

  const defaultFormData: CustomerBranchCreate & {
    id?: string;
    codeCustomer?: string;
  } = {
    id: '',
    customerId: '',
    // branchCode: '',
    // codeCustomer: '',

    legalPersonNo: '',
    citizenId: '',
    namePrefix: '',
    firstName: '',
    lastName: '',
    firstNameEN: '',
    lastNameEN: '',
    telephoneNo: '',
    gender: '',
    birthDate: '',

    businessType: '',
    jobPosition: '',
    jobDescription: '',
    payDate: '',
    payDateEN: '',
    wageRate: 0,
    wageRateText: '',
    homeCode: '',
    employmentOffice: '',
    employmentOfficeEN: '',

    address: '',
    addressEN: '',
    street: '',
    streetEN: '',
    moo: '',
    mooEN: '',
    soi: '',
    soiEN: '',
    provinceId: '',
    districtId: '',
    subDistrictId: '',

    contactName: '',
    email: '',
    contactTel: '',
    officeTel: '',
    agent: '',
    status: 'CREATED',

    customerName: '',
    registerName: '',
    registerNameEN: '',
    registerDate: null,
    authorizedCapital: '',
    authorizedName: '',
    authorizedNameEN: '',
    file: [],
  };

  let resetFormData = structuredClone(defaultFormData);

  const currentFormData = ref<CustomerBranchCreate & { id?: string }>(
    structuredClone(defaultFormData),
  );

  const state = ref<{
    dialogType: 'info' | 'create' | 'edit';
    dialogOpen: boolean;
    dialogModal: boolean;
    currentCustomerId: string;
  }>({
    dialogType: 'info',
    dialogOpen: false,
    dialogModal: false,
    currentCustomerId: '',
  });

  async function initForm(form: 'create'): Promise<void>;
  async function initForm(form: 'info' | 'edit', id: string): Promise<void>;
  async function initForm(form: 'info' | 'create' | 'edit', id?: string) {
    state.value.dialogType = form;

    resetFormData = structuredClone(defaultFormData);

    if (!id) return;

    const _data = await customerStore.getBranchById(id);

    if (!_data) return;
    resetFormData = {
      id: _data.id,
      code: _data.code,
      customerCode: '',
      provinceId: _data.provinceId,
      districtId: _data.districtId,
      subDistrictId: _data.subDistrictId,
      wageRate: _data.wageRate,
      payDate: _data.payDate, // Convert the string to a Date object
      payDateEN: _data.payDateEN,
      jobDescription: _data.jobDescription,
      jobPosition: _data.jobPosition,
      businessType: _data.businessType,
      employmentOffice: _data.employmentOffice,
      employmentOfficeEN: _data.employmentOfficeEN,
      telephoneNo: _data.telephoneNo,
      email: _data.email,
      addressEN: _data.addressEN,
      address: _data.address,
      status: 'CREATED',
      customerId: _data.customerId,
      citizenId: _data.citizenId,
      authorizedCapital: _data.authorizedCapital,
      registerDate: new Date(), // Convert the string to a Date object
      registerNameEN: _data.registerNameEN,
      registerName: _data.registerName,
      legalPersonNo: _data.legalPersonNo,
      contactName: _data.contactName,
      namePrefix: _data.namePrefix,
      firstName: _data.firstName,
      firstNameEN: _data.firstNameEN,
      lastName: _data.lastName,
      lastNameEN: _data.lastNameEN,
      gender: _data.gender,
      birthDate: _data.birthDate,
      moo: _data.moo,
      mooEN: _data.mooEN,
      soi: _data.soi,
      soiEN: _data.soiEN,
      street: _data.street,
      streetEN: _data.streetEN,
      wageRateText: _data.wageRateText,
      contactTel: _data.contactTel,
      officeTel: _data.officeTel,
      agent: _data.agent,
      codeCustomer: _data.codeCustomer,
      customerName: _data.customerName,
      homeCode: _data.homeCode,
      authorizedName: _data.authorizedName,
      authorizedNameEN: _data.authorizedNameEN,
      statusSave: false,
      file: [],
    };

    currentFormData.value = structuredClone(resetFormData);
  }

  function isFormDataDifferent() {
    return (
      JSON.stringify(resetFormData) !== JSON.stringify(currentFormData.value)
    );
  }

  watch(
    () => state.value.dialogType,
    () => {
      if (state.value.dialogType === 'create') {
        currentFormData.value = structuredClone(defaultFormData);
      }
    },
  );

  async function submitForm() {
    console.log(currentFormData.value);
    if (!state.value.currentCustomerId) {
      throw new Error(
        'Employer id cannot be found. Did you properly set employer id?',
      );
    }

    if (!currentFormData.value.id) {
      const res = await customerStore.createBranch({
        ...currentFormData.value,
        citizenId:
          customerFormStore.currentFormData.customerType === 'CORP'
            ? undefined
            : currentFormData.value.citizenId,
        customerId: state.value.currentCustomerId,
      });
      if (res) return res;
    } else {
      const res = await customerStore.editBranchById(currentFormData.value.id, {
        ...currentFormData.value,
        id: undefined,
      });
      if (res) return res;
    }
  }

  return {
    state,
    currentFormData,
    initForm,
    isFormDataDifferent,
    submitForm,
  };
});

export const useEmployeeForm = defineStore('form-employee', () => {
  const customerStore = useCustomerStore();
  const employeeStore = useEmployeeStore();
  const flowStore = useFlowStore();
  const branchStore = useMyBranch();

  const state = ref<{
    dialogType: 'info' | 'create' | 'edit';
    imageDialog: boolean;
    currentTab: string;
    dialogModal: boolean;
    drawerModal: boolean;
    isImageEdit: boolean;

    currentEmployeeCode: string;
    currentEmployee: Employee | null;
    currentIndex: number;
    profileUrl: string;
    isEmployeeEdit: boolean;
    profileSubmit: boolean;
    formDataEmployeeSameAddr: boolean;
    editReadonly: boolean;
    statusSavePersonal: boolean;
    infoEmployeePersonCard: {
      id: string;
      img?: string;
      name: string;
      male: boolean;
      female: boolean;
      badge: string;
      disabled: boolean;
    }[];
    formDataEmployeeOwner:
      | {
          id: string;
          address: string;
          addressEN: string;
          provinceId: string;
          districtId: string;
          subDistrictId: string;
          zipCode: string;
        }
      | undefined;
    ocr: boolean;
  }>({
    isImageEdit: false,
    currentIndex: -1,
    statusSavePersonal: false,
    drawerModal: false,
    imageDialog: false,
    currentTab: 'personalInfo',
    dialogModal: false,
    dialogType: 'info',
    currentEmployeeCode: '',
    currentEmployee: null,
    profileUrl: '',
    isEmployeeEdit: false,
    profileSubmit: false,
    formDataEmployeeSameAddr: true,
    editReadonly: false,
    infoEmployeePersonCard: [],
    formDataEmployeeOwner: undefined,
    ocr: false,
  });

  const defaultFormData: EmployeeCreate = {
    id: '',
    code: '',
    customerBranchId: '',
    nrcNo: '',
    dateOfBirth: null,
    gender: '',
    nationality: '',
    status: 'CREATED',

    namePrefix: '',
    firstName: '',
    firstNameEN: '',
    lastName: '',
    lastNameEN: '',
    middleName: '',
    middleNameEN: '',

    addressEN: '',
    address: '',
    zipCode: '',

    subDistrictId: '',
    districtId: '',
    provinceId: '',

    employeeWork: [
      {
        workEndDate: null,
        workPermitExpireDate: null,
        workPermitIssuDate: null,
        workPermitNo: '',
        workplace: '',
        jobType: '',
        positionName: '',
        ownerName: '',
        remark: '',
      },
    ],
    employeeCheckup: [
      {
        coverageExpireDate: null,
        coverageStartDate: null,
        insuranceCompany: '',
        medicalBenefitScheme: '',
        remark: '',
        hospitalName: '',
        provinceId: '',
        checkupResult: '',
        checkupType: '',
      },
    ],
    employeeOtherInfo: {
      citizenId: '',
      fatherFirstName: '',
      fatherLastName: '',
      fatherFirstNameEN: '',
      fatherLastNameEN: '',
      fatherBirthPlace: '',

      motherFirstName: '',
      motherLastName: '',
      motherFirstNameEN: '',
      motherLastNameEN: '',
      motherBirthPlace: '',
    },
    image: null,
  };

  let resetEmployeeData = structuredClone(defaultFormData);
  const currentFromDataEmployee = ref<EmployeeCreate>(
    structuredClone(defaultFormData),
  );

  function isFormDataDifferent() {
    return (
      JSON.stringify(resetEmployeeData) !==
      JSON.stringify(currentFromDataEmployee.value)
    );
  }

  // function resetFormDataEmployee(cb?: (...args: any[]) => unknown) {
  //   state.value.dialogType = 'create';
  //   currentFromDataEmployee.value = structuredClone(resetEmployeeData);
  //   cb?.();
  // }

  function resetFormDataEmployee(clean = false) {
    if (clean) {
      state.value.currentTab = 'personalInfo';
      state.value.formDataEmployeeOwner = undefined;
      resetEmployeeData = structuredClone(defaultFormData);
      state.value.statusSavePersonal = false;
      state.value.profileUrl = '';
    } else {
      resetEmployeeData.selectedImage =
        currentFromDataEmployee.value.selectedImage;
    }
    currentFromDataEmployee.value = structuredClone(resetEmployeeData);
  }

  async function submitOther() {
    if (!currentFromDataEmployee.value.employeeOtherInfo) return;

    if (!currentFromDataEmployee.value.employeeOtherInfo.id) {
      const res = await employeeStore.createEmployeeOtherInfo(
        currentFromDataEmployee.value?.id || '',
        currentFromDataEmployee.value.employeeOtherInfo,
      );

      if (res) {
        currentFromDataEmployee.value.employeeOtherInfo.id = res.id;
        currentFromDataEmployee.value.employeeOtherInfo.statusSave = true;
      }
    } else {
      const res = await employeeStore.editByIdEmployeeOtherInfo(
        currentFromDataEmployee.value?.id || '',
        currentFromDataEmployee.value.employeeOtherInfo,
      );
      if (res) {
        currentFromDataEmployee.value.employeeOtherInfo.statusSave = true;
      }
    }

    await assignFormDataEmployee(currentFromDataEmployee.value.id);
  }

  async function deleteWorkHistory() {
    if (!currentFromDataEmployee.value.employeeWork) return;

    const res = await employeeStore.deleteByIdWork({
      employeeId: currentFromDataEmployee.value.id || '',
      workId:
        currentFromDataEmployee.value.employeeWork[state.value.currentIndex]
          ?.id,
    });

    if (res) {
      await assignFormDataEmployee(currentFromDataEmployee.value.id);
    }
  }

  async function deleteHealthCheck() {
    if (!currentFromDataEmployee.value.employeeCheckup) return;

    const res = await employeeStore.deleteByIdCheckUp({
      employeeId: currentFromDataEmployee.value.id || '',
      checkUpId:
        currentFromDataEmployee.value.employeeCheckup[state.value.currentIndex]
          ?.id,
    });

    if (res) {
      currentFromDataEmployee.value.employeeCheckup.splice(
        state.value.currentIndex,
        1,
      );
    }
    await assignFormDataEmployee(currentFromDataEmployee.value.id);
  }

  async function submitWorkHistory() {
    if (!currentFromDataEmployee.value.employeeWork) return;

    if (
      !currentFromDataEmployee.value.employeeWork[state.value.currentIndex].id
    ) {
      const res = await employeeStore.createEmployeeWork(
        currentFromDataEmployee.value?.id || '',
        currentFromDataEmployee.value.employeeWork[state.value.currentIndex],
      );
      if (res) {
        currentFromDataEmployee.value.employeeWork[
          state.value.currentIndex
        ].id = res.id;
        currentFromDataEmployee.value.employeeWork[
          state.value.currentIndex
        ].statusSave = true;
      }
    } else {
      const data =
        currentFromDataEmployee.value?.employeeWork[state.value.currentIndex];

      const res = await employeeStore.editByIdEmployeeWork(
        currentFromDataEmployee.value?.id || '',
        data,
      );

      if (res) {
        currentFromDataEmployee.value.employeeWork[
          state.value.currentIndex
        ].statusSave = true;
      }
    }
    await assignFormDataEmployee(currentFromDataEmployee.value.id);
  }

  async function submitHealthCheck() {
    if (!currentFromDataEmployee.value.employeeCheckup) return;

    if (
      !currentFromDataEmployee.value.employeeCheckup[state.value.currentIndex]
        .id
    ) {
      const res = await employeeStore.createEmployeeCheckup(
        state.value.currentEmployee?.id || '',
        currentFromDataEmployee.value.employeeCheckup[state.value.currentIndex],
      );

      if (res) {
        currentFromDataEmployee.value.employeeCheckup[
          state.value.currentIndex
        ].id = res.id;

        currentFromDataEmployee.value.employeeCheckup[
          state.value.currentIndex
        ].statusSave = true;
      }
    } else {
      const data =
        currentFromDataEmployee.value.employeeCheckup[state.value.currentIndex];

      const res = await employeeStore.editByIdEmployeeCheckup(
        state.value.currentEmployee?.id || '',
        data,
      );

      if (res) {
        currentFromDataEmployee.value.employeeCheckup[
          state.value.currentIndex
        ].statusSave = true;
      }
    }

    await assignFormDataEmployee(currentFromDataEmployee.value.id);
  }

  async function submitPersonal(imgList?: {
    selectedImage: string;
    list: { url: string; imgFile: File | null; name: string }[];
  }) {
    if (state.value.dialogType === 'create') {
      const res = await employeeStore.create(
        {
          ...currentFromDataEmployee.value,
          customerBranchId: state.value.formDataEmployeeOwner?.id || '',

          employeeWork: [],
          employeeCheckup: [],
          employeeOtherInfo: undefined,
        },
        imgList,
      );

      if (res) {
        await assignFormDataEmployee(res.id);
        currentFromDataEmployee.value.id = res.id;
        currentFromDataEmployee.value.file = res.file;
        state.value.statusSavePersonal = true;
      }
    }
    if (state.value.dialogType === 'edit') {
      const res = await employeeStore.editById(
        state.value.currentEmployee?.id || '',
        {
          ...currentFromDataEmployee.value,
          status:
            state.value.currentEmployee?.status === 'CREATED'
              ? 'ACTIVE'
              : state.value.currentEmployee?.status,
          customerBranchId: state.value.formDataEmployeeOwner?.id || '',
          employeeWork: [],
          employeeCheckup: [],
          employeeOtherInfo: undefined,
        },
      );
      if (res) {
        await assignFormDataEmployee(res.id);
        state.value.statusSavePersonal = true;
      }
    }
  }

  async function assignFormDataEmployee(id?: string) {
    if (!id) {
      resetEmployeeData = structuredClone(defaultFormData);
      return;
    }

    const _data = await employeeStore.fetchById(id);

    if (_data) {
      const _attach = await employeeStore.listAttachment(_data.id);

      state.value.currentEmployee = _data;

      const {
        createdAt,
        createdByUserId,
        statusOrder,
        province,
        district,
        subDistrict,
        updatedAt,
        updatedByUserId,
        createdBy,
        updatedBy,
        profileImageUrl,
        ...payload
      } = _data;

      resetEmployeeData = {
        ...payload,
        provinceId: province?.id,
        districtId: district?.id,
        subDistrictId: subDistrict?.id,
        employeeCheckup: structuredClone(
          payload.employeeCheckup?.length === 0
            ? defaultFormData.employeeCheckup
            : payload.employeeCheckup?.map((item) => ({
                ...item,
                statusSave: true,
              })),
        ),
        employeeOtherInfo: structuredClone(
          {
            ...payload.employeeOtherInfo,
            statusSave: !!payload.employeeOtherInfo?.id ? true : false,
          } || {},
        ),
        employeeWork: structuredClone(
          payload.employeeWork?.length === 0
            ? defaultFormData.employeeWork
            : payload.employeeWork?.map((item) => ({
                ...item,
                statusSave: true,
              })),
        ),
        file: _attach
          ? await Promise.all(
              _attach.map(async (name) => {
                const fragment = name.split('-');
                const group = fragment.length === 1 ? 'other' : fragment.at(0);

                return {
                  url: await employeeStore.getAttachment(_data.id, name),
                  name,
                  group,
                };
              }),
            )
          : [],
      };

      currentFromDataEmployee.value = structuredClone(resetEmployeeData);
      const foundBranch = await customerStore.fetchListCustomeBranchById(
        payload.customerBranchId,
      );

      state.value.currentEmployeeCode = payload.code;

      state.value.profileUrl =
        `${baseUrl}/employee/${id}/image/${_data.selectedImage}` || '';

      profileImageUrl
        ? (state.value.profileSubmit = true)
        : (state.value.profileSubmit = false);

      state.value.formDataEmployeeOwner = { ...foundBranch };

      if (
        foundBranch.address === payload.address &&
        foundBranch.zipCode === payload.zipCode
      ) {
        state.value.formDataEmployeeSameAddr = true;
      } else {
        state.value.formDataEmployeeSameAddr = false;
      }

      if (
        state.value.infoEmployeePersonCard &&
        Array.isArray(state.value.infoEmployeePersonCard) &&
        state.value.infoEmployeePersonCard.length > 0 &&
        profileImageUrl !== null
      ) {
        if (typeof state.value.infoEmployeePersonCard[0] === 'object') {
          state.value.infoEmployeePersonCard[0].img = profileImageUrl;
        }
      }
      flowStore.rotate();
    }
  }

  async function employeeFilterOwnerBranch(
    val: string,
    update: (...args: unknown[]) => void,
  ) {
    update(async () => {
      const result = await customerStore.fetchListCustomeBranch({
        includeCustomer: true,
        query: val,
        pageSize: 30,
      });
      if (result) employeeStore.ownerOption = result.result;
    });
  }

  return {
    state,
    currentFromDataEmployee,
    resetEmployeeData,

    submitOther,
    submitWorkHistory,
    submitPersonal,
    submitHealthCheck,

    deleteWorkHistory,
    deleteHealthCheck,

    resetFormDataEmployee,
    assignFormDataEmployee,

    employeeFilterOwnerBranch,

    isFormDataDifferent,
  };
});
