import { defineComponent, ref, computed } from 'vue'
import { ElDialog, ElButton } from 'element-plus'
import CipFormValidate from '@cip/components/cip-form-validate'
import { componentScheme } from './component.scheme'
import { generateProps, generateEmits } from '../helper/component-util'
import { getUsingConfig } from '@cip/utils/util'
import './dialog.less'
const sizeConfig = {
  mini: '374px',
  small: '568px',
  default: '860px',
  large: '1144px'
}
export default defineComponent({
  name: 'CipDialog',
  props: generateProps(componentScheme),
  emits: generateEmits(componentScheme),
  setup (props, { slots, emit }) {
    const formValidateRef = ref()

    const waiting = ref(false)
    // 默认使用props.onConfirm当入参为函数时使用函数
    const confirm = async (cb) => {
      // 防止cb为e导致的错误
      if (typeof cb !== 'function') cb = props.onConfirm
      try {
        waiting.value = true
        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'))
          }
        })
        updateVisible(false)
        return res ?? true
      } finally {
        waiting.value = false
      }
    }
    const cancel = () => {
      updateVisible(false)
      emit('cancel')
    }
    const openHandler = () => {
      formValidateRef.value?.clear()
    }
    const closeHandler = () => {
      emit('close')
    }
    const updateVisible = (val) => {
      emit('update:modelValue', val)
    }
    const width = computed(() => {
      return getUsingConfig(props.width, sizeConfig[props.size], sizeConfig.default)
    })

    return () => (
      <ElDialog
        class={['cip-dialog__wrapper', { 'cip-dialog--show-only': props.showOnly }]}
        modelValue={props.modelValue}
        onUpdate:modelValue={updateVisible}
        title={props.title}
        width={width.value}
        closeOnClickModal={props.closeOnClickModal}
        top={props.top}
        destroyOnClose={props.destroyOnClose}
        appendToBody={true}
        onClose={() => closeHandler()}
        onOpen={() => openHandler()}
        fullscreen={props.fullscreen}
      >
        {{
          header: () => <>
            <div class="el-dialog__mainTitle">{ slots.mainTitle?.() || props.title }</div>
            <div class="el-dialog__subTitle">{slots.subTitle?.() || props.subTitle}</div>
          </>,
          default: () => <CipFormValidate ref={formValidateRef}>
            {slots.default?.()}
          </CipFormValidate>,
          footer: props.showOnly && !slots.footer
            ? undefined
            : () => {
                if (!props.showOnly) {
                  const defaultFooter = <div>
                {
                  !waiting.value && props.showCancel &&
                  <ElButton
                    onClick={() => cancel()}
                    size={props.buttonSize}>
                    {props.cancelText}
                  </ElButton>
                }
                <ElButton
                  onClick={() => confirm()}
                  size={props.buttonSize}
                  type={'primary'}
                  loading={waiting.value} >
                  {props.confirmText}
                </ElButton>
              </div>
                  const footerSlot = slots.footer?.({ confirm, loading: waiting.value, cancel })
                  return slots.footer ? footerSlot : defaultFooter
                } else {
                  return slots.footer?.()
                }
              }
        }}
      </ElDialog>
    )
  }
})
