<template>
  <div>
    <n-card :bordered="false" class="pt-3 mb-3 proCard">
      <BasicForm @register="register" @submit="handleSubmit" @reset="handleReset">
        <template #statusSlot="{ model, field }">
          <n-input v-model:value="model[field]" />
        </template>
      </BasicForm>
    </n-card>
    <n-card :bordered="false" class="proCard">
      <BasicTable
        :columns="columns"
        :request="loadDataTable"
        :row-key="(row) => row.tableName"
        ref="basicTableRef"
        :actionColumn="actionColumn"
        @update:checked-row-keys="onCheckedRow"
        :autoScrollX="true"
      >
        <template #tableTitle>
          <n-space>
            <n-button
              type="primary"
              @click="handleGenerator"
              v-perm="['sys:generator:batchGenerator']"
            >
              <template #icon>
                <n-icon>
                  <PlusOutlined />
                </n-icon>
              </template>
              批量生成
            </n-button>
          </n-space>
        </template>
      </BasicTable>
    </n-card>
  </div>
</template>

<script lang="ts" setup>
  import { h, reactive, ref } from 'vue';
  import { useMessage, useDialog } from 'naive-ui';
  import { TableAction } from '@/components/Table';
  import { BasicForm, useForm } from '@/components/Form/index';
  import { getTableList, generator, batchGenerator } from '@/api/tool/generator';
  import { columns } from './columns';
  import { schemas } from './querySchemas';
  import { PlusOutlined } from '@vicons/antd';
  import { renderIcon } from '@/utils';

  const message = useMessage();
  const dialog = useDialog();
  const basicTableRef = ref();

  const rowKeys = ref([]);

  const formParams = reactive({
    tableName: '',
    tableComment: '',
  });

  const actionColumn = reactive({
    width: 200,
    title: '操作',
    align: 'center',
    key: 'action',
    fixed: 'right',
    render(record) {
      return h(TableAction as any, {
        style: 'button',
        actions: [
          {
            label: '生成',
            icon: renderIcon(PlusOutlined),
            type: 'info',
            onClick: handleGenerator.bind(null, record),
            auth: ['sys:generator:generator'],
          },
        ],
      });
    },
  });

  const loadDataTable = async (res) => {
    rowKeys.value = [];
    const result = await getTableList({ ...formParams, ...res });
    return result;
  };

  function onCheckedRow(keys) {
    rowKeys.value = keys;
  }

  function reloadTable(noRefresh = '') {
    basicTableRef.value.reload(noRefresh ? {} : { pageNo: 1 });
  }

  function handleSubmit(values: Recordable) {
    for (const key in formParams) {
      formParams[key] = '';
    }
    for (const key in values) {
      formParams[key] = values[key];
    }
    reloadTable();
  }

  function handleReset(values: Recordable) {
    for (const key in formParams) {
      formParams[key] = '';
    }
    for (const key in values) {
      formParams[key] = values[key];
    }
    reloadTable();
  }

  const [register, {}] = useForm({
    gridProps: { cols: '1 s:1 m:2 l:3 xl:4 2xl:4' },
    labelWidth: 100,
    schemas,
  });

  /**
   * 执行生成
   */
  const handleGenerator = async (record) => {
    console.log(record);
    dialog.warning({
      title: '提示',
      content: '确定要生成？',
      positiveText: '确定',
      negativeText: '取消',
      onPositiveClick: async () => {
        record.tableName
          ? await generator({ tableNames: [record.tableName] })
          : await batchGenerator({ tableNames: rowKeys.value });
        message.success('生成成功');
        reloadTable();
      },
    });
  };
</script>

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