<template>
  <div class="cus-form">
    <el-form ref="ref_cusForm" :label-width="labelWidth" v-bind="$attrs">
      <el-row style="display:flex; flex-wrap: wrap">
        <slot/>
      </el-row>
    </el-form>
  </div>
</template>

<script lang="ts">
import {
  defineComponent,
  computed,
  onMounted,
  ref,
  reactive,
  watch,
  getCurrentInstance,
  ComponentInternalInstance,
  toRefs,
  nextTick,
  provide
} from 'vue'
import {useStore} from 'vuex'
import {useRouter, useRoute} from 'vue-router'

export default defineComponent({
  name: 'CusForm',
  components: {},
  props: {
    labelWidth: {default: '100px'},
    elementLoadingBackground: {},
    formView: {default: false}
  },
  setup(props, { emit }) {
    const store = useStore();
    const router = useRouter();
    const route = useRoute();
    const that = (getCurrentInstance() as ComponentInternalInstance).appContext.config.globalProperties
    const state = reactive({})
    const ref_cusForm: any = ref(null)
    provide('element-loading-background', props.elementLoadingBackground)
    let _formView: any = ref(props.formView)
    watch(() => props.formView, (n) => {
      _formView.value = n
    })
    provide('form-view', _formView)
    const submit = () => {
      return new Promise((resolve, reject) => {
        const nodes: any = [];
        const handleItem = (itemVue: any) => {
          const _itemValue = itemVue?.__vueParentComponent?.parent
          if (_itemValue?.type.name === "CusFormColumn") {
            const errorMessage = _itemValue.setupState.handleValidate()
            if (errorMessage) {
              nodes.push({
                node: _itemValue,
                message: errorMessage
              });
            }
          }
          if (itemVue.childNodes && itemVue.childNodes.length > 0) {
            itemVue.childNodes.forEach((v: any) => {
              handleItem(v);
            });
          }
        };
        handleItem(ref_cusForm?.value?.$el);
        if (nodes.length > 0) {
          reject(nodes);
        } else {
          resolve(null);
        }
      });
    }
    const handleEnter = () => {
      emit('handleEnter')
    }
    const reset = () => {
      const handleItem = (itemVue: any) => {
        const _itemValue = itemVue?.__vueParentComponent?.parent
        if (_itemValue?.type.name === "CusFormColumn") {
          _itemValue.setupState.reset()
        } else {
          if (itemVue.childNodes && itemVue.childNodes.length > 0) {
            itemVue.childNodes.forEach((v: any) => {
              handleItem(v);
            });
          }
        }
      };
      handleItem(ref_cusForm?.value?.$el);
    }
    return {
      ...toRefs(state),
      ref_cusForm,
      submit,
      handleEnter,
      reset
    }
  },
})
</script>

<style scoped lang="scss">
</style>
