import { Dialog } from 'vant'
import { defineComponent, PropType, reactive, watch } from 'vue'
import styles from './index.module.less'

export default defineComponent({
  name: 'o-dialog',
  props: {
    show: {
      type: Boolean,
      default: false
    },
    message: {
      type: String,
      default: ''
    },
    title: {
      type: String,
      default: ''
    },
    confirmButtonText: {
      type: String,
      default: '确认'
    },
    allowHtml: {
      type: Boolean,
      default: false
    },
    cancelButtonText: {
      type: String,
      default: '取消'
    },
    showConfirmButton: {
      type: Boolean,
      default: true
    },
    showCancelButton: {
      type: Boolean,
      default: false
    },
    messageAlign: {
      type: String as PropType<'left' | 'center' | 'right'>,
      default: 'center'
    },
    dialogMarginTop: {
      type: String,
      default: '0px'
    }
  },
  emits: ['cancel', 'confirm', 'update:show'],
  setup(props, { emit, slots }) {
    const state = reactive({
      show: props.show || false
    })

    // 监听状态
    watch(
      () => props.show,
      () => {
        state.show = props.show
      }
    )
    return () => (
      <Dialog
        class={styles.oDialog}
        style={{
          marginTop: props.dialogMarginTop
        }}
        v-model:show={state.show}
        message={props.message}
        allowHtml={props.allowHtml}
        messageAlign={props.messageAlign}
        confirmButtonText={props.confirmButtonText}
        cancelButtonText={props.cancelButtonText}
        showConfirmButton={props.showConfirmButton}
        showCancelButton={props.showCancelButton}
        onConfirm={() => {
          emit('update:show', false)
          emit('confirm')
        }}
        onCancel={() => {
          emit('update:show', false)
          emit('cancel')
        }}
      >
        {{
          title: () =>
            props.title && (
              <div class={styles.dialogTitle}>
                <i></i>
                {props.title}
              </div>
            )
        }}
      </Dialog>
    )
  }
})
