<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 + '|' + row.tableComment"
        ref="basicTableRef"
        :actionColumn="actionColumn"
        @update:checked-row-keys="onCheckedRow"
        :autoScrollX="true"
      >
        <template #tableTitle>
          <n-space>
            <n-button
              type="primary"
              @click="handleGenerator"
              :disabled="!rowKeys.length"
              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, SnippetsOutlined } 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: 100,
    title: '操作',
    align: 'center',
    key: 'action',
    fixed: 'right',
    render(record) {
      return h(TableAction as any, {
        style: 'button',
        actions: [
          {
            label: '一键生成',
            icon: renderIcon(SnippetsOutlined),
            type: 'info',
            onClick: handleGenerator.bind(null, record),
            auth: ['sys:generator:generator'],
          },
        ],
      });
    },
  });

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

  /**
   * 数据行选中事件
   * @param keys 参数
   */
  function onCheckedRow(keys) {
    rowKeys.value = keys;
  }

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

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

  /**
   * 执行重置
   * @param values 参数
   */
  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 + '|' + record.tableComment] })
          : await batchGenerator({
              tableNames: rowKeys.value,
            });
        message.success('生成成功');
        reloadTable();
      },
    });
  };
</script>

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