<script setup lang="ts">
import { ref } from 'vue';

import { confirm, Page } from '@vben/common-ui';

import { Button, Card, Steps } from 'ant-design-vue';

import { useVbenForm } from '#/adapter/form';
import { downloadByData } from '#/util/tool';
import {
  codeGenerationDownloadApi,
  generationApi,
} from '#/views/code-generation/api';
import { codeGenerationForm } from '#/views/code-generation/config/form';

import CodeGenerationFiledTable from './components/fileds.vue';

const [Form, formApi] = useVbenForm(codeGenerationForm);

const formValue = ref();
const tableRef = ref();
const generation = () => {
  formApi.getValues().then((data) => {
    formValue.value = data;
    formValue.value.field = tableRef.value?.tableData;
    generationApi(formValue.value).then((res) => {
      confirm({
        cancelText: '迟点下载',
        confirmText: '是的，马上下载',
        content:
          '您的模块已经生成成功，是否立即下载？\r\n' +
          '后端代码已经自动生成：\r\n' +
          '（Controller、Service、Model、Route、Mysql数据表），无需您操作。\r\n' +
          '您只需要把代码黏贴至 ”您的根目录/apps/web-antd/src/views/my-gen“文件夹下即可使用',
        icon: 'success',
        title: '代码生成成功！',
      }).then(() => {
        codeGenerationDownloadApi(res.id).then((blob) => {
          downloadByData(blob, res.file_name, 'application/zip');
        });
        // 列表中下载代码方式
        // downloadInfoApi(1).then((result) => {
        //   codeGenerationDownloadApi(1).then((blob) => {
        //     downloadByData(blob, result.file_name, 'application/zip');
        //   });
        // });
      });
    });
  });
};

const stepsCurrent = ref(0);
const stepsItems = [
  {
    title: '基础信息',
    description: '类和菜单的基础信息',
  },
  {
    title: '字段信息',
    description: '设计数据库字段信息',
    subTitle: 'Left 00:00:08',
  },
  {
    title: '代码生成成功',
    description: '下载压缩包',
  },
];
</script>

<template>
  <Page title="代码生成器" auto-content-height>
    <Steps :current="stepsCurrent" :items="stepsItems" />
    <Card class="mt-6" :title="stepsItems[stepsCurrent]?.title">
      <Form v-show="stepsCurrent === 0" />
      <CodeGenerationFiledTable ref="tableRef" v-show="stepsCurrent === 1" />
    </Card>
    <template #extra>
      <div class="flex items-center justify-between gap-4">
        <Button
          v-if="stepsCurrent >= 0 && stepsCurrent < 1"
          @click="stepsCurrent++"
          type="primary"
        >
          下一步
        </Button>
        <Button v-if="stepsCurrent > 0" @click="stepsCurrent--" type="primary">
          上一步
        </Button>
        <Button v-if="stepsCurrent === 1" type="primary" @click="generation">
          <i class="fa-solid fa-code mr-2"></i>生成代码
        </Button>
      </div>
    </template>
  </Page>
</template>

<style scoped></style>
