<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.id"
        ref="basicTableRef"
        :actionColumn="actionColumn"
        @update:checked-row-keys="onCheckedRow"
        :autoScrollX="true"
      >
        <template #tableTitle>
          <n-space>
            <n-button type="primary" @click="handleAdd" v-perm="['sys:position:add']">
              <template #icon>
                <n-icon>
                  <PlusOutlined />
                </n-icon>
              </template>
              新建
            </n-button>

            <n-button
              type="error"
              @click="handleDelete"
              :disabled="!rowKeys.length"
              v-perm="['sys:param:batchDelete']"
            >
              <template #icon>
                <n-icon>
                  <DeleteOutlined />
                </n-icon>
              </template>
              删除
            </n-button>
          </n-space>
        </template>
      </BasicTable>
    </n-card>
    <editDialog
      ref="createModalRef"
      :paramId="paramId"
      v-if="editVisible"
      v-model:visible="editVisible"
      @success="reloadTable('noRefresh')"
    />
  </div>
</template>

<script lang="ts" setup>
  import { h, nextTick, reactive, ref, unref } from 'vue';
  import { useMessage, useDialog } from 'naive-ui';
  import { TableAction } from '@/components/Table';
  import { BasicForm, useForm } from '@/components/Form/index';
  import { getParamList, paramDelete, paramBatchDelete } from '@/api/data/param';
  import { columns } from './columns';
  import { PlusOutlined, DeleteOutlined, FormOutlined } from '@vicons/antd';
  import CreateModal from './CreateModal.vue';
  import editDialog from './edit.vue';
  import { basicModal, useModal } from '@/components/Modal';
  import { schemas } from './querySchemas';
  import { renderIcon } from '@/utils';

  const message = useMessage();
  const dialog = useDialog();
  const basicTableRef = ref();
  const createModalRef = ref();
  const editVisible = ref(false);
  const paramId = ref(0);
  const rowKeys = ref([]);
  const exportLoading = ref(false);

  const showModal = ref(false);
  const formParams = reactive({
    name: '',
    type: '',
    status: '',
  });

  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(FormOutlined),
            type: 'info',
            onClick: handleEdit.bind(null, record),
            auth: ['sys:param:update'],
          },
          {
            label: '删除',
            icon: renderIcon(DeleteOutlined),
            type: 'error',
            onClick: handleDelete.bind(null, record),
            auth: ['sys:param:delete'],
          },
        ],
      });
    },
  });

  function addTable() {
    showModal.value = true;
  }

  const loadDataTable = async (res) => {
    rowKeys.value = [];
    const result = await getParamList({ ...formParams, ...res });
    console.log(result);
    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: 80,
    schemas,
  });

  /**
   * 执行添加
   */
  const handleAdd = async () => {
    paramId.value = 0;
    editVisible.value = true;
    await nextTick();
    createModalRef.value.openModal();
  };
  /**
   * 执行编辑
   */
  async function handleEdit(record: Recordable) {
    paramId.value = record.id;
    editVisible.value = true;
    await nextTick();
    createModalRef.value.openModal();
  }
  /**
   * 执行删除
   * @param id 参数
   */
  async function handleDelete(record) {
    dialog.warning({
      title: '提示',
      content: '确定要删除？',
      positiveText: '确定',
      negativeText: '取消',
      onPositiveClick: async () => {
        record.id ? await paramDelete(record.id) : await paramBatchDelete(rowKeys.value);
        message.success('删除成功');
        reloadTable();
      },
    });
  }
</script>

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