<template>
  <view class="device-binding-container">
    <view class="header-nav">
      <AppIcon name="chevron-left" size="20" color="#FFFFFF" />
      <text class="nav-title">设备绑定管理</text>
    </view>

    <view class="tabs">
      <view class="tab" :class="{ active: activeTab === 0 }" @click="activeTab = 0">设备参数绑定</view>
      <view class="tab" :class="{ active: activeTab === 1 }" @click="activeTab = 1">站点费率绑定</view>
    </view>

    <scroll-view class="content-scroll" scroll-y>
      <!-- 设备参数绑定 -->
      <view v-if="activeTab === 0" class="binding-section">
        <view class="card">
          <view class="card-header">1. 选择设备 (可多选)</view>
          <view class="station-filter">
            <picker @change="onStationChange" :value="stationIndex" :range="stationList" range-key="stationName">
              <view class="picker-item">
                {{ stationIndex === -1 ? '全部站点' : stationList[stationIndex].stationName }}
              </view>
            </picker>
          </view>
          <view class="device-list">
            <view v-for="device in filteredDevices" :key="device.id" class="device-item" @click="toggleDeviceSelection(device.id)">
              <checkbox :checked="selectedDeviceIds.includes(device.id)" />
              <text class="device-name">{{ device.deviceName }} ({{ device.id }})</text>
            </view>
            <view v-if="filteredDevices.length === 0" class="empty-tip">暂无可选设备</view>
          </view>
        </view>

        <view class="card">
          <view class="card-header">2. 选择参数模板</view>
          <picker @change="onConfigTemplateChange" :value="configIndex" :range="configTemplates" range-key="name">
            <view class="picker-item">
              {{ configIndex === -1 ? '点击选择模板' : configTemplates[configIndex].name }}
            </view>
          </picker>
        </view>

        <button class="action-btn" @click="handleBatchBindConfig" :disabled="selectedDeviceIds.length === 0 || configIndex === -1">
          执行批量绑定
        </button>
      </view>

      <!-- 站点费率绑定 -->
      <view v-if="activeTab === 1" class="binding-section">
        <view class="card">
          <view class="card-header">1. 选择站点</view>
          <picker @change="onStationSelectForFee" :value="stationIndexForFee" :range="stationList" range-key="stationName">
            <view class="picker-item">
              {{ stationIndexForFee === -1 ? '点击选择站点' : stationList[stationIndexForFee].stationName }}
            </view>
          </picker>
        </view>

        <view class="card">
          <view class="card-header">2. 选择费率模板</view>
          <picker @change="onFeeTemplateChange" :value="feeIndex" :range="feeTemplates" range-key="name">
            <view class="picker-item">
              {{ feeIndex === -1 ? '点击选择费率模板' : feeTemplates[feeIndex].name }}
            </view>
          </picker>
        </view>

        <button class="action-btn" @click="handleBindStationFee" :disabled="stationIndexForFee === -1 || feeIndex === -1">
          保存绑定关系
        </button>
      </view>
    </scroll-view>

    <view class="loading-overlay" v-if="loading">
      <view class="loading-spinner"></view>
      <text class="loading-text">处理中...</text>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { getDeviceList, getDeviceConfigList, batchModifyDeviceConfig } from '../../api/device.js'
import { getPlatformFeeRateList, bindStationFeeRate } from '../../api/rate.js'
import { getStationList } from '../../api/station.js'
import { showToast } from '../../utils/index.js'

const loading = ref(false)
const activeTab = ref(0)

const stationList = ref([])
const stationIndex = ref(-1)
const deviceList = ref([])
const selectedDeviceIds = ref([])

const configTemplates = ref([])
const configIndex = ref(-1)

const stationIndexForFee = ref(-1)
const feeTemplates = ref([])
const feeIndex = ref(-1)

onMounted(() => {
  fetchInitialData()
})

const fetchInitialData = async () => {
  loading.value = true
  try {
    const [stationsRes, configsRes, feesRes, devicesRes] = await Promise.all([
      getStationList(),
      getDeviceConfigList({ page: 1, pageSize: 1000 }),
      getPlatformFeeRateList({ page: 1, pageSize: 1000 }),
      getDeviceList({ page: 1, pageSize: 1000 })
    ])

    const adapt = (res) => {
      if (!res || res.code !== 200) return []
      const data = res.data
      return data.list || data.records || (Array.isArray(data) ? data : [])
    }

    stationList.value = adapt(stationsRes)
    configTemplates.value = adapt(configsRes)
    feeTemplates.value = adapt(feesRes)
    deviceList.value = adapt(devicesRes)
  } catch (error) {
    console.error('加载数据失败:', error)
    showToast('加载数据失败')
  } finally {
    loading.value = false
  }
}

const filteredDevices = computed(() => {
  if (stationIndex.value === -1) return deviceList.value
  const targetStationId = stationList.value[stationIndex.value].stationId
  return deviceList.value.filter(d => d.stationId == targetStationId)
})

const onStationChange = (e) => {
  stationIndex.value = e.detail.value
  selectedDeviceIds.value = []
}

const toggleDeviceSelection = (id) => {
  const index = selectedDeviceIds.value.indexOf(id)
  if (index > -1) {
    selectedDeviceIds.value.splice(index, 1)
  } else {
    selectedDeviceIds.value.push(id)
  }
}

const onConfigTemplateChange = (e) => {
  configIndex.value = e.detail.value
}

const handleBatchBindConfig = async () => {
  const template = configTemplates.value[configIndex.value]
  loading.value = true
  try {
    const res = await batchModifyDeviceConfig({
      deviceIds: selectedDeviceIds.value,
      deviceConfigId: template.id
    })
    if (res.code === 200) {
      showToast('绑定成功', 'success')
      selectedDeviceIds.value = []
    } else {
      showToast(res.message || '绑定失败')
    }
  } catch (error) {
    showToast('操作失败')
  } finally {
    loading.value = false
  }
}

const onStationSelectForFee = (e) => {
  stationIndexForFee.value = e.detail.value
}

const onFeeTemplateChange = (e) => {
  feeIndex.value = e.detail.value
}

const handleBindStationFee = async () => {
  const station = stationList.value[stationIndexForFee.value]
  const template = feeTemplates.value[feeIndex.value]
  loading.value = true
  try {
    const res = await bindStationFeeRate({
      stationId: station.stationId,
      feeRateId: template.id
    })
    if (res.code === 200) {
      showToast('费率绑定成功', 'success')
    } else {
      showToast(res.message || '操作失败')
    }
  } catch (error) {
    showToast('操作失败')
  } finally {
    loading.value = false
  }
}

const goBack = () => {
  uni.navigateBack()
}
</script>

<style scoped>
.device-binding-container {
  min-height: 100vh;
  background-color: #F5F7FA;
  display: flex;
  flex-direction: column;
}

.header-nav {
  display: flex;
  align-items: center;
  padding-top: calc(24rpx + var(--status-bar-height));
  padding-right: 30rpx;
  padding-bottom: 24rpx;
  padding-left: 30rpx;
  background: #C6171E;
  color: #fff;
}

.back-icon {
  font-size: 40rpx;
  margin-right: 20rpx;
}

.nav-title {
  font-size: 34rpx;
  font-weight: 600;
  flex: 1;
  text-align: center;
}

.tabs {
  display: flex;
  background-color: #fff;
  border-bottom: 1rpx solid #eee;
}

.tab {
  flex: 1;
  text-align: center;
  padding: 24rpx 0;
  font-size: 28rpx;
  color: #666;
  position: relative;
}

.tab.active {
  color: #C6171E;
  font-weight: 600;
}

.tab.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 25%;
  width: 50%;
  height: 4rpx;
  background-color: #C6171E;
}

.content-scroll {
  flex: 1;
  padding: 20rpx;
}

.card {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 24rpx;
  margin-bottom: 24rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);
}

.card-header {
  font-size: 28rpx;
  font-weight: 600;
  color: #333;
  margin-bottom: 20rpx;
  border-bottom: 1rpx solid #f5f5f5;
  padding-bottom: 12rpx;
}

.station-filter {
  margin-bottom: 20rpx;
}

.picker-item {
  background-color: #f9f9f9;
  padding: 20rpx;
  border-radius: 8rpx;
  font-size: 26rpx;
  color: #666;
  border: 1rpx solid #eee;
}

.device-list {
  max-height: 400rpx;
  overflow-y: auto;
}

.device-item {
  display: flex;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #f9f9f9;
}

.device-name {
  font-size: 26rpx;
  color: #333;
  margin-left: 12rpx;
}

.empty-tip {
  text-align: center;
  padding: 40rpx;
  color: #999;
  font-size: 24rpx;
}

.action-btn {
  background: #C6171E;
  color: #fff;
  margin-top: 40rpx;
  border-radius: 12rpx;
}

.action-btn:disabled {
  opacity: 0.5;
}

.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.4);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.loading-spinner {
  font-size: 64rpx;
  animation: spin 1s linear infinite;
  margin-bottom: 32rpx;
  color: #fff;
}

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

</style>
