<template>
  <Panel class="vtj-tabs" v-bind="$attrs">
    <template v-slot:title>
      <ElTabs
        type="card"
        v-model="currentTab"
        @tab-remove="handelTabRemove"
        :stretch="props.stretch">
        <ElTabPane
          v-for="item in props.items"
          :label="item.label"
          :name="item.name"
          :closable="item.closable"
          lazy></ElTabPane>
      </ElTabs>
    </template>
    <template v-slot:tools>
      <ElDropdown
        v-if="props.more"
        :hide-on-click="false"
        size="small"
        placement="bottom-end"
        @command="handleCommand">
        <i class="vtj-icon-more"></i>
        <template #dropdown>
          <ElDropdownMenu>
            <ElDropdownItem
              v-for="item in props.more"
              :key="item.name"
              :command="item">
              <span v-if="props.checkable" class="vtj-tabs__check">
                <i :class="`${item.checked ? 'vtj-icon-check' : 'none'}`"></i>
              </span>

              {{ item.label }}
            </ElDropdownItem>
          </ElDropdownMenu>
        </template>
      </ElDropdown>
    </template>
    <slot></slot>
  </Panel>
</template>
<script lang="ts" setup>
import { ref, watch } from 'vue';
import Panel, { Props as PanelProps } from './Panel.vue';
import {
  ElTabs,
  ElTabPane,
  ElDropdown,
  ElDropdownMenu,
  ElDropdownItem
} from 'element-plus';

export interface TabItem {
  name: string;
  label: string;
  closable?: boolean;
}

export interface MoreItem {
  label: string;
  name: string;
  checked?: boolean;
  closable?: boolean;
}

export interface Props extends PanelProps {
  items?: TabItem[];
  modelValue?: string;
  more?: MoreItem[];
  stretch?: boolean;
  checkable?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  items: () => []
});

const currentTab = ref<string>(
  (props.modelValue || props.items[0]?.name) ?? ''
);

const emit = defineEmits(['update:modelValue', 'more', 'tab-remove']);

watch(currentTab, () => {
  emit('update:modelValue', currentTab.value);
});

watch(
  () => props.modelValue,
  (name) => {
    currentTab.value = name as string;
  }
);

const handleCommand = (command: any) => {
  emit('more', command);
};
const handelTabRemove = (name: any) => {
  emit('tab-remove', name);
};
</script>
