<template>
  <view class="device-list-container">
    <view class="search-bar">
      <input 
        type="text" 
        placeholder="请输入设备名称或编号" 
        v-model="searchKeyword"
        @input="handleSearch"
      />
      <button class="search-btn" @click="handleSearch">搜索</button>
    </view>
    
    <view class="filter-bar">
      <view class="segmented-control">
        <view 
          v-for="(option, index) in filterOptions" 
          :key="index"
          class="segment-item"
          :class="{ 'active': activeFilter === index }"
          @click="activeFilter = index; handleFilterChange(index)"
        >
          <text>{{ option }}</text>
        </view>
      </view>
    </view>
    
    <view class="device-list">
      <view 
        v-for="device in deviceList" 
        :key="device.id || device.deviceId || device.id_ || device.id"
        class="device-item"
        @click="viewDeviceDetail(getDeviceId(device))"
      >
        <view class="device-header">
          <view class="device-info">
            <text class="device-name">{{ device.name }}</text>
            <view class="device-id-and-status">
                  <text class="device-id">ID: {{ device.shortId }}</text>
                  <view class="device-status" :class="getDeviceStatusClass(getDeviceStatusValue(device))">
                    <text class="status-dot"></text>
                    <text>{{ getDeviceStatusText(getDeviceStatusValue(device)) }}</text>
                  </view>
                  <!-- 设备配置下拉选择 -->
                  <view class="config-container">
                    <button 
                      class="config-btn"
                      @click.stop="toggleConfigDropdown(getDeviceId(device))"
                    >
                      设备配置
                    </button>
                    
                    <!-- 配置下拉框 -->
                    <view v-if="showConfigDropdown === getDeviceId(device)" class="config-dropdown">
                      <view class="dropdown-header">
                        <text class="dropdown-title">选择配置</text>
                        <text class="dropdown-close" @click.stop="closeConfigDropdown">✕</text>
                      </view>
                      <view class="dropdown-content">
                        <view 
                          v-for="config in configList" 
                          :key="config.id" 
                          class="config-option"
                          @click.stop="selectConfig(getDeviceId(device), config.id, config.name)"
                        >
                          <text class="config-option-name">{{ config.name }}</text>
                          <text class="config-option-desc">{{ config.remark || '无描述' }}</text>
                        </view>
                        <view v-if="configList.length === 0" class="no-config">
                          <text>暂无配置，请先添加</text>
                        </view>
                      </view>
                    </view>
                  </view>
                </view>
          </view>
        </view>
        <view class="device-content">
          <view class="device-station">
            <text class="station-label">所属站点:</text>
            <text class="station-name">{{ device.stationName || '未分配站点' }}</text>
          </view>
          <view class="device-config-display">
            <text class="config-label">价格配置:</text>
            <text class="config-name-val">{{ device.deviceConfigName || '未绑定配置' }}</text>
          </view>
        </view>
        <view class="device-footer">
          <!-- 设备闲忙状态 -->
          <view class="device-busy-status" :class="getDeviceBusyStatusClass(device)">
            <text class="busy-status-text">{{ getDeviceBusyStatus(device) }}</text>
          </view>
          <button 
            v-if="getDeviceStatusValue(device) === 1 || getDeviceStatusValue(device) === '1' || getDeviceStatusValue(device) === 'ONLINE'" 
            class="stop-btn"
            @click.stop="handleStopDevice(device.shortId)"
          >
            停止设备
          </button>
        </view>
      </view>
    </view>
    
    <view class="load-more" v-if="deviceList.length > 0" @click="loadMore">
      <text v-if="loadMoreStatus === 'loading'">正在加载...</text>
      <text v-else-if="loadMoreStatus === 'noMore'">没有更多数据了</text>
      <text v-else>上拉加载更多</text>
    </view>
    
    <view class="empty-state" v-if="deviceList.length === 0 && !loading">
      <text class="empty-icon">📱</text>
      <text>暂无设备数据</text>
    </view>
    
    <view class="loading-state" v-if="loading && deviceList.length === 0">
      <text class="loading-text">加载中...</text>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { getDeviceList, stopDevice, getDeviceConfigList, batchModifyDeviceConfig } from '../../api/device.js'
import { formatTime, showToast, storage } from '../../utils/index.js'

const deviceList = ref([])
const loading = ref(true)
const page = ref(1)
const pageSize = ref(10)
const hasMore = ref(true)
const loadMoreStatus = ref('more')
const activeFilter = ref(0)
const searchKeyword = ref('')

// 设备配置相关
const configList = ref([])
const showConfigDropdown = ref(null)
const loadingConfig = ref(false)

const filterOptions = ['全部', '在线', '离线', '故障']
const loadMoreText = {
  contentdown: '上拉加载更多',
  contentrefresh: '正在加载...',
  contentnomore: '没有更多数据了'
}

onMounted(() => {
  loadDeviceList()
})

const loadDeviceList = async (isLoadMore = false) => {
  if (!isLoadMore) {
    page.value = 1
    deviceList.value = []
    loading.value = true
  }
  
  try {
    const params = {
      page: page.value,
      pageSize: pageSize.value,
      keyword: searchKeyword.value,
      status: activeFilter.value === 0 ? '' : getStatusValue(activeFilter.value)
    }
    
    const res = await getDeviceList(params)
    
    // 添加调试信息
    console.log('设备列表API返回数据:', res)
    
    if (res && res.code === 200) {
      const data = res.data
      
      // 检查数据结构
      console.log('设备列表API返回完整数据:', res)
      console.log('设备列表数据:', data)
      
      // 适配不同的数据结构
      const records = data.records || data.list || data
      const totalPages = data.pages || data.totalPages || 1
      
      // 查看每条设备记录的详细信息，特别是状态字段
      console.log('设备记录详细信息:', records)
      if (records.length > 0) {
        console.log('第一条设备记录:', records[0])
        console.log('设备状态字段名:', Object.keys(records[0]).filter(key => 
          ['status', 'state', 'stateCode', 'deviceStatus'].includes(key.toLowerCase())
        ))
      }
      
      if (isLoadMore) {
        deviceList.value = [...deviceList.value, ...records]
      } else {
        deviceList.value = records
      }
      
      hasMore.value = page.value < totalPages
      loadMoreStatus.value = hasMore.value ? 'more' : 'noMore'
      
      if (isLoadMore) {
        page.value++
      }
      
      console.log('处理后的设备列表:', deviceList.value)
    } else {
      console.error('设备列表API返回错误:', res)
    }
  } catch (error) {
    console.error('获取设备列表失败:', error)
    showToast('获取设备列表失败')
  } finally {
    loading.value = false
  }
}

const loadMore = () => {
  if (hasMore.value && !loading.value) {
    loadMoreStatus.value = 'loading'
    loadDeviceList(true)
  }
}

const handleSearch = () => {
  loadDeviceList()
}

const handleFilterChange = (index) => {
  activeFilter.value = index
  loadDeviceList()
}

const viewDeviceDetail = (deviceId) => {
  // 跳转到设备详情页面
  uni.navigateTo({
    url: `/pages/device/detail?id=${deviceId}`
  })
}

const handleStopDevice = async (shortId) => {
  try {
    await stopDevice(shortId)
    showToast('设备已停止', 'success')
    // 刷新设备列表
    loadDeviceList()
  } catch (error) {
    console.error('停止设备失败:', error)
    showToast('停止设备失败')
  }
}

// 加载设备配置列表
const loadConfigList = async () => {
  if (loadingConfig.value) return
  loadingConfig.value = true
  try {
    const res = await getDeviceConfigList({ page: 1, pageSize: 1000 })
    if (res && res.code === 200) {
      const data = res.data
      // 适配分页结构 list, records 或直接数组
      configList.value = data.list || data.records || (Array.isArray(data) ? data : [])
      console.log('加载真实配置列表成功:', configList.value)
    } else {
      showToast(res.message || '加载配置失败')
    }
  } catch (error) {
    console.error('加载设备配置列表失败:', error)
    showToast('无法连接服务器')
  } finally {
    loadingConfig.value = false
  }
}

// 切换配置下拉框
const toggleConfigDropdown = (deviceId) => {
  if (showConfigDropdown.value === deviceId) {
    closeConfigDropdown()
  } else {
    // 加载配置列表
    loadConfigList()
    showConfigDropdown.value = deviceId
  }
}

// 关闭配置下拉框
const closeConfigDropdown = () => {
  showConfigDropdown.value = null
}

// 选择配置
const selectConfig = async (deviceId, configId, configName) => {
  try {
    // 使用正确的批量修改接口进行配置绑定
    const res = await batchModifyDeviceConfig({
      deviceIds: [deviceId],
      deviceConfigId: configId
    })
    
    if (res && res.code === 200) {
      showToast(`成功绑定: ${configName}`, 'success')
      closeConfigDropdown()
      // 延迟刷新列表
      setTimeout(() => {
        loadDeviceList()
      }, 500)
    } else {
      showToast(res.message || '绑定失败')
    }
  } catch (error) {
    console.error('绑定设备配置失败:', error)
    showToast('网络连接失败')
  }
}

// 设备配置（保留旧方法，可能其他地方还在使用）
const handleDeviceConfig = (deviceId) => {
  uni.navigateTo({
    url: `/pages/setting/device-config?id=${deviceId}&type=device_binding`
  })
}

// 从设备对象中提取ID，处理不同的字段名
const getDeviceId = (device) => {
  if (!device) return null
  
  // 尝试不同的ID字段名
  const possibleFields = ['id', 'deviceId', 'device_id', 'id_']
  
  for (const field of possibleFields) {
    if (device[field] !== undefined && device[field] !== null) {
      console.log('使用设备ID字段:', field, '值:', device[field])
      return device[field]
    }
  }
  
  // 如果没有找到ID字段，尝试使用shortId
  if (device.shortId) {
    console.log('使用设备shortId作为ID:', device.shortId)
    return device.shortId
  }
  
  console.warn('设备对象没有ID字段:', device)
  return null
}

// 从设备对象中提取状态值，处理不同的字段名
const getDeviceStatusValue = (device) => {
  if (!device) return null
  
  // 尝试不同的状态字段名
  const possibleFields = ['status', 'state', 'stateCode', 'deviceStatus', 'device_state']
  
  for (const field of possibleFields) {
    if (device[field] !== undefined && device[field] !== null) {
      console.log('使用设备状态字段:', field, '值:', device[field], '类型:', typeof device[field])
      return device[field]
    }
  }
  
  return null
}

// 从字典获取设备状态文本
const getDeviceStatusText = (status) => {
  // 添加调试信息
  console.log('设备状态值:', status, '类型:', typeof status)
  
  // 如果状态为空，直接返回离线
  if (status === null || status === undefined || status === '') {
    return '离线'
  }
  
  try {
    const dicts = storage.get('dicts')
    if (!dicts || !dicts['WashDevice.status']) {
      console.warn('字典数据未加载或不存在 WashDevice.status')
      // 降级处理：使用默认映射
      const statusMap = {
        'init': '初始化',
        'idle': '设备空闲',
        'busy': '设备忙碌',
        'sleep': '不在营业时间',
        'maintenance': '维护模式',
        'fault': '设备故障',
        0: '离线', 1: '在线', 2: '故障', 3: '维护中',
        '0': '离线', '1': '在线', '2': '故障', '3': '维护中',
        'ONLINE': '在线', 'OFFLINE': '离线', 'FAULT': '故障', 'MAINTENANCE': '维护中'
      }
      return statusMap[status] || statusMap[String(status)] || String(status)
    }
    
    const deviceStatusDict = dicts['WashDevice.status']
    const dictItem = deviceStatusDict.find(item => item.value == status)
    
    return dictItem ? dictItem.name : String(status)
  } catch (error) {
    console.error('获取设备状态文本失败:', error)
    return String(status)
  }
}

// 获取设备闲忙状态
const getDeviceBusyStatus = (device) => {
  const status = getDeviceStatusValue(device)
  
  // 如果设备不在线，不显示闲忙状态
  if (status !== 1 && status !== '1' && status !== 'ONLINE') {
    return null
  }
  
  // 检查是否有当前订单或工作状态
  // 假设device对象有isBusy或currentOrder等字段表示闲忙状态
  // 如果没有这些字段，我们可以根据今日订单数来推测
  const hasCurrentOrder = device.isBusy || device.currentOrder || device.workingStatus === 'BUSY'
  
  // 如果没有明确的闲忙状态字段，我们可以假设如果今日有订单则可能忙碌
  // 这是一个降级处理方案
  const isLikelyBusy = hasCurrentOrder || (device.todayOrders > 0)
  
  return isLikelyBusy ? '忙碌' : '空闲'
}

// 获取设备闲忙状态样式类
const getDeviceBusyStatusClass = (device) => {
  const busyStatus = getDeviceBusyStatus(device)
  if (!busyStatus) return ''
  
  return busyStatus === '忙碌' ? 'busy-status' : 'idle-status'
}

const getDeviceStatusClass = (status) => {
  const statusClassMap = {
    // 新状态值映射
    'init': 'status-online',      // 初始化 - 在线样式
    'idle': 'status-online',      // 设备空闲 - 在线样式
    'busy': 'status-online',      // 设备忙碌 - 在线样式
    'sleep': 'status-offline',    // 不在营业时间 - 离线样式
    'maintenance': 'status-maintenance',  // 维护模式 - 维护样式
    'fault': 'status-fault',      // 设备故障 - 故障样式
    // 旧状态值映射（兼容）
    0: 'status-offline',
    1: 'status-online',
    2: 'status-fault',
    3: 'status-maintenance',
    '0': 'status-offline',
    '1': 'status-online',
    '2': 'status-fault',
    '3': 'status-maintenance',
    'ONLINE': 'status-online',
    'OFFLINE': 'status-offline',
    'FAULT': 'status-fault',
    'MAINTENANCE': 'status-maintenance'
  }
  
  // 尝试直接匹配或类型转换后匹配
  return statusClassMap[status] || statusClassMap[String(status)] || ''
}

const getStatusValue = (filterIndex) => {
  const statusMap = {
    1: 1, // 在线
    2: 0, // 离线
    3: 2  // 故障
  }
  return statusMap[filterIndex] || ''
}
</script>

<style scoped>
.device-list-container {
  padding: 20rpx;
  background-color: #F8F9FA;
  min-height: 100vh;
  box-sizing: border-box;
  padding-bottom: 100rpx;
}

.search-bar {
  display: flex;
  margin-bottom: 30rpx;
  background-color: #FFFFFF;
  border-radius: 24rpx;
  padding: 20rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.06);
}

.search-bar input {
  flex: 1;
  height: 70rpx;
  border: none;
  outline: none;
  font-size: 28rpx;
  color: #1A1A1A;
  padding: 0 24rpx;
  background-color: #F5F5F5;
  border-radius: 16rpx;
  margin-right: 20rpx;
}

.search-btn {
  padding: 20rpx 40rpx;
  background: linear-gradient(135deg, #667EEA 0%, #764BA2 100%);
  color: #FFFFFF;
  border: none;
  border-radius: 16rpx;
  font-size: 28rpx;
  font-weight: 500;
  transition: all 0.3s;
}

.search-btn:active {
  transform: scale(0.95);
  opacity: 0.9;
}

.filter-bar {
  background-color: #FFFFFF;
  padding: 20rpx;
  border-radius: 24rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.06);
  margin-bottom: 30rpx;
}

.segmented-control {
  display: flex;
  width: 100%;
  border-radius: 16rpx;
  overflow: hidden;
  background-color: #F5F5F5;
  padding: 6rpx;
  gap: 6rpx;
}

.segment-item {
  flex: 1;
  text-align: center;
  padding: 16rpx 0;
  font-size: 26rpx;
  color: #666666;
  position: relative;
  transition: all 0.3s;
  border-radius: 12rpx;
  font-weight: 500;
}

.segment-item.active {
  color: #FFFFFF;
  font-weight: 600;
  background: linear-gradient(135deg, #667EEA 0%, #764BA2 100%);
  box-shadow: 0 4rpx 12rpx rgba(102, 126, 234, 0.3);
}

.load-more {
  text-align: center;
  padding: 40rpx;
  color: #666666;
  font-size: 28rpx;
  background-color: #FFFFFF;
  margin-top: 30rpx;
  border-radius: 24rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.06);
  transition: all 0.3s;
}

.load-more:active {
  transform: translateY(-4rpx);
  box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.1);
}

.empty-icon {
  font-size: 120rpx;
  margin-bottom: 32rpx;
  opacity: 0.5;
}

.loading-state {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 120rpx 0;
  color: #999999;
}

.loading-text {
  font-size: 28rpx;
}

.device-list {
  display: flex;
  flex-direction: column;
  gap: 16rpx;
}

.device-item {
  background-color: #FFFFFF;
  border-radius: 20rpx;
  padding: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.04);
  transition: all 0.3s;
  height: 260rpx; /* 增加高度以容纳新字段 */
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.device-item:active {
  transform: translateY(-4rpx);
  box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.1);
}

.device-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16rpx;
  padding-bottom: 16rpx;
  border-bottom: 1rpx solid #F5F5F5;
}

.device-info {
  flex: 1;
}

.device-name {
  font-size: 28rpx;
  font-weight: 600;
  color: #1A1A1A;
  margin-bottom: 8rpx;
  display: block;
}

.device-id-and-status {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 12rpx;
}

.device-status {
  display: flex;
  align-items: center;
  font-size: 22rpx;
  font-weight: 600;
  padding: 6rpx 16rpx;
  border-radius: 24rpx;
  white-space: nowrap;
}

.device-id {
  font-size: 26rpx;
  color: #667EEA;
  font-weight: 700;
  white-space: nowrap;
  flex: 1;
  min-width: 180rpx;
  text-transform: uppercase;
  letter-spacing: 1rpx;
}

.status-dot {
  display: inline-block;
  width: 12rpx;
  height: 12rpx;
  border-radius: 50%;
  margin-right: 8rpx;
  background-color: currentColor;
}

.status-online {
  color: #52C41A;
  background: linear-gradient(135deg, #F6FFED 0%, #D9F7BE 100%);
}

.status-offline {
  color: #999999;
  background: linear-gradient(135deg, #F5F5F5 0%, #E0E0E0 100%);
}

.status-fault {
  color: #F5222D;
  background: linear-gradient(135deg, #FFF1F0 0%, #FFCCC7 100%);
}

.status-maintenance {
  color: #FAAD14;
  background: linear-gradient(135deg, #FFF7E6 0%, #FFE7BA 100%);
}

.device-content {
  margin-bottom: 8rpx;
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.device-station, .device-config-display {
  display: flex;
  align-items: center;
  font-size: 24rpx;
  margin-bottom: 6rpx;
}

.station-label, .config-label {
  color: #999999;
  margin-right: 8rpx;
  width: 110rpx;
}

.station-name, .config-name-val {
  color: #1A1A1A;
  font-weight: 500;
  flex: 1;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.device-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 12rpx;
  border-top: 1rpx solid #F5F5F5;
}

.device-busy-status {
  display: inline-flex;
  align-items: center;
  font-size: 22rpx;
  font-weight: 600;
  padding: 6rpx 16rpx;
  border-radius: 24rpx;
  margin-right: 12rpx;
}

.busy-status {
  color: #F5222D;
  background-color: #FFF1F0;
}

.idle-status {
  color: #52C41A;
  background-color: #F6FFED;
}

.device-metrics {
  display: flex;
  gap: 40rpx;
}

.metric-item {
  display: flex;
  align-items: center;
  font-size: 24rpx;
}

.metric-label {
  color: #999999;
  margin-right: 8rpx;
}

.metric-value {
  color: #1A1A1A;
  font-weight: 600;
  font-size: 28rpx;
}

.stop-btn {
  padding: 6rpx 20rpx;
  background: linear-gradient(135deg, #F5222D 0%, #FF4D4F 100%);
  color: #FFFFFF;
  border: none;
  border-radius: 12rpx;
  font-size: 22rpx;
  font-weight: 500;
  transition: all 0.3s;
  margin-left: 12rpx;
}

.stop-btn:active {
  transform: scale(0.95);
  opacity: 0.9;
}

/* 设备配置按钮 */
.config-btn {
  padding: 6rpx 20rpx;
  background: linear-gradient(135deg, #667EEA 0%, #764BA2 100%);
  color: #FFFFFF;
  border: none;
  border-radius: 12rpx;
  font-size: 22rpx;
  font-weight: 500;
  transition: all 0.3s;
  white-space: nowrap;
}

/* 停止设备按钮 */
.stop-btn {
  margin-left: 12rpx;
}

.config-btn:active {
  transform: scale(0.95);
  opacity: 0.9;
}

/* 配置容器 */
.config-container {
  position: relative;
}

/* 配置下拉框 */
.config-dropdown {
  position: absolute;
  top: 100%;
  right: 0;
  margin-top: 8rpx;
  width: 300rpx;
  background-color: #FFFFFF;
  border-radius: 12rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.15);
  z-index: 1000;
  overflow: hidden;
}

/* 下拉框头部 */
.dropdown-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16rpx 20rpx;
  background-color: #F8F9FA;
  border-bottom: 1rpx solid #E0E0E0;
}

.dropdown-title {
  font-size: 24rpx;
  font-weight: 600;
  color: #1A1A1A;
}

.dropdown-close {
  font-size: 24rpx;
  color: #999999;
  cursor: pointer;
  padding: 4rpx;
}

.dropdown-close:active {
  color: #666666;
}

/* 下拉框内容 */
.dropdown-content {
  max-height: 300rpx;
  overflow-y: auto;
}

/* 配置选项 */
.config-option {
  padding: 16rpx 20rpx;
  border-bottom: 1rpx solid #F0F0F0;
  transition: background-color 0.2s;
}

.config-option:last-child {
  border-bottom: none;
}

.config-option:active {
  background-color: #F5F5F5;
}

.config-option-name {
  font-size: 24rpx;
  font-weight: 500;
  color: #1A1A1A;
  display: block;
  margin-bottom: 4rpx;
}

.config-option-desc {
  font-size: 20rpx;
  color: #999999;
  display: block;
}

/* 无配置提示 */
.no-config {
  padding: 32rpx 20rpx;
  text-align: center;
  color: #999999;
  font-size: 22rpx;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 120rpx 0;
  color: #999999;
}

.empty-state text {
  margin-top: 32rpx;
  font-size: 28rpx;
  display: block;
}
</style>