<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <search-form
      v-show="showSearch"
      :query-params="queryParams"
      :types="knowledgeTypes"
      @query="handleQuery"
      @reset="resetQuery"
    />

    <!-- 操作按钮 -->
    <action-buttons
      :selected-rows="selectedRows"
      :columns="columns"
      v-model:show-search="showSearch"
      @add="handleAdd"
      @update="handleUpdate"
      @delete="handleDelete"
      @export="handleExport"
      @query="getList"
    />

    <!-- 数据表格 -->
    <know-table
      :list="knowledgeList"
      :loading="loading"
      :columns="columns"
      :types="knowledgeTypes"
      @selection-change="handleSelectionChange"
      @view="handleView"
      @update="handleUpdate"
      @delete="handleDelete"
    />

    <!-- 分页 -->
    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    <!-- 添加或修改果园对话框 -->
    <form-dialog
      ref="formDialogRef"
      v-model:open="open"
      :types="knowledgeTypes"
      :title="title"
      @success="getList"
    />
  </div>
</template>

<script setup name="Knowledge">
import { listKnowledge, delKnowledge } from '@/api/knowledge'
import { columnsConfig } from './config.js'
import Pagination from '@/components/Pagination'
import SearchForm from './components/SearchForm'
import ActionButtons from './components/ActionButtons'
import knowTable from './components/knowTable'
import FormDialog from './components/FormDialog'
import { useDict } from '@/utils/dict'

// 获取组件实例代理
const { proxy } = getCurrentInstance()
const columns = reactive(columnsConfig)
const formDialogRef = ref(null)

// 状态管理
const knowledgeList = ref([])
const open = ref(false)
const viewOpen = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const selectedRows = ref([])
const total = ref(0)
const title = ref('')
const dateRange = ref([])
const currentId = ref(null)

// 字典数据
const { knowledge_type: knowledgeTypes } = useDict('knowledge_type')

// 表单和查询参数
const data = reactive({
  queryParams: {
    title: null,
    type: null,
    pageNum: 1,
    pageSize: 10,
  }
})

const { queryParams } = toRefs(data)

// 生命周期
onMounted(() => {
  getList()
})

/** 查询果园设备列表 */
async function getList() {
  loading.value = true
  try {
    const res = await listKnowledge(queryParams.value)
    knowledgeList.value = res.rows || []
    total.value = res.total || 0
  } catch (error) {
    proxy.$modal.msgError('获取科普知识列表失败: ' + (error.message || '未知错误'))
    console.error('Failed to get knowledge list:', error)
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy?.$refs.queryRef?.resetFields()
  dateRange.value = []
  handleQuery()
}

/** 新增按钮操作 */
function handleAdd() {
  open.value = true
  title.value = '新增科普知识'// 默认状态为正常
  formDialogRef.value.resetForm()
}

/** 修改按钮操作 */
function handleUpdate(row) {
  open.value = true
  title.value = '修改科普知识的详细信息'
  // 如果传入了row，则编辑特定行，否则编辑选中的行
  const targetRow = row || (selectedRows.value.length ? selectedRows.value[0] : null)
  if (targetRow) {
    formDialogRef.value.setForm(targetRow)
  }
}

/** 查看按钮操作 */
function handleView(row) {
  viewOpen.value = true
  currentId.value = row.id
}

/** 删除按钮操作 */
async function handleDelete(row) {
  const ids = row ? [row.id] : selectedRows.value.map(item => item.id)
  const knowledgeNames = row ? [row.title] : selectedRows.value.map(item => item.title)

  try {
    await proxy.$confirm(`是否确认删除选中的${knowledgeNames.join(',')}科普知识数据?`)
    await delKnowledge(ids)
    proxy.$modal.msgSuccess('删除成功')
    getList()
    selectedRows.value = [] // 清空选中状态
  } catch (error) {
    // 取消操作不提示错误
    if (error !== 'cancel') {
      proxy.$modal.msgError('删除失败: ' + (error.message || '未知错误'))
    }
  }
}

/** 导出按钮操作 */
async function handleExport() {
  const fileName = await proxy.download('/business/device/export', queryParams.value, `虫情设备数据_${new Date().getTime()}.xlsx`)
  fileName && proxy.$download.name(fileName)
}

/** 选择框选中数据变化 */
function handleSelectionChange(selection) {
  selectedRows.value = selection
}
</script>

<style lang="scss" scoped>
.app-container {
  @apply p-5 bg-white min-h-[calc(100vh-120px)] rounded-lg shadow-sm;
}

.mb-3 {
  margin-bottom: 12px;
}

// 表格样式优化
:deep(.el-table) {
  @apply text-sm border border-gray-200 rounded-lg overflow-hidden;

  .el-table__header-wrapper {
    @apply bg-gray-50;
  }

  .el-table__body {
    @apply bg-white;
  }

  .el-table__row {
    @apply hover:bg-blue-50 transition-colors duration-150;
  }

  .el-table-column--selection {
    @apply w-12;
  }
}

// 对话框样式
:deep(.el-dialog) {
  @apply rounded-lg overflow-hidden shadow-lg;
}

:deep(.el-dialog__header) {
  @apply bg-gray-50 border-b border-gray-200;
}

.dialog-footer {
  @apply flex justify-center mt-4 space-x-3;
}
</style>