<template>
  <popup
    v-model="showDialog"
    class="max-w-[1200px] h-[80%] min-h-[320px]"
    body-class="flex-1 min-h-0"
    title="代码预览"
    :width="isMobile ? '96%' : '80%'"
    :show-footer="false"
    show-fullscreen
    :loading="isLoading"
  >
    <el-tabs class="preview-popup" v-model="activeTab">
      <el-tab-pane
        class="h-full flex flex-col"
        v-for="(item, index) in codeList"
        :key="index"
        :label="item.desc"
        :name="index"
      >
        <div class="preview-popup__header">
          <span class="text-base flex-1 break-all">{{ item.path }}{{ item.filename }}</span>
          <el-button type="primary" link @click="handleCopy(item.content)">复制</el-button>
        </div>
        <div class="preview-popup__content flex-1">
          <hljsVuePlugin.component :code="item.content" />
        </div>
      </el-tab-pane>
    </el-tabs>
  </popup>
</template>

<script setup lang="ts">
import { generatorPreview } from '@/api/tool/generator'
import useClipboard from 'vue-clipboard3'
import 'highlight.js/styles/atom-one-dark.css'
import 'highlight.js/lib/common'
import hljsVuePlugin from '@highlightjs/vue-plugin'
import { useConfigStore } from '@/stores/modules/config'

// 组件参数
const showDialog = ref(false)
const isLoading = ref(false)
const activeTab = ref(0)
const codeList = ref<any[]>([])
const { toClipboard } = useClipboard()
const configStore = useConfigStore()
const isMobile = computed(() => configStore.windowSizeLevel === 1)

// 打开弹窗
const open = async (id: number) => {
  showDialog.value = true
  try {
    isLoading.value = true
    const data = await generatorPreview({ id })
    isLoading.value = false
    codeList.value = data
    activeTab.value = 0
  } catch (e) {
    console.error(e)
    showDialog.value = false
  }
}

// 复制代码
const handleCopy = async (text: string) => {
  try {
    await toClipboard(text)
    ElMessage.success('复制成功')
  } catch (e) {
    ElMessage.error('复制失败')
  }
}

defineExpose({ open })
</script>

<style lang="scss" scoped>
.preview-popup {
  @apply h-full;

  &__header {
    @apply px-4 py-2 flex items-center min-w-0 gap-3;
    background: var(--el-fill-color);
    border-bottom: 1px solid var(--el-border-color);
    z-index: 10;
  }

  &__content {
    @apply overflow-auto flex-1;
    background: #282c34;

    pre,
    :deep(.hljs) {
      height: 100%;
    }
  }

  &__content,
  :deep(.hljs) {
    &::-webkit-scrollbar {
      width: 10px;
      height: 10px;
    }

    &::-webkit-scrollbar-track {
      background: #2d2d30;
      border-radius: 5px;
    }

    &::-webkit-scrollbar-thumb {
      background: #424242;
      border-radius: 5px;
      cursor: pointer;

      &:hover {
        background: #666;
      }
    }
  }
}
</style>
