import CipBreadcrumb from '@cip/components/main/cip-main-breadcrumb'
import './index.less'
import { computed, ref } from 'vue'
import { useMain } from '@cip/hooks/use-main'
import { useCipConfig } from '@cip/components/hooks/use-cip-config'
import CipFormValidate from '@cip/components/cip-form-validate'
import { getUsingConfig } from '@cip/utils/util'
export default {
  name: 'CipPageLayoutHandle',
  props: {
    loading: Boolean,
    onConfirm: Function,
    onBack: Function,
    hideHeader: { type: Boolean, default: undefined },
    hideHandler: { type: Boolean, default: undefined }
  },
  setup (props, { slots }) {
    const { closeTab } = useMain()

    const formValidateRef = ref()
    const waiting = ref(false)

    const confirm = async (cb) => {
      if (typeof cb !== 'function') cb = props.onConfirm
      waiting.value = true
      try {
        await formValidateRef.value.validate()
        // 校验通过
        const res = await new Promise((resolve, reject) => {
          if (typeof cb === 'function') {
            cb(resolve, reject)
          } else {
            reject(new TypeError('onConfirm is not a function'))
          }
        })
        return res ?? true
      } finally {
        waiting.value = false
      }
    }

    const cipConfig = useCipConfig()
    const usingHideHeader = computed(() => {
      if (props.hideHeader !== undefined) {
        return props.hideHeader
      } else {
        return cipConfig.layout.hideHeader === true
      }
    })
    const usingHideHandler = computed(() => {
      if (props.hideHandler !== undefined) {
        return props.hideHandler
      } else {
        return cipConfig.layout.hideHandler === true
      }
    })

    const handleBackFn = computed(() => {
      return getUsingConfig(props.onBack, closeTab)
    })

    return () => <div class={'cip-page-layout-handle'} v-loading={props.loading}>
      {!usingHideHeader.value && <div class={'cip-page-layout-handle__breadcrumb'}>
        <CipBreadcrumb canBack={true} back={() => handleBackFn.value()} />
      </div>}
      <div class={'cip-page-layout-handle__main'}>
        <CipFormValidate ref={formValidateRef}>
          {slots.default?.()}
        </CipFormValidate>
      </div>
      <template>

      </template>
      { !usingHideHandler.value && <div class={'cip-page-layout-handle__handler'} >
        {(slots.handler || slots.handle)?.({ waiting: waiting.value, confirm })}
      </div>}
    </div>
  }
}
