<template>
  <div class="dataset-page">
    <div class="dataset-page-search">
      <el-input
        v-model="keyword"
        placeholder="请输入关键词"
        style="width: 20%"
        :prefix-icon="Search"
        @input="searchPageData"
      />
      <div class="dataset-page-content-action">
        <el-space>
          <el-dropdown>
            <el-button>
              批量操作
              <el-icon class="el-icon--right">
                <arrow-down />
              </el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item :disabled="ids.length <= 0" @click="handleBatchDelete">
                  <el-icon>
                    <Delete />
                  </el-icon>
                  批量删除
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
          <el-button :icon="Plus" type="primary" @click="handleOpenForm">新建知识库</el-button>
        </el-space>
      </div>
    </div>
    <div class="dataset-page-table">
      <!--loading-->
      <div
        v-if="loading"
        v-loading="loading"
        class="loading-page"
        element-loading-text="正在加载..."
        style="width: 100%; height: calc(100vh - 250px)"
      ></div>
      <!--搜索结果-->
      <lz-page-empty v-else-if="!datasetData.length && !loading" type="5">
        <lz-svg-icon icon-class="empty2" style="font-size: 312px" />
      </lz-page-empty>
      <!-- table列表和分页-->
      <app-table
        v-else
        :data="datasetData"
        :pagination-config="paginationConfig"
        :tableDefaultHeight="210"
        class="mt-16"
        style="width: 100%"
        @changePage="getPageData"
        @sizeChange="handleSizeChange"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="知识库名称" min-width="220" prop="name">
          <template #default="{ row }">
            <span @click="handlePreview(row)">
              <AutoTooltip style="color: #3067ef; cursor: pointer">
                {{ row.name }}
              </AutoTooltip>
            </span>
          </template>
        </el-table-column>
        <el-table-column label="知识数" min-width="100" prop="create_id">
          <template #default="{ row }">
            <AutoTooltip>
              {{ row.knowledgeSum }}
            </AutoTooltip>
          </template>
        </el-table-column>
        <el-table-column label="更新时间" min-width="180" prop="modify_time">
          <template #default="{ row }">
            <AutoTooltip>
              {{ row.updatedTime }}
            </AutoTooltip>
          </template>
        </el-table-column>
        <el-table-column label="创建人" min-width="120" prop="modify_time">
          <template #default="{ row }">
            <AutoTooltip>
              {{ row.crateName }}
            </AutoTooltip>
          </template>
        </el-table-column>
        <el-table-column align="left" fixed="right" label="操作" width="220">
          <template #default="{ row }">
            <div>
              <span class="mr-10 primary-text" style="cursor: pointer" @click="handlePreview(row)">
                查看
              </span>
              <span class="mr-10 primary-text" style="cursor: pointer" @click="handleEdit(row)">
                编辑
              </span>
              <span class="mr-10 primary-text" style="cursor: pointer" @click="handleDelete(row)">
                删除
              </span>
            </div>
          </template>
        </el-table-column>
      </app-table>
    </div>
    <DatasetForm ref="datasetFormRef" @refresh="handlePreview" />
  </div>
</template>

<script lang="ts" setup>
import AppTable from '@/components/app-table/index.vue'
import AutoTooltip from '@/components/auto-tooltip/index.vue'
import router from '@/router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { debounce } from 'lodash-es'
import { onMounted, reactive, ref } from 'vue'
import { Plus, Search } from '@element-plus/icons-vue'
import DatasetForm from './components/DatasetForm.vue'
import api from '@/servers/finyx/api/index'

const go = (name: string, query?: any) => {
  router.push({ name, query })
}

const keyword = ref<string>('')

const loading = ref<boolean>(false)
const datasetData = ref<any>([])
const ids = ref<Array<string>>([])
const paginationConfig = reactive({
  current_page: 1,
  page_size: 10,
  total: 0
})

// 搜索按钮
const searchPageData = debounce(() => {
  handleSizeChange()
}, 300)

const getListParams = () => {
  const { current_page, page_size } = paginationConfig
  const model: any = {
    model: {
      name: keyword.value
    },
    size: page_size,
    current: current_page
  }
  return model
}

// 获取列表数据
async function getPageData() {
  try {
    loading.value = true
    const { records, total } = await api.zhishiku.page5(getListParams())
    datasetData.value = records
    paginationConfig.total = +total
  } catch (e: any) {
    ElMessage.error('获取知识库列表失败')
  } finally {
    loading.value = false
  }
}
// 初始化
onMounted(getPageData)
// 分页大小切换
const handleSizeChange = () => {
  paginationConfig.current_page = 1
  getPageData()
}
// 选择数据
const handleSelectionChange = (val: any) => {
  ids.value = val.map((v: any) => v.id)
}
// 查看
const handlePreview = (row: any) => {
  go('knowledgeDatasetView', { id: row.id, name: row.name })
}

const datasetFormRef = ref<any>(null)
// 新建
const handleOpenForm = () => {
  datasetFormRef.value.open()
}
// 编辑
const handleEdit = async (row: any) => {
  try {
    const data = await api.zhishiku.getDetail5({ id: row.id })
    datasetFormRef.value.open(data)
  } catch (e: any) {
    ElMessage.error('知识库获取失败')
  }
}
// 删除
const handleDelete = async (row: any) => {
  const confirm = await ElMessageBox.confirm('知识库删除后不可恢复，请谨慎操作', {
    title: '确认删除知识库',
    type: 'warning'
  })
  if (confirm) {
    try {
      loading.value = true
      await api.zhishiku.delete5([row.id])
      ElMessage.success('知识库删除成功')
      await getPageData()
    } catch (e: any) {
      ElMessage.success('知识库删除失败')
    } finally {
      loading.value = false
    }
  }
}
// 批量删除
const handleBatchDelete = async () => {
  const confirm = await ElMessageBox.confirm('知识库删除后不可恢复，请谨慎操作', {
    title: '确认删除知识库',
    type: 'warning'
  })
  if (confirm) {
    try {
      loading.value = true
      await api.zhishiku.delete5(ids.value)
      ElMessage.success('知识库删除成功')
      await getPageData()
    } catch (e: any) {
      ElMessage.success('知识库删除失败')
    } finally {
      loading.value = false
    }
  }
}
</script>

<style lang="scss" scoped>
.dataset-page {
  display: flex;
  height: 100%;
  flex-direction: column;

  &-search {
    width: 100%;
    display: flex;
    justify-content: space-between;

    &-action {
      width: 200px;
      margin-left: 10px;
    }
  }

  &-table {
    height: calc(100% - 32px);
    position: relative;
  }
}
</style>
