import {
  createDefaultStoreInputForm,
  createDefaultDoctorInputForm,
} from '@/subPackages/sub_salesperson/common/inputFormHelpers.js'

export function serializeStoreDraft(vm) {
  return {
    form: JSON.parse(JSON.stringify(vm.form)),
    ui: {
      currentStep: vm.currentStep,
      clinicTypeIndex: vm.clinicTypeIndex,
      bankTypeIndex: vm.bankTypeIndex,
    },
  }
}

export function applyStoreDraft(vm, draft) {
  if (!draft) return
  Object.assign(vm.form, createDefaultStoreInputForm(), draft.form || {})
  if (!Array.isArray(vm.form.url)) vm.form.url = []
  if (!Array.isArray(vm.form.contract_files)) vm.form.contract_files = []
  const ui = draft.ui || {}
  vm.currentStep = ui.currentStep != null ? ui.currentStep : 0
  vm.clinicTypeIndex = ui.clinicTypeIndex != null ? ui.clinicTypeIndex : (Number(vm.form.clinic_type) === 1 ? 0 : 1)
  vm.bankTypeIndex = ui.bankTypeIndex != null
    ? ui.bankTypeIndex
    : Math.max(0, vm.bankTypes.findIndex((b) => b.value === Number(vm.form.bank_account_type)))
}

export function applyDoctorDraft(vm, draft) {
  if (!draft) return
  Object.assign(vm.form, createDefaultDoctorInputForm(), draft.form || {})
  const ui = draft.ui || {}
  vm.selectedStoreInputIds = Array.isArray(ui.selectedStoreInputIds)
    ? [...ui.selectedStoreInputIds]
    : (Array.isArray(ui.selectedStoreIds) ? [...ui.selectedStoreIds] : [])
  vm.selectedStoreIds = Array.isArray(ui.selectedStoreIds) ? [...ui.selectedStoreIds] : []
  vm.departIndex = ui.departIndex != null ? ui.departIndex : Math.max(0, vm.departOptions.findIndex((d) => d.id === vm.form.depart_id))
  vm.titleIndex = ui.titleIndex != null ? ui.titleIndex : Math.max(0, vm.titleOptions.findIndex((t) => t.id === vm.form.title_id))
  vm.typeIndex = ui.typeIndex != null ? ui.typeIndex : (Number(vm.form.type) === 2 ? 1 : 0)
  vm.signTypeIndex = ui.signTypeIndex != null ? ui.signTypeIndex : (Number(vm.form.sign_type) === 2 ? 1 : 0)
  vm.currentStep = ui.currentStep != null ? ui.currentStep : 0
}

export function serializeDoctorDraft(vm) {
  return {
    form: JSON.parse(JSON.stringify(vm.form)),
    ui: {
      selectedStoreInputIds: [...(vm.selectedStoreInputIds || [])],
      selectedStoreIds: [...(vm.selectedStoreIds || [])],
      departIndex: vm.departIndex,
      titleIndex: vm.titleIndex,
      typeIndex: vm.typeIndex,
      signTypeIndex: vm.signTypeIndex,
      currentStep: vm.currentStep,
    },
  }
}
