<template>
  <PageWrapper>
    <el-card :bordered="false" class="pt-3 mb-3 proCard">
      <BasicForm @register="register" @submit="handleSubmit" @reset="handleReset" />
    </el-card>
    <el-card :bordered="false" class="proCard">
      <BasicTable
        :columns="columns"
        :request="loadDataTable"
        :row-key="(row) => row.id"
        ref="tableRef"
        :actionColumn="actionColumn"
        @selection-change="onSelectionChange"
      >
        <template #tableTitle>
          <el-button
            type="primary"
            @click="handleBatchGenerator()"
            :disabled="!selectionData.length"
            v-perm="['sys:generator:batchGenerator']"
          >
            <template #icon>
              <el-icon class="el-input__icon">
                <PlusOutlined />
              </el-icon>
            </template>
            批量生成
          </el-button>
        </template>
      </BasicTable>
    </el-card>

    <editDialog
      v-if="editVisible"
      :dataSourceId="dataSourceId"
      v-model:visible="editVisible"
      @success="reloadTable('noRefresh')"
    />
  </PageWrapper>
</template>

<script lang="ts" setup>
  import { reactive, ref, h, nextTick, defineAsyncComponent } from 'vue';
  import { ColProps } from 'element-plus';
  import { schemas } from './querySchemas';
  import { useForm } from '@/components/Form/index';
  import { TableAction } from '@/components/Table';
  import { getTableList, generator, batchGenerator } from '@/api/tool/generator';
  import { columns } from './columns';
  import { PlusOutlined } from '@vicons/antd';
  import { message, confirm } from '@/utils/auth';

  /**
   * 导入组件
   */
  const editDialog = defineAsyncComponent(() => import('./edit.vue'));

  /**
   * 定义参数变量
   */
  const dataSourceId = ref(0);
  const editVisible = ref(false);
  const selectionData = ref([]);
  const tableRef = ref();

  /**
   * 定义查询参数
   */
  const formParams = reactive({
    tableName: '',
    tableComment: '',
  });

  /**
   * 定义操作栏
   */
  const actionColumn = reactive({
    width: 150,
    label: '操作',
    prop: 'action',
    fixed: 'right',
    render(record) {
      return h(TableAction, {
        style: 'button',
        actions: [
          {
            label: '一键生成',
            icon: 'SwitchFilled',
            type: 'primary',
            onClick: handleGenerator.bind(null, record),
            auth: ['sys:generator:generator'],
          },
        ],
      });
    },
  });

  /**
   * 加载数据列表
   * @param res 参数
   */
  const loadDataTable = async (res: any) => {
    const result = await getTableList({ ...formParams, ...res });
    return result;
  };

  /**
   * 刷新数据列表
   * @param noRefresh 参数
   */
  function reloadTable(noRefresh = '') {
    tableRef.value.reload(noRefresh ? {} : { pageNo: 1 });
  }

  /**
   * 注册
   */
  const [register, {}] = useForm({
    labelWidth: 100,
    layout: 'horizontal',
    colProps: { span: 6 } as ColProps,
    submitOnReset: true,
    schemas,
  });

  /**
   * 执行提交表单
   * @param values 参数
   */
  function handleSubmit(values: Recordable) {
    handleReset();
    for (const key in values) {
      formParams[key] = values[key];
    }
    reloadTable();
  }

  /**
   * 执行重置
   */
  function handleReset() {
    for (const key in formParams) {
      formParams[key] = '';
    }
  }

  /**
   * 批量生成
   * @param record 数据记录
   */
  async function handleBatchGenerator(record: Recordable) {
    let names = [];
    if (!record) {
      names = selectionData.value.map(({ tableName }) => tableName);
    }
    await confirm('确定要批量一键生成吗？');
    record
      ? await batchGenerator({ tableNames: record.row.tableName })
      : await batchGenerator({ tableNames: names });
    message('批量生成成功');
    reloadTable();
  }

  /**
   * 一键生成
   * @param recored 数据记录
   */
  const handleGenerator = async (record: Recordable) => {
    await generator({ tableNames: [record.row.tableName] });
    message('一键生成成功');
  };

  /**
   * 选项发生变化
   */
  function onSelectionChange(value) {
    selectionData.value = value;
  }
</script>

<style lang="scss" scoped></style>
