import { FormInst, NForm } from 'naive-ui'
import { defineComponent, onMounted, reactive, ref, watch } from 'vue'
import { useRoute } from 'vue-router'
import styles from './index.module.less'
import { Searchs } from '@/utils/searchs'

export default defineComponent({
  name: 'save-form',
  props: {
    model: {
      type: Object,
      default: {}
    },
    saveKey: {
      type: String,
      default: ''
    }
  },
  emits: ['setModel', 'submit', 'reset'],
  setup(props, { slots, attrs, emit, expose }) {
    const forms = ref<FormInst | null>()
    const route = useRoute()
    const state = reactive({
      searchs: null as any,
      saveKey: props.saveKey,
      model: {} as any
    })

    const formInitValue = () => {
      const model = props.model
      const tmpModel = {} as any
      for (const key in model) {
        tmpModel[key] = null
      }
      return tmpModel
    }
    watch(
      () => props.saveKey,
      (key) => {
        state.saveKey = key
      }
    )
    watch(
      () => props.model,
      (model) => {
        state.model = model
      },
      { deep: true }
    )

    const setFormValue = () => {
      const searchs = new Searchs(state.saveKey || route.path)
      state.searchs = searchs
      const active = searchs.get(state.saveKey || route.path)

      for (const key in active.form) {
        if (active.form.hasOwnProperty(key)) {
          const item = active.form[key]
          state.model[key] = item
        }
      }

      emit('setModel', state.model as any)
      if (state.saveKey) {
        state.searchs.update(route.path, undefined, 'bind')
      }
    }
    onMounted(() => {
      setFormValue()
    })

    const submit = (evt: Event) => {
      if (evt) {
        evt.stopPropagation()
        evt.stopImmediatePropagation()
        evt.preventDefault()
      }

      if (state.saveKey) {
        state.searchs.update(route.path, undefined, 'bind')
      }
      state.searchs.update(state.model, undefined, 'form')
      emit('submit', evt)
    }

    const reset = (evt: any) => {
      if (evt) {
        evt.stopPropagation()
        evt.stopImmediatePropagation()
        evt.preventDefault()
      }

      let setItemEvent = new Event('watchStorage')
      window.dispatchEvent(setItemEvent)
      resetFields()
      emit('submit', evt)
    }

    // const save = (search = null as any, type = 'form' as 'form' | 'page') => {
    //   search = search ? search : state.model
    //   state.searchs.update(search, undefined, type)
    // }

    const resetFields = () => {
      // console.log(forms.value, 'resetFields', formInitValue())
      emit('setModel', formInitValue())
      // forms.value?.restoreValidation()
      state.searchs.update({}, undefined, 'form')
      state.searchs.update({}, undefined, 'page')
    }

    expose({
      submit,
      reset
    })
    return () => {
      return (
        <div class={['section-container section-save-form', styles.saveForm]}>
          <NForm
            model={state.model}
            ref={forms}
            inline
            label-placement="left"
            label-width="auto"
            {...attrs}
          >
            {slots.default && slots.default()}
          </NForm>
        </div>
      )
    }
  }
})
