<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <search-form
      v-show="showSearch"
      :query-params="queryParams"
      v-model:dateRange="dateRange"
      @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"
    />

    <!-- 数据表格 -->
    <orchard-table
      :orchard-list="orchardList"
      :loading="loading"
      :columns="columns"
      @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" />
    <!-- 添加或修改果园对话框 -->
    <orchard-form-dialog
      v-model:open="open"
      :form="form"
      :title="title"
      @success="getList"
    />

    <!-- 查看果园对话框 -->
    <orchard-view-dialog
      v-model:open="viewOpen"
      :orchard-id="currentOrchardId"
    />
  </div>
</template>

<script setup name="Orchard">
import { ElMessage } from 'element-plus'
import { listOrchard, delOrchard } from '@/api/orchard'
import { columnsConfig } from './config.js'
import Pagination from '@/components/Pagination'
import SearchForm from './components/SearchForm'
import ActionButtons from './components/ActionButtons'
import OrchardTable from './components/OrchardTable'
import OrchardFormDialog from './components/OrchardFormDialog'
import OrchardViewDialog from './components/OrchardViewDialog'

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

// 状态管理
const orchardList = 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 currentOrchardId = ref(null)

// 表单和查询参数
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    orchardName: undefined,
    manager: undefined,
    status: undefined,
    beginTime: undefined,
    endTime: undefined
  }
})

const { queryParams, form } = toRefs(data)

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

/** 查询果园列表 */
async function getList() {
  loading.value = true
  try {
    // 处理日期范围
    if (dateRange.value && dateRange.value.length) {
      queryParams.value.beginTime = dateRange.value[0]
      queryParams.value.endTime = dateRange.value[1]
    } else {
      queryParams.value.beginTime = undefined
      queryParams.value.endTime = undefined
    }

    const res = await listOrchard(queryParams.value)
    orchardList.value = res.rows || []
    total.value = res.total || 0
  } catch (error) {
    ElMessage.error('获取果园数据失败: ' + (error.message || '未知错误'))
    console.error('Failed to get orchard 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 = '新增果园'
  form.value = { status: '0' } // 默认状态为正常
}

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

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

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

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

/** 导出按钮操作 */
function handleExport() {
  proxy.download('/business/orchard/export', queryParams.value, `果园数据_${new Date().getTime()}.xlsx`)
}

/** 选择框选中数据变化 */
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>