<template>
  <div>
    <n-card :bordered="false" class="proCard">
      <div class="n-layout-page-header">
        <n-card :bordered="false" title="@{.tableComment}">
          <!--  这是系统自动生成的CURD表格，你可以将此行注释改为表格的描述 -->
        </n-card>
      </div>
@{ if eq .isSearchForm true }
      <BasicForm
        @register="register"
        @submit="reloadTable"
        @reset="reloadTable"
        @keyup.enter="reloadTable"
        ref="searchFormRef"
      >
        <template #statusSlot="{ model, field }">
          <n-input v-model:value="model[field]" />
        </template>
      </BasicForm>@{end}

      <BasicTable
        :openChecked="@{.options.Step.HasCheck}"
        :columns="columns"
        :request="loadDataTable"
        :row-key="(row) => row.id"
        ref="actionRef"
        :actionColumn="actionColumn"
        @update:checked-row-keys="onCheckedRow"
        :scroll-x="1090"
        :resizeHeightOffset="-10000"
        size="small"
      >
        <template #tableTitle>
@{ if eq .options.Step.HasAdd true }          <n-button
            type="primary"
            @click="addTable"
            class="min-left-space"
            v-if="hasPermission(['/@{.apiPrefix}/edit'])"
          >
            <template #icon>
              <n-icon>
                <PlusOutlined />
              </n-icon>
            </template>
            添加
          </n-button>@{end}
@{ if eq .options.Step.HasBatchDel true }          <n-button
            type="error"
            @click="handleBatchDelete"
            :disabled="batchDeleteDisabled"
            class="min-left-space"
            v-if="hasPermission(['/@{.apiPrefix}/delete'])"
          >
            <template #icon>
              <n-icon>
                <DeleteOutlined />
              </n-icon>
            </template>
            批量删除
          </n-button>@{end}
@{ if eq .options.Step.HasExport true }          <n-button
            type="primary"
            @click="handleExport"
            class="min-left-space"
            v-if="hasPermission(['/@{.apiPrefix}/delete'])"
          >
            <template #icon>
              <n-icon>
                <ExportOutlined />
              </n-icon>
            </template>
            导出
          </n-button>@{end}
        </template>
      </BasicTable>
    </n-card>
@{ if eq .options.Step.HasEdit true }    <Edit
      @reloadTable="reloadTable"
      @updateShowModal="updateShowModal"
      :showModal="showModal"
      :formParams="formParams"
    />@{end}
  </div>
</template>

<script lang="ts" setup>
  import { h, reactive, ref } from 'vue';
  import { useDialog, useMessage } from 'naive-ui';
  import { BasicTable, TableAction } from '@/components/Table';
  import { BasicForm, useForm } from '@/components/Form/index';
  import { usePermission } from '@/hooks/web/usePermission';
@{.apiImport}
  import { State, columns, schemas, options, newState } from './model';
@{.iconsImport}
@{ if or (eq .options.Step.HasView true) (eq .options.Step.HasEdit true) }  import { useRouter } from 'vue-router';@{end}
  import { getOptionLabel } from '@/utils/hotgo';
@{ if eq .options.Step.HasEdit true }  import Edit from './edit.vue';@{end}
  const { hasPermission } = usePermission();
@{ if or (eq .options.Step.HasView true) (eq .options.Step.HasEdit true) }  const router = useRouter();@{end}
  const actionRef = ref();
  const dialog = useDialog();
  const message = useMessage();
  const searchFormRef = ref<any>({});
  const batchDeleteDisabled = ref(true);
  const checkedIds = ref([]);
  const showModal = ref(false);
  const formParams = ref<State>();

  const actionColumn = reactive({
    width: 300,
    title: '操作',
    key: 'action',
    // fixed: 'right',
    render(record) {
      return h(TableAction as any, {
        style: 'button',
        actions: [
@{ if eq .options.Step.HasEdit true }          {
            label: '编辑',
            onClick: handleEdit.bind(null, record),
            auth: ['/@{.apiPrefix}/edit'],
          },@{end}
@{ if eq .options.Step.HasStatus true }          {
            label: '禁用',
            onClick: handleStatus.bind(null, record, 2),
            ifShow: () => {
              return record.status === 1;
            },
            auth: ['/@{.apiPrefix}/status'],
          },
          {
            label: '启用',
            onClick: handleStatus.bind(null, record, 1),
            ifShow: () => {
              return record.status === 2;
            },
            auth: ['/@{.apiPrefix}/status'],
          },@{end}
@{ if eq .options.Step.HasDel true }          {
            label: '删除',
            onClick: handleDelete.bind(null, record),
            auth: ['/@{.apiPrefix}/delete'],
          },@{end}
        ],
@{ if eq .options.Step.HasView true }        dropDownActions: [
          {
            label: '查看详情',
            key: 'view',
            auth: ['/@{.apiPrefix}/view'],
          },
        ],
        select: (key) => {
          if (key === 'view') {
            return handleView(record);
          }
        },@{end}
      });
    },
  });

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

  const loadDataTable = async (res) => {
    return await List({ ...searchFormRef.value?.formModel, ...res });
  };
@{ if eq .options.Step.HasAdd true }
  function addTable() {
    showModal.value = true;
    formParams.value = newState(null);
  }@{end}
@{ if or (eq .options.Step.HasAdd true) (eq .options.Step.HasEdit true) }
  function updateShowModal(value) {
    showModal.value = value;
  }@{end}

@{ if eq .options.Step.HasCheck true }  function onCheckedRow(rowKeys) {
    batchDeleteDisabled.value = rowKeys.length <= 0;
    checkedIds.value = rowKeys;
  }@{end}

  function reloadTable() {
    actionRef.value.reload();
  }
@{ if eq .options.Step.HasView true }
  function handleView(record: Recordable) {
    router.push({ name: '@{.varName | LcFirst}View', params: { id: record.@{.pk.TsName} } });
  }@{end}
@{ if eq .options.Step.HasEdit true }
  function handleEdit(record: Recordable) {
    showModal.value = true;
    formParams.value = newState(record as State);
  }@{end}

@{ if eq .options.Step.HasDel true }  function handleDelete(record: Recordable) {
    dialog.warning({
      title: '警告',
      content: '你确定要删除？',
      positiveText: '确定',
      negativeText: '取消',
      onPositiveClick: () => {
        Delete(record).then((_res) => {
          message.success('删除成功');
          reloadTable();
        });
      },
      onNegativeClick: () => {
        // message.error('取消');
      },
    });
  }@{end}

@{ if eq .options.Step.HasBatchDel true }  function handleBatchDelete() {
    dialog.warning({
      title: '警告',
      content: '你确定要批量删除？',
      positiveText: '确定',
      negativeText: '取消',
      onPositiveClick: () => {
        Delete({ id: checkedIds.value }).then((_res) => {
          message.success('删除成功');
          reloadTable();
        });
      },
      onNegativeClick: () => {
        // message.error('取消');
      },
    });
  }@{end}

@{ if eq .options.Step.HasExport true }  function handleExport() {
    message.loading('正在导出列表...', { duration: 1200 });
    Export(searchFormRef.value?.formModel);
  }@{end}

@{ if eq .options.Step.HasStatus true }  function handleStatus(record: Recordable, status: number) {
    Status({ @{.pk.TsName}: record.@{.pk.TsName}, status: status }).then((_res) => {
      message.success('设为' + getOptionLabel(options.value.sys_normal_disable, status) + '成功');
      setTimeout(() => {
        reloadTable();
      });
    });
  }@{end}
</script>

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