<template>
  <div class="h-full overflow-hidden">
    <n-scrollbar>
      <n-card title="课程分类" :bordered="false" class="rounded-16px shadow-sm">
        <n-space class="pb-14px" justify="space-between">
          <!-- 加入查询组件 -->
          <n-space>
            <n-button type="primary" @click="addTableData">
              <icon-ic-round-plus class="mr-4px text-20px" />
              新增
            </n-button>
            <n-button type="error" @click="deleteTableData">
              <icon-ic-round-delete class="mr-4px text-20px" />
              删除
            </n-button>
            <!-- 添加查询按钮 -->
            <n-button type="primary">
              <icon-simple-line-icons:magnifier class="mr-4px text-16px" />
              查询
            </n-button>
            <div class="mr-5px"></div>
            <n-input-group>
              <n-input-number
                v-model:value="conditionParams.id"
                :style="{ width: '98%', marginRight: '2%' }"
                placeholder="请输入ID..."
                clearable
              />
              <n-input
                :style="{ width: '98%', marginRight: '2%' }"
                :value="conditionParams.name"
                placeholder="请输入学科名称..."
                clearable
                @input="event => (conditionParams.name = event)"
              />
              <n-input
                :style="{ width: '98%', marginRight: '2%' }"
                :value="conditionParams.description"
                placeholder="请输入学科描述..."
                clearable
                @input="event => (conditionParams.description = event)"
              />
              <n-input-number
                v-model:value="conditionParams.createUid"
                :style="{ width: '120%', marginRight: '2%' }"
                placeholder="请输入用户ID..."
                clearable
              />
              <n-input
                v-model:value="conditionParams.createTime"
                :style="{ width: '98%', marginRight: '2%' }"
                placeholder="请输入创建时间..."
                clearable
                @input="event => (conditionParams.createTime = event)"
              />
              <n-input
                v-model:value="conditionParams.modifyTime"
                :style="{ width: '98%', marginRight: '2%' }"
                placeholder="请输入修改时间..."
                clearable
                @input="event => (conditionParams.modifyTime = event)"
              />
              <n-select
                v-model:value="conditionParams.disabled"
                :options="userStatusOptions"
                :style="{ width: '98%', marginRight: '2%' }"
                placeholder="输入查询状态..."
                clearable
                @input="event => (conditionParams.disabled = event)"
              />
              <n-button type="primary" ghost @click="searchCondition()"> 搜索 </n-button>
            </n-input-group>
          </n-space>
          <n-space align="center" :size="18">
            <n-button size="small" type="primary" @click="searchCondition">
              <icon-mdi-refresh class="mr-4px text-16px" :class="{ 'animate-spin': loading }" />
              刷新表格
            </n-button>
          </n-space>
        </n-space>
        <n-data-table
          :columns="columns"
          :data="tableData"
          :loading="loading"
          :row-key="rowKey"
          @update:checked-row-keys="handleCheck"
        />
        <n-pagination
          v-model:page="pagination.page"
          v-model:page-size="pagination.pageSize"
          class="flex-justify-end"
          :item-count="pagination.itemCount"
          show-size-picker
          :page-sizes="[10, 20, 30, 40]"
          :on-update:page="(page: number)=>{pagination.page = page; searchCondition()}"
          :on-update:page-size="(pageSize: number)=>{pagination.pageSize = pageSize; searchCondition()}"
        />
        <table-action-add
          v-model:visible="visible"
          :type="modalType"
          :pagination="pagination"
          :edit-data="(editData as SelectByCondition_1Params)"
          @search-condition="searchCondition"
        />
      </n-card>
    </n-scrollbar>
  </div>
  <!-- <div>
			<PDFView :pdfUrl="tableData" />
		</div> -->
</template>

<script setup lang="tsx">
import type { Ref } from 'vue';
import { ref, reactive, watch } from 'vue';
import { NButton, NSpace, NTag, NPopconfirm } from 'naive-ui';
import type { DataTableColumns, PaginationProps, DataTableRowKey } from 'naive-ui';
import { userStatusOptions, userStatusLabels } from '@/constants';
import { useBoolean, useLoading } from '@/hooks';
import { deleteById, selectByCondition_1 } from '~/src/service/api/sort';
import type { SelectByCondition_1Params } from '~/src/service/api/sort';
import type { ModalType } from './components/table-action-add.vue';
import TableActionAdd from './components/table-action-add.vue';
// import PDFView from "../../.././components/View/pdfPreview.vue"
type RowData = {
  key: number;
  id: number;
  name: string;
  description: string;
  createTime: string;
  modifyTime: string;
  createUid: number;
  disabled: string;
};
const conditionParams: SelectByCondition_1Params = reactive({
  id: null,
  name: null,
  description: null,
  createUid: null,
  createTime: null,
  modifyTime: null,
  disabled: null
});

const { loading, startLoading, endLoading } = useLoading(false);
const { bool: visible, setTrue: openModal } = useBoolean();
const tableData = ref<SelectByCondition_1Params[]>([]);

const pagination: PaginationProps = ref({
  page: 1,
  pageSize: 10,
  showSizePicker: true,
  itemCount: 1
}).value;

async function searchCondition() {
  startLoading();
  const res = await selectByCondition_1(pagination.page as number, pagination.pageSize as number, conditionParams);
  tableData.value = res.data as [];
  if (pagination.itemCount === 1) {
    pagination.itemCount = Number(res.total);
  }
  endLoading();
}

function init() {
  searchCondition();
}
// 在条件改变时立即触发搜索
watch(conditionParams, () => {
  if (Object.values(conditionParams).every(value => value === '' || value === null)) {
    // 如果所有条件参数都为空，则查询所有数据
    searchCondition();
  }
  searchCondition();
});
// 初始化
init();

const checkedRowKeysRef = ref<DataTableRowKey[]>([]);
const s = ref<DataTableRowKey[]>([]);

const modalType = ref<ModalType>('add');

function setModalType(type: ModalType) {
  modalType.value = type;
}
// 添加
function addTableData() {
  openModal();
  setModalType('add');
}

const editData = ref<SelectByCondition_1Params | null>(null);
function setEditData(data: SelectByCondition_1Params | null) {
  editData.value = data;
}
function handleEditTable(rowId: number) {
  const findItem = tableData.value.find(item => item.id === rowId);
  setModalType('edit');
  openModal();
  if (findItem) {
    setEditData(findItem);
  }
}

function handleDeleteTable(rowId: number) {
  const rowIdNumber = Number(rowId);
  deleteById(rowIdNumber).then(() => {
    searchCondition(); // 删除完成后刷新表格数据
  });
}
const rowKey = (row: RowData) => row.id;
function handleCheck(rowKeys: DataTableRowKey[]) {
  checkedRowKeysRef.value = rowKeys;
}
async function deleteTableData() {
  const ids = checkedRowKeysRef.value.filter(item => !s.value?.includes(item));
  s.value = checkedRowKeysRef.value;
  if (ids.length !== 0) {
    for (const id of ids) {
      deleteById(id as number);
    }
    window.$message?.success('删除成功!');
    searchCondition(); // 删除完成后刷新表格数据
  } else {
    // 没有选择任何行时的操作
    window.$message?.error('未选择要删除的行');
  }
}

const columns: Ref<DataTableColumns<UserManagement.User>> = ref([
  {
    type: 'selection',
    align: 'center'
  },
  {
    key: 'id',
    title: 'ID',
    align: 'center'
  },
  {
    key: 'name',
    title: '学科名称',
    align: 'center'
  },
  {
    key: 'description',
    title: '学科描述',
    align: 'center'
  },
  {
    key: 'createTime',
    title: '创建时间',
    align: 'center'
  },
  {
    key: 'modifyTime',
    title: '修改时间',
    align: 'center'
  },
  {
    key: 'createUid',
    title: '创建用户ID',
    align: 'center'
  },
  {
    key: 'disabled',
    title: '状态',
    align: 'center',

    render: row => {
      if (row.disabled) {
        const tagTypes: Record<UserManagement.UserStatusKey, NaiveUI.ThemeColor> = {
          N: 'error',
          Y: 'success'
        };
        return <NTag type={tagTypes[row.disabled]}>{userStatusLabels[row.disabled]}</NTag>;
      }
      return '';
    }
  },
  {
    key: 'actions',
    title: '操作',
    align: 'center',
    render: row => {
      return (
        <NSpace justify={'center'}>
          <NButton size={'small'} onClick={() => handleEditTable(row.id)}>
            编辑
          </NButton>
          <NPopconfirm onPositiveClick={() => handleDeleteTable(row.id)}>
            {{
              default: () => '确认删除',
              trigger: () => <NButton size={'small'}>删除</NButton>
            }}
          </NPopconfirm>
          <NButton size={'small'} onClick={() => handleEditTable(row.id)}>
            查看
          </NButton>
        </NSpace>
      );
    }
  }
]);
</script>
