<template>
  <teleport v-if="props.modelValue" to="body">
    <div class="vtj-dialog__modal"></div>
    <Panel
      class="vtj-dialog"
      v-bind="$attrs"
      :tools="tools"
      :style="styles"
      draggable
      @tool-click="handleToolClick">
      <slot></slot>
      <template v-if="$slots.footer || cancel || submit" #footer>
        <slot name="footer">
          <ElButton v-if="cancel" @click="handleCancel" size="default"
            >取消</ElButton
          >
          <ElButton
            v-if="submit"
            type="primary"
            @click="handleSubmit"
            size="default">
            确定
          </ElButton>
        </slot>
      </template>
    </Panel>
  </teleport>
</template>
<script lang="ts" setup>
import { computed, useAttrs } from 'vue';
import Panel, { Props as PanelProps, ToolItem } from './Panel.vue';
import { ElButton } from 'element-plus';

export interface Props extends PanelProps {
  modelValue?: boolean;
  modal?: boolean;
  width?: string;
  height?: string;
  top?: string;
  cancel?: boolean;
  submit?: boolean;
  closable?: boolean;
}

const attrs = useAttrs();

const props = withDefaults(defineProps<Props>(), {
  modelValue: true,
  modal: true,
  width: '80%',
  heiht: 'auto',
  top: '40%',
  cancel: false,
  submit: false,
  closable: true
});

const styles = computed(() => {
  return {
    width: props.width,
    height: props.height,
    top: props.top
  };
});

const tools = computed(() => {
  const toolBtns = [...((attrs.tools || []) as ToolItem[])];
  if (props.closable) {
    toolBtns.push({ name: 'close', icon: 'vtj-icon-close' });
  }
  return toolBtns;
});

const emit = defineEmits(['close', 'update:modelValue', 'submit']);

const handleToolClick = (item: ToolItem) => {
  if (item.name === 'close') {
    emit('update:modelValue', false);
    emit('close');
  }
};

function handleCancel() {
  emit('update:modelValue', false);
  emit('close');
}

function handleSubmit() {
  emit('submit');
}
</script>
