<script setup lang="ts">
import { ref } from 'vue'
import { isNumber } from 'is-what'
import { copy } from 'copy-anything'
import { dbCompanies, defaultsCompany } from './dbCompanies'
import CFormContractor from './CFormContractor.vue'
import CFormWrapper from '../../../CFormWrapper/CFormWrapper.vue'
import { openModalSpinner } from '../../../CModalConfirmation/helpers'
import { variableTitle } from './variableTitle'

const props = defineProps({
  docId: { type: String, default: undefined },
})

const emit = defineEmits({
  hide: () => true,
})
// もしくは
// const emit = defineEmits<{
//   (e: 'hide'): void
// }>()

const mode: 'edit' | 'add' = props.docId ? 'edit' : 'add'

const localData = ref(defaultsCompany())
const localId = props.docId || Math.random().toString()

if (mode === 'add') {
  localData.value.id = localId
  variableTitle.value = '新規作成'
}
if (mode === 'edit' && props.docId) {
  // fetch data from server
  variableTitle.value = '詳細編集'
  dbCompanies
    .doc(props.docId)
    .fetch()
    .then((company) => {
      if (company) localData.value = copy(company)
    })
}

const validation = {
  name: {
    error: (val: any) => {
      if (!val) return '会社名を記入してください'
      return null
    },
  },
  tel: {
    error: (val: any) => {
      if (!val) return '電話番号'
      return null
    },
  },
  addressNum: {
    error: (val: any) => {
      if (!val) return '郵便番号を記入してください'
      if (!isNumber(Number(val))) return '郵便番号は数字のみ'
      if (String(val).length > 7) return '郵便番号はなげーよ'
      return null
    },
  },
}

async function save() {
  // console.log(`こちらのデータを保存 → `, localData.value)
  const hideSpinner = openModalSpinner()
  await new Promise((resolve) => setTimeout(resolve, 1000))
  await dbCompanies.doc(localId).merge(localData.value)
  hideSpinner()
  emit('hide')
}
</script>

<template>
  <CFormWrapper
    v-slot="{ fieldProps, errorsPerField }"
    v-model="localData"
    :mode="mode"
    :validation="validation"
    @save="() => save()"
    @cancel="() => (mode === 'add' ? emit('hide') : undefined)"
    @close="() => emit('hide')"
  >
    <CFormContractor
      v-model="localData"
      :fieldProps="fieldProps"
      :errorsPerField="errorsPerField"
    />
  </CFormWrapper>
</template>
