<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    :title="basicSetting.title"
    :width="basicSetting.width"
    :loading="loadingSpinning"
  >
    <a-tabs v-model:activeKey="codeTypeActiveKey" @change="codeTypeChange">
      <a-tab-pane
        v-for="codeType in codeTypeArray"
        :key="codeType.codeTypeKey"
        :tab="codeType.codeTypeTitle"
        force-render
      >
        <a-tabs v-model:activeKey="typeListActiveKey" tab-position="left" hide-add type="card">
          <a-tab-pane
            v-for="pan in codeType.codeTypeList"
            :key="pan.codeFileName"
            :tab="pan.codeFileName"
          >
            <div class="gen-preview-content">
              <Highlight :code="pan.codeFileContent" />
            </div>
          </a-tab-pane>
        </a-tabs>
      </a-tab-pane>
    </a-tabs>
  </BasicDrawer>
</template>

<script setup lang="ts">
  import { ref } from 'vue';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { Highlight } from '/@/components/CodeEditor/index';
  import { genBasicPreview } from '/@/api/infra/genApi';
  import { useMessage } from '/@/hooks/web/useMessage';

  const { createMessage } = useMessage();
  const basicSetting = {
    title: '预览',
    width: '60%',
  };
  const codeTypeActiveKey = ref();
  const typeListActiveKey = ref();
  const loadingSpinning = ref(true);
  const codeTypeArray = ref([]);
  const [registerDrawer, { changeLoading }] = useDrawerInner(async data => {
    try {
      const res = await genBasicPreview({ id: data.record.id });
      codeTypeArray.value = [
        {
          codeTypeKey: 'frontend',
          codeTypeTitle: '前端代码',
          codeTypeList: res.genBasicCodeFrontendResultList,
        },
        {
          codeTypeKey: 'backend',
          codeTypeTitle: '后端代码',
          codeTypeList: res.genBasicCodeBackendResultList,
        },
        {
          codeTypeKey: 'sqlend',
          codeTypeTitle: 'SQL文件',
          codeTypeList: res.genBasicCodeSqlResultList,
        },
      ];
    } catch (error) {
      createMessage.error('预览失败：请检查问题或反馈');
    } finally {
      loadingSpinning.value = false;
      changeLoading(loadingSpinning.value);
    }
  });
  // 切换标签
  const codeTypeChange = value => {
    typeListActiveKey.value = codeTypeArray.value.find(
      f => f.codeTypeKey === value,
    ).codeTypeList[0].codeFileName;
  };
</script>

<style lang="less" scoped>
  .gen-preview-content {
    height: calc(100vh - 160px);
    overflow: auto;
  }
</style>
