<template>
  <div>
    <BasicTable @register="registerTable" v-if="!isEdit">
      <template #toolbar>
        <a-button type="warning" @click="handleEditTable">新增</a-button>
        <!-- <a-button type="success" @click="handleGenTable">生成</a-button> -->
        <a-button type="danger" @click="handleDelete">删除</a-button>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key == 'action'">
          <TableAction
            :actions="[
              {
                tooltip: '预览',
                label: '预览',
                onClick: handlePreview.bind(null, record),
              },
              {
                tooltip: '编辑',
                label: '编辑',
                onClick: handleEditTable.bind(null, record),
              },
              {
                tooltip: '生成',
                label: '生成',
                onClick: handleGenTable.bind(null, record),
              },
              {
                icon: 'icon-delete|iconfont',
                tooltip: '删除',
                label: '删除',
                color: 'error',
                popConfirm: {
                  title: '是否确认删除',
                  placement: 'left',
                  confirm: handleDelete.bind(null, record),
                },
              },
            ]"
          />
        </template>
      </template>
    </BasicTable>
    <Steps v-else @closed="handleSuccess" ref="stepsRef" />
    <PreviewDrawer @register="registerDrawer" @success="handleSuccess" />
  </div>
</template>
<script lang="ts" setup>
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { columns, searchFormSchema } from './data';
  import { genBasicPage, genBasicDelete, genBasicExecGenZip } from '/@/api/infra/genApi';
  import { useDrawer } from '/@/components/Drawer';
  import PreviewDrawer from './previewDrawer.vue';
  import Steps from './step/index.vue';
  import { downloadByData } from '/@/utils/file/download';
  import { ref, nextTick } from 'vue';
  import { useMessage } from '/@/hooks/web/useMessage';

  const { createConfirm, createMessage } = useMessage();
  const [registerDrawer, { openDrawer }] = useDrawer();
  const [registerTable, { getSelectRowKeys, reload }] = useTable({
    title: '代码生成列表',
    api: genBasicPage,
    rowKey: 'id',
    rowSelection: { type: 'checkbox' },
    clickToRowSelect: false,
    columns,
    formConfig: {
      labelWidth: 120,
      schemas: searchFormSchema,
      autoSubmitOnEnter: true,
      baseColProps: { xs: 24, sm: 12, md: 12, lg: 8 },
      resetButtonOptions: {
        preIcon: 'ant-design:delete-outlined',
      },
      submitButtonOptions: {
        preIcon: 'ant-design:search-outlined',
      },
    },
    showIndexColumn: true,
    indexColumnProps: {
      fixed: 'left',
    },
    useSearchForm: true,
    showTableSetting: true,
    bordered: true,
    actionColumn: {
      width: 300,
      title: '操作',
      dataIndex: 'action',
    },
  });
  // 是否编辑
  const isEdit = ref(false);
  const stepsRef = ref();

  // 预览按钮事件
  function handlePreview(record: Recordable) {
    console.log(record);
    openDrawer(true, {
      record,
    });
  }
  // 编辑按钮事件
  function handleEditTable(record: Recordable) {
    console.log(record);
    isEdit.value = true;
    nextTick(() => {
      stepsRef.value.configSteps(record || {});
    });
  }
  // 删除按钮事件
  async function handleDelete(record: Recordable) {
    const isGen = getSelectRowKeys().length ? true : false;
    if (isGen) {
      createConfirm({
        content: '你确定要删除?',
        iconType: 'warning',
        onOk: async () => {
          const keys = getSelectRowKeys();
          await genBasicDelete(keys);
          createMessage.success('删除成功！');
          await reload();
        },
      });
    } else {
      await genBasicDelete([record.id]);
    }
    await reload();
  }

  // 生成按钮事件
  async function handleGenTable(record: Recordable) {
    const res = await genBasicExecGenZip({ id: record.id });
    if (res) {
      downloadByData(res, record?.functionName + '.' + record.generateType.toLowerCase());
    }

    // const isGen = getSelectRows().length ? true : false;
    // console.log(
    //   '🚀 ~ file: index.vue:123 ~ handleGenTable ~ getSelectRows().length ',
    //   getSelectRows().length,
    // );
    // let streamData = '';
    // let fileName = '';
    // if (isGen) {
    //   const tables = getSelectRows()
    //     .map(ele => {
    //       return ele.id;
    //     })
    //     .join(',');
    //   streamData = await genBasicExecGenZip(tables);
    //   fileName = tables;
    // } else {
    //   streamData = await genBasicExecGenZip(record.tableName);
    //   fileName = record.tableName;
    // }
    // console.log('🚀 ~ file: index.vue:139 ~ handleGenTable ~ streamData', streamData);
    // downloadByData(streamData, `${fileName}.zip`);
    // console.log(record);
    // let url = genBasicExecGenZip();
  }
  // 回调函数
  async function handleSuccess(record: Recordable) {
    console.log(record);
    isEdit.value = false;
    await reload();
  }
</script>
