<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>
import { machinesDeviceList } from "@/api/services/agriculturalMachines.js";
import storage from "@/utils/storage.js";

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

  methods: {
    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}`;
    },

    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) : '其他');
    },

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

    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';
    },

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

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

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

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

    onSearch() {
      this.pageNum = 1;
      this.machines = [];
      this.allLoaded = false;
      this.fetchMachines();
    },

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

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

      machinesDeviceList(params)
        .then(res => {
          if (res && res.data.code === 200 && res.data.rows) {
            const data = res.data.rows;
            if (this.pageNum === 1) {
              this.machines = data;
            } else {
              this.machines = this.machines.concat(data);
            }
            this.total = res.data.total
            if (this.machines.length >= this.total) {
              this.allLoaded = true;
            } else {
              this.allLoaded = 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(() => {
          this.loading = false;
          uni.hideLoading();
        });
    },

    loadMore() {
      if (this.loading || this.allLoaded) return;
      this.pageNum += 1;
      this.fetchMachines();
    },

    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);
        }
      });
    }
  },

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

  onPullDownRefresh() {
    this.pageNum = 1;
    this.machines = [];
    this.allLoaded = false;
    this.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>


