<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <pest-search-form
      v-show="showSearch"
      :query-params="queryParams"
      :device-types="deviceTypes"
      :status-options="statusOptions"
      @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"
    />

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

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

<script setup name="Device">
import { listDevice, delDevice } from '@/api/device'
import { columnsConfig } from './config.js'
import Pagination from '@/components/Pagination'
import PestSearchForm from './components/PestSearchForm'
import ActionButtons from './components/ActionButtons'
import DeviceTable from './components/PestTable'
import DeviceFormDialog from './components/PestFormDialog'
import DeviceViewDialog from './components/PestViewDialog'
import { useDict } from '@/utils/dict'

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

// 状态管理
const deviceList = 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 { monitor_device_type: deviceTypes } = useDict('monitor_device_type')
const { device_status: statusOptions } = useDict('device_status')

// 表单和查询参数
const data = reactive({
  form: {
    deviceNo: '',
    deviceAddr: '',
    model: '',
    installPointDes: '',
    imgUrl: '',
    type: null,
    status: '0',
    videoPlayUrl: ''
  },
  queryParams: {
    type: null,
    status: null,
    pageNum: 1,
    pageSize: 10,
  }
})

const { queryParams, form } = toRefs(data)

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

/** 查询果园设备列表 */
async function getList() {
  loading.value = true
  try {
    const res = await listDevice(queryParams.value)
    deviceList.value = res.rows || []
    total.value = res.total || 0
  } catch (error) {
    proxy.$modal.msgError('获取虫情设备数据失败: ' + (error.message || '未知错误'))
    console.error('Failed to get pest 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: '1' } // 默认状态为正常
}

/** 修改按钮操作 */
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
  currentId.value = row.id
}

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

  try {
    await proxy.$confirm(`是否确认删除选中的${deviceNames.join(', ')}虫情设备数据?`)
    await delDevice(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>