// pages/device/fence/fence.js
const API = require('../../../utils/api').API

Page({
  data: {
    list: [],
    total: 0,
    page: 1,
    limit: 10,
    totalPages: 0,
    loading: false,
    refreshing: false,
    searchValue: '',
    
    // 地图相关
    showMap: false,  // 是否显示地图视图
    selectedFence: null,  // 当前选中的围栏
    mapCenter: {
      latitude: 38.5248248,
      longitude: 106.2267664
    },
    mapMarkers: [],  // 地图标记点
    mapPolygons: [],  // 地图多边形
    mapScale: 12
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.loadData()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // 可选：每次显示页面时刷新数据
    // this.loadData()
  },

  /**
   * 加载数据
   */
  async loadData(isRefresh = false) {
    if (isRefresh) {
      this.setData({ refreshing: true })
    }

    this.setData({ loading: true })

    try {
      const params = {
        page: this.data.page,
        limit: this.data.limit,
        _t: Date.now(),
        refresh: isRefresh
      }

      // 如果有搜索条件，添加到参数中
      if (this.data.searchValue) {
        params.name = this.data.searchValue.trim() // 按围栏名称精确查询
        params.number = this.data.searchValue.trim() // 兼容参数
      }

      console.log('请求参数:', params)

      const res = await API.getFenceList(params)
      
      console.log('电子围栏数据:', res)

      // 根据实际返回的数据结构调整
      let list = res.data?.list || res.data || res.list || []
      const total = res.data?.total || res.total || list.length || 0
      
      // 数据预处理：确保所有字段都存在
      list = list.map(item => {
        return {
          ...item,
          // 确保必要字段存在
          id: item.id,
          name: item.name || '未命名围栏',
          type: item.type || '围栏',
          description: item.description || '',
          isActive: item.isActive !== undefined ? item.isActive : true,
          grazingStatus: item.grazingStatus || '未知',
          area: item.area || '0',
          center: item.center || { lng: '106.2267664', lat: '38.5248248' },
          coordinates: item.coordinates || [],
          insideCount: item.insideCount || 0,
          outsideCount: item.outsideCount || 0,
          createdAt: item.createdAt || item.created_at || '',
          updatedAt: item.updatedAt || item.updated_at || ''
        }
      })
      
      // 如果有搜索条件，进行前端精确过滤（确保精确匹配）
      if (this.data.searchValue && this.data.searchValue.trim()) {
        const searchKey = this.data.searchValue.trim()
        list = list.filter(item => {
          const name = String(item.name || '')
          // 精确匹配：完全相等
          return name === searchKey
        })
        
        console.log('精确查找结果:', list.length, '条')
        
        if (list.length === 0) {
          wx.showToast({
            title: '未找到匹配的围栏',
            icon: 'none',
            duration: 2000
          })
        }
      }
      
      const totalPages = Math.ceil((this.data.searchValue ? list.length : total) / this.data.limit)

      this.setData({
        list: list,
        total: total,
        totalPages: totalPages,
        loading: false,
        refreshing: false
      })

      // 停止下拉刷新
      if (isRefresh) {
        wx.stopPullDownRefresh()
      }

    } catch (error) {
      console.error('加载数据失败:', error)
      
      this.setData({
        loading: false,
        refreshing: false
      })

      wx.showToast({
        title: '加载失败',
        icon: 'none'
      })

      if (isRefresh) {
        wx.stopPullDownRefresh()
      }
    }
  },

  /**
   * 搜索输入
   */
  onSearchInput(e) {
    this.setData({
      searchValue: e.detail.value
    })
  },

  /**
   * 执行搜索
   */
  handleSearch() {
    this.setData({ page: 1 })
    this.loadData(true)
  },

  /**
   * 清空搜索
   */
  clearSearch() {
    this.setData({ 
      searchValue: '',
      page: 1
    })
    this.loadData(true)
  },

  /**
   * 切换页码
   */
  changePage(e) {
    const page = e.currentTarget.dataset.page
    if (page !== this.data.page && page >= 1 && page <= this.data.totalPages) {
      this.setData({ page })
      this.loadData()
    }
  },

  /**
   * 上一页
   */
  prevPage() {
    if (this.data.page > 1) {
      this.setData({ page: this.data.page - 1 })
      this.loadData()
    }
  },

  /**
   * 下一页
   */
  nextPage() {
    if (this.data.page < this.data.totalPages) {
      this.setData({ page: this.data.page + 1 })
      this.loadData()
    }
  },

  /**
   * 查看围栏详情（在地图上显示）
   */
  viewDetail(e) {
    const id = e.currentTarget.dataset.id
    const index = e.currentTarget.dataset.index
    console.log('查看围栏详情:', id)
    
    const fence = this.data.list[index]
    if (!fence) {
      wx.showToast({
        title: '围栏数据不存在',
        icon: 'none'
      })
      return
    }
    
    // 切换到地图视图并显示该围栏
    this.showFenceOnMap(fence)
  },

  /**
   * 切换视图：列表/地图
   */
  toggleView() {
    const showMap = !this.data.showMap
    this.setData({ showMap })
    
    // 如果切换到地图视图，加载所有围栏到地图
    if (showMap && this.data.list.length > 0) {
      this.loadAllFencesToMap()
    }
  },

  /**
   * 在地图上显示单个围栏
   */
  showFenceOnMap(fence) {
    if (!fence || !fence.coordinates || fence.coordinates.length === 0) {
      wx.showToast({
        title: '围栏坐标数据不完整',
        icon: 'none'
      })
      return
    }

    // 转换坐标格式
    const points = fence.coordinates.map(coord => ({
      latitude: parseFloat(coord.lat),
      longitude: parseFloat(coord.lng)
    }))

    // 创建多边形
    const polygon = {
      points: points,
      strokeWidth: 3,
      strokeColor: fence.isActive ? '#52c41a' : '#ff4d4f',
      fillColor: fence.isActive ? '#52c41a33' : '#ff4d4f33'
    }

    // 创建中心点标记
    const marker = {
      id: fence.id,
      latitude: parseFloat(fence.center.lat),
      longitude: parseFloat(fence.center.lng),
      title: fence.name,
      iconPath: '/images/marker.png',
      width: 30,
      height: 30,
      callout: {
        content: `${fence.name}\n${fence.type}\n${fence.grazingStatus}`,
        fontSize: 12,
        borderRadius: 5,
        padding: 8,
        display: 'ALWAYS'
      }
    }

    this.setData({
      showMap: true,
      selectedFence: fence,
      mapCenter: {
        latitude: parseFloat(fence.center.lat),
        longitude: parseFloat(fence.center.lng)
      },
      mapPolygons: [polygon],
      mapMarkers: [marker],
      mapScale: 14
    })
  },

  /**
   * 加载所有围栏到地图
   */
  loadAllFencesToMap() {
    const polygons = []
    const markers = []

    this.data.list.forEach(fence => {
      if (fence.coordinates && fence.coordinates.length > 0) {
        // 添加多边形
        const points = fence.coordinates.map(coord => ({
          latitude: parseFloat(coord.lat),
          longitude: parseFloat(coord.lng)
        }))

        polygons.push({
          points: points,
          strokeWidth: 2,
          strokeColor: fence.isActive ? '#52c41a' : '#ff4d4f',
          fillColor: fence.isActive ? '#52c41a22' : '#ff4d4f22'
        })

        // 添加中心点标记
        markers.push({
          id: fence.id,
          latitude: parseFloat(fence.center.lat),
          longitude: parseFloat(fence.center.lng),
          title: fence.name,
          iconPath: '/images/marker.png',
          width: 25,
          height: 25
        })
      }
    })

    // 计算所有围栏的中心点
    let centerLat = 38.5248248
    let centerLng = 106.2267664
    
    if (markers.length > 0) {
      centerLat = markers.reduce((sum, m) => sum + m.latitude, 0) / markers.length
      centerLng = markers.reduce((sum, m) => sum + m.longitude, 0) / markers.length
    }

    this.setData({
      mapPolygons: polygons,
      mapMarkers: markers,
      mapCenter: {
        latitude: centerLat,
        longitude: centerLng
      },
      mapScale: 10
    })
  },

  /**
   * 地图标记点击事件
   */
  onMarkerTap(e) {
    const markerId = e.detail.markerId || e.markerId
    console.log('点击标记:', markerId)
    
    const fence = this.data.list.find(f => f.id === markerId)
    if (fence) {
      this.setData({ selectedFence: fence })
      // 可以显示围栏详细信息
      wx.showModal({
        title: fence.name,
        content: `类型：${fence.type}\n状态：${fence.grazingStatus}\n面积：${fence.area}平方米\n内部数量：${fence.insideCount}\n外部数量：${fence.outsideCount}`,
        showCancel: false
      })
    }
  },

  /**
   * 地图区域变化事件
   */
  onRegionChange(e) {
    console.log('地图区域变化:', e)
  },

  /**
   * 下拉刷新
   */
  onPullDownRefresh() {
    this.setData({ page: 1 })
    this.loadData(true)
  },

  /**
   * 上拉加载更多
   */
  onReachBottom() {
    if (this.data.page < this.data.totalPages && !this.data.loading) {
      this.setData({ page: this.data.page + 1 })
      this.loadData()
    }
  }
})

