<template>
  <view class="container">
    <!-- 顶部搜索与筛选 -->
    <view class="search-bar">
      <input v-model="filters.search" placeholder="搜索：名称 / 编号 / 所属农场" class="search-input" />
      <picker mode="selector" :range="machineTypeDisplayOptions" @change="onTypeChange" class="filter-picker">
        <view class="filter-label">类型：{{ selectedTypeLabel }}</view>
      </picker>
      <picker mode="selector" :range="onlineStatusDisplayOptions" @change="onStatusChange" class="filter-picker">
        <view class="filter-label">状态：{{ selectedStatusLabel }}</view>
      </picker>
      <button @click="onSearch" class="search-btn">搜索</button>
    </view>

    <!-- 列表 -->
    <scroll-view scroll-y class="list-wrapper" :style="{height: listHeight+'px'}">
      <view v-if="machines.length === 0 && !loading" class="empty-tip">暂无农机数据</view>

      <view v-for="machine in machines" :key="machine.id" class="machine-card" @click="navigateToDetail(machine)">
        <image :src="machine.imageUrl || '/static/icons/machine_default.png'" class="machine-image" mode="aspectFill" />

        <view class="machine-info">
          <view class="row">
            <text class="machine-name">{{ machine.machineName }}</text>
            <text class="machine-code">（{{ machine.machineCode }}）</text>
          </view>

          <view class="row meta-row">
            <text class="meta-item">类型：{{ getMachineTypeLabel(machine.machineType) }}</text>
            <text class="meta-item">农场：{{ machine.deptName || '-' }}</text>
            <text class="meta-item">地块：{{ machine.currentField || '-' }}</text>
          </view>

          <view class="row status-row">
            <view :class="['status-badge', onlineClass(machine.onlineStatus)]">{{ onlineStatusLabel(machine.onlineStatus) }}</view>
            <text class="meta-item">保养：{{ maintenanceLabel(machine.maintenanceStatus) }}</text>
            <text class="meta-item">定位：{{ locationLabel(machine.locationStatus) }}</text>
            <text class="alarm-count">告警：{{ machine.alarmCount || 0 }}</text>
          </view>

          <view class="row footer-row">
            <text class="manager">负责人：{{ machine.managerName || '-' }}</text>
            <text class="date">启用：{{ formatDate(machine.purchaseDate) }}</text>
          </view>
        </view>
      </view>

      <view v-if="loading" class="loading-tip">加载中...</view>

      <!-- 分页/加载更多 -->
      <button v-if="!allLoaded && !loading" @click="loadMore" class="load-more-btn">加载更多</button>
      <text v-if="allLoaded" class="end-tip">已加载全部</text>
    </scroll-view>
  </view>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { onLoad, onPullDownRefresh } from '@dcloudio/uni-app'
import { machinesDeviceList } from "@/api/services/agriculturalMachines.js"
import storage from "@/utils/storage.js"

// Reactive data
const machines = ref([])
const loading = ref(false)
const pageNum = ref(1)
const pageSize = ref(10)
const total = ref(0)
const allLoaded = ref(false)
const listHeight = ref(0)
const filters = reactive({
  search: '',
  machineType: '', // numeric or string code from backend
  onlineStatus: '' // filter by onlineStatus
})
const machineTypeDisplayOptions = ref(['全部','其他','拖拉机','收割机','播种机','喷雾机','农业智能体'])
const machineTypeCodeOptions = ref(['', '0','1','2','3','4','5'])
const onlineStatusDisplayOptions = ref(['全部','离线','在线','待命','作业中','维护中','故障'])
const onlineStatusCodeOptions = ref(['', '0','1','2','3','4','5'])
const selectedTypeLabel = ref('全部')
const selectedStatusLabel = ref('全部')

// Methods
const formatDate = (dateStr) => {
  if (!dateStr) return '-'
  const d = new Date(dateStr)
  if (isNaN(d.getTime())) return '-'
  const y = d.getFullYear()
  const m = (`0${d.getMonth() + 1}`).slice(-2)
  const day = (`0${d.getDate()}`).slice(-2)
  return `${y}-${m}-${day}`
}

const getMachineTypeLabel = (type) => {
  // backend uses numbers or strings; coerce to number if possible
  const map = {
    '0': '其他',
    '1': '拖拉机',
    '2': '收割机',
    '3': '播种机',
    '4': '喷雾机',
    '5': '农业智能体'
  }
  return map[String(type)] || (type ? String(type) : '其他')
}

const onlineStatusLabel = (code) => {
  const map = {
    '0': '离线',
    '1': '在线',
    '2': '待命',
    '3': '作业中',
    '4': '维护中',
    '5': '故障'
  }
  return map[String(code)] || '-'
}

const onlineClass = (code) => {
  const c = Number(code)
  if (c === 1) return 'status-online'
  if (c === 0) return 'status-offline'
  if (c === 5) return 'status-error'
  return 'status-idle'
}

const maintenanceLabel = (code) => {
  const map = { '1': '正常', '2': '需保养', '3': '待修复' }
  return map[code] || (code ? code : '-')
}

const locationLabel = (code) => {
  const map = { '1': '良好', '2': '异常', '3': '无信号' }
  return map[code] || (code ? code : '-')
}

const onTypeChange = (e) => {
  const idx = Number(e.detail.value)
  selectedTypeLabel.value = machineTypeDisplayOptions.value[idx]
  filters.machineType = machineTypeCodeOptions.value[idx] || ''
}

const onStatusChange = (e) => {
  const idx = Number(e.detail.value)
  selectedStatusLabel.value = onlineStatusDisplayOptions.value[idx]
  filters.onlineStatus = onlineStatusCodeOptions.value[idx] || ''
}

const onSearch = () => {
  pageNum.value = 1
  machines.value = []
  allLoaded.value = false
  fetchMachines()
}

const fetchMachines = () => {
  if (loading.value || allLoaded.value) return
  loading.value = true
  uni.showLoading({ title: '加载中...' })

  const params = {
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    machineName: filters.search || undefined,
    machineCode: filters.search || undefined,
    deptName: filters.search || undefined,
    machineType: filters.machineType || undefined,
    onlineStatus: filters.onlineStatus || undefined
  }

  machinesDeviceList(params)
    .then(res => {
      if (res && res.data.code === 200 && res.data.rows) {
        const data = res.data.rows
        if (pageNum.value === 1) {
          machines.value = data
        } else {
          machines.value = machines.value.concat(data)
        }
        total.value = res.data.total
        if (machines.value.length >= total.value) {
          allLoaded.value = true
        } else {
          allLoaded.value = false
        }
      } else {
        uni.showToast({ title: (res && res.data.rows && res.data.msg) || '获取数据失败', icon: 'none' })
      }
    })
    .catch(err => {
      console.error('fetchMachines error', err)
      uni.showToast({ title: '请求失败', icon: 'none' })
    })
    .finally(() => {
      loading.value = false
      uni.hideLoading()
    })
}

const loadMore = () => {
  if (loading.value || allLoaded.value) return
  pageNum.value += 1
  fetchMachines()
}

const navigateToDetail = (machine) => {
  // Placeholder navigation - create detail page separately if needed
  uni.navigateTo({
    url: '/pages/device/device-list/detail-machine?id=' + machine.id,
    success: (res) => {
      setTimeout(() => {
        uni.$emit('agriculturalMachinesData', {
          machineId: machine.id,
          machineCode: machine.machineCode,
          machineName: machine.machineName,
          onlineStatus: machine.onlineStatus,
          updateTime: machine.updateTime
        })
      }, 100)
    }
  })
}

// Lifecycle hooks
onLoad(() => {
  // compute list height to make scroll-view fill screen (simple heuristic)
  const systemInfo = uni.getSystemInfoSync()
  // subtract header/search height approx 160px
  listHeight.value = systemInfo.windowHeight - 160
  // initial load
  fetchMachines()
})

onPullDownRefresh(() => {
  pageNum.value = 1
  machines.value = []
  allLoaded.value = false
  fetchMachines()
  setTimeout(() => {
    uni.stopPullDownRefresh()
  }, 800)
})
</script>

<style scoped>
.container {
  padding: 24rpx;
  background-color: #F9FCFA;
  min-height: 100vh;
  box-sizing: border-box;
}
.search-bar {
  display: flex;
  align-items: center;
  gap: 12rpx;
  margin-bottom: 18rpx;
}
.search-input {
  flex: 1;
  height: 68rpx;
  border-radius: 12rpx;
  padding: 0 20rpx;
  background: #fff;
  border: 1rpx solid #EFEFEF;
}
.filter-picker {
  width: 180rpx;
  height: 68rpx;
  background: #fff;
  border-radius: 12rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1rpx solid #EFEFEF;
}
.filter-label {
  color: #666;
}
.search-btn {
  background: #3BB44A;
  color: #fff;
  padding: 14rpx 20rpx;
  border-radius: 12rpx;
}
.list-wrapper {
  width: 100%;
}
.machine-card {
  display: flex;
  background: #fff;
  border-radius: 20rpx;
  padding: 20rpx;
  margin-bottom: 18rpx;
  box-shadow: 0 8rpx 24rpx rgba(0,0,0,0.04);
  align-items: center;
}
.machine-image {
  width: 140rpx;
  height: 100rpx;
  border-radius: 12rpx;
  margin-right: 18rpx;
  background: #f6f6f6;
}
.machine-info {
  flex: 1;
}
.row {
  display: flex;
  align-items: center;
  margin-bottom: 8rpx;
}
.machine-name {
  font-size: 30rpx;
  font-weight: 600;
  color: #333;
  margin-right: 8rpx;
}
.machine-code {
  color: #999;
  font-size: 24rpx;
}
.meta-row .meta-item {
  margin-right: 18rpx;
  color: #666;
  font-size: 24rpx;
}
.status-row .status-badge {
  padding: 8rpx 12rpx;
  border-radius: 8rpx;
  color: #fff;
  font-size: 22rpx;
  margin-right: 12rpx;
}
.status-online { background: #4CAF50; }
.status-offline { background: #F56C6C; }
.status-error { background: #FF9800; }
.status-idle { background: #9E9E9E; }
.alarm-count {
  margin-left: 12rpx;
  color: #F56C6C;
  font-weight: 600;
}
.footer-row {
  justify-content: space-between;
  color: #999;
  font-size: 22rpx;
}
.loading-tip, .end-tip {
  text-align: center;
  color: #999;
  margin: 18rpx 0;
}
.empty-tip {
  text-align: center;
  color: #999;
  margin-top: 60rpx;
}
.load-more-btn {
  width: 80%;
  margin: 18rpx auto;
  background: #fff;
  border: 1rpx solid #EFEFEF;
  padding: 14rpx 0;
  border-radius: 12rpx;
}
</style>


