<template>
  <div class="device-management">
    <header class="header">
      <h1>设备管理</h1>
      <div class="user-info">
        <span>欢迎, {{ username }}</span>
        <button class="logout-btn" @click="logout">退出</button>
      </div>
    </header>

    <main class="main-content">
      <div class="toolbar">
        <button class="btn btn-primary" @click="openAddDeviceModal">添加设备</button>
      </div>

      <div class="device-tree" id="deviceTree">
        <!-- 设备树将通过JavaScript动态生成 -->
      </div>
    </main>

    <!-- 添加/编辑设备模态框 -->
    <div class="modal" v-if="showModal">
      <div class="modal-content">
        <div class="modal-header">
          <h3>{{ editingDevice ? '编辑设备' : '添加设备' }}</h3>
          <button class="close-btn" @click="closeDeviceModal">&times;</button>
        </div>
        <div class="modal-body">
          <form @submit.prevent="saveDevice">
            <input type="hidden" v-model="deviceForm.id">
            <div class="form-group">
              <label for="deviceName">设备名称</label>
              <input type="text" id="deviceName" v-model="deviceForm.name" required>
            </div>
            <div class="form-group">
              <label for="deviceType">设备类型</label>
              <select id="deviceType" v-model="deviceForm.type" required @change="toggleParentField">
                <option value="">请选择设备类型</option>
                <option value="relay">中继设备</option>
                <option value="pig_pen_controller">猪舍主控</option>
                <option value="feed_mill_controller">做料车间主控</option>
                <option value="fan">风机</option>
                <option value="water_curtain">水帘</option>
              </select>
            </div>
            <div class="form-group" v-if="deviceForm.type !== 'relay' && deviceForm.type !== ''">
              <label for="parentId">上级设备</label>
              <select id="parentId" v-model="deviceForm.parent_id">
                <option value="">请选择上级设备</option>
                <option 
                  v-for="parent in getParentDevices(deviceForm.type)" 
                  :key="parent.id" 
                  :value="parent.id"
                >
                  {{ parent.name }}
                </option>
              </select>
            </div>
          </form>
        </div>
        <div class="modal-footer">
          <button class="btn btn-secondary" @click="closeDeviceModal">取消</button>
          <button class="btn btn-primary" @click="saveDevice">保存</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'Device',
  data() {
    return {
      username: localStorage.getItem('username') || '管理员',
      devices: [],
      showModal: false,
      editingDevice: null,
      deviceForm: {
        id: null,
        name: '',
        type: '',
        parent_id: null
      }
    }
  },
  computed: {
    // 获取中继设备（顶级设备）
    relayDevices() {
      return this.devices.filter(device => device.type === 'relay')
    }
  },
  mounted() {
    this.loadDevices()
  },
  methods: {
    logout() {
      // 清除本地存储的认证信息
      localStorage.removeItem('authToken')
      localStorage.removeItem('userId')
      localStorage.removeItem('username')
      
      // 跳转到登录页面
      this.$router.push('/')
    },
    
    // 获取控制器设备（区域主控）
    getControllerDevices(parentId) {
      return this.devices.filter(device => 
        device.parent_id === parentId && 
        (device.type === 'pig_pen_controller' || device.type === 'feed_mill_controller')
      )
    },
    
    // 获取叶子设备（具体设备）
    getLeafDevices(parentId) {
      return this.devices.filter(device => 
        device.parent_id === parentId && 
        (device.type === 'fan' || device.type === 'water_curtain')
      )
    },
    
    // 获取设备类型文本
    getDeviceTypeText(type) {
      const typeMap = {
        'relay': '中继',
        'pig_pen_controller': '猪舍主控',
        'feed_mill_controller': '做料车间主控',
        'fan': '风机',
        'water_curtain': '水帘'
      }
      return typeMap[type] || type
    },
    
    // 获取上级设备选项
    getParentDevices(currentType) {
      if (currentType === 'pig_pen_controller' || currentType === 'feed_mill_controller') {
        // 控制器的上级是中继设备
        return this.devices.filter(device => device.type === 'relay')
      } else if (currentType === 'fan' || currentType === 'water_curtain') {
        // 设备的上级是控制器
        return this.devices.filter(device => 
          device.type === 'pig_pen_controller' || device.type === 'feed_mill_controller')
      }
      return []
    },
    
    // 加载设备列表
    async loadDevices() {
      try {
        const response = await fetch('/api/v1/device/list', {
          headers: {
            'Authorization': 'Bearer ' + localStorage.getItem('authToken')
          }
        })
        
        const data = await response.json()
        
        if (response.ok && data.code === 0) {
          this.devices = data.data.devices
        } else {
          console.error('获取设备列表失败:', data.message)
        }
      } catch (error) {
        console.error('获取设备列表失败:', error)
      }
    },
    
    // 打开添加设备模态框
    openAddDeviceModal() {
      this.editingDevice = null
      this.deviceForm = {
        id: null,
        name: '',
        type: '',
        parent_id: null
      }
      this.showModal = true
    },
    
    // 编辑设备
    editDevice(device) {
      this.editingDevice = device
      this.deviceForm = { ...device }
      this.showModal = true
    },
    
    // 关闭模态框
    closeDeviceModal() {
      this.showModal = false
    },
    
    // 保存设备
    async saveDevice() {
      if (!this.deviceForm.name || !this.deviceForm.type) {
        alert('请填写必填字段')
        return
      }
      
      if (this.deviceForm.type !== 'relay' && !this.deviceForm.parent_id) {
        alert('请选择上级设备')
        return
      }
      
      try {
        let url, method
        const deviceData = {
          name: this.deviceForm.name,
          type: this.deviceForm.type,
          parent_id: this.deviceForm.parent_id
        }
        
        if (this.editingDevice) {
          // 更新设备
          url = '/api/v1/device/update'
          method = 'POST'
          deviceData.id = this.deviceForm.id
        } else {
          // 创建设备
          url = '/api/v1/device/create'
          method = 'POST'
        }
        
        const response = await fetch(url, {
          method: method,
          headers: {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer ' + localStorage.getItem('authToken')
          },
          body: JSON.stringify(deviceData)
        })
        
        const data = await response.json()
        
        if (response.ok && data.code === 0) {
          // 保存成功，重新加载设备列表
          await this.loadDevices()
          this.closeDeviceModal()
        } else {
          alert('保存失败: ' + data.message)
        }
      } catch (error) {
        console.error('保存设备失败:', error)
        alert('保存设备失败: ' + error.message)
      }
    },
    
    // 删除设备
    async deleteDevice(deviceId) {
      if (!confirm('确定要删除这个设备吗？')) {
        return
      }
      
      try {
        const response = await fetch('/api/v1/device/delete', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer ' + localStorage.getItem('authToken')
          },
          body: JSON.stringify({ id: deviceId })
        })
        
        const data = await response.json()
        
        if (response.ok && data.code === 0) {
          // 删除成功，重新加载设备列表
          await this.loadDevices()
        } else {
          alert('删除失败: ' + data.message)
        }
      } catch (error) {
        console.error('删除设备失败:', error)
        alert('删除设备失败: ' + error.message)
      }
    },
    
    // 根据设备类型切换上级设备字段显示
    toggleParentField() {
      if (this.deviceForm.type === 'relay') {
        this.deviceForm.parent_id = null
      }
    }
  }
}
</script>

<style scoped>
.device-management {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.header {
  background: #2c3e50;
  color: white;
  padding: 1rem;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header h1 {
  margin: 0;
  font-size: 1.5rem;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.logout-btn {
  background: #e74c3c;
  color: white;
  border: none;
  padding: 0.5rem 1rem;
  border-radius: 4px;
  cursor: pointer;
}

.logout-btn:hover {
  background: #c0392b;
}

.main-content {
  flex: 1;
  padding: 1rem;
  overflow-y: auto;
}

.toolbar {
  margin-bottom: 1rem;
}

.btn {
  padding: 0.5rem 1rem;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 1rem;
}

.btn-primary {
  background: #3498db;
  color: white;
}

.btn-primary:hover {
  background: #2980b9;
}

.btn-secondary {
  background: #95a5a6;
  color: white;
}

.btn-secondary:hover {
  background: #7f8c8d;
}

.device-tree {
  background: white;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  padding: 1rem;
}

.tree-node {
  margin-bottom: 0.5rem;
  padding: 0.5rem;
  border-radius: 4px;
  border-left: 3px solid #3498db;
}

.tree-node.relay-node {
  background: #ecf0f1;
  border-left-color: #e74c3c;
}

.tree-node.controller-node {
  background: #f8f9fa;
  border-left-color: #f39c12;
  margin-left: 1rem;
}

.tree-node.device-node {
  background: #fff;
  border-left-color: #2ecc71;
  margin-left: 2rem;
}

.node-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.node-title {
  font-weight: bold;
}

.node-type {
  font-size: 0.8rem;
  padding: 0.2rem 0.5rem;
  border-radius: 4px;
  margin: 0 0.5rem;
}

.relay-type {
  background: #e74c3c;
  color: white;
}

.controller-type {
  background: #f39c12;
  color: white;
}

.device-type {
  background: #2ecc71;
  color: white;
}

.node-actions {
  display: flex;
  gap: 0.5rem;
}

.action-btn {
  padding: 0.2rem 0.5rem;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 0.9rem;
}

.edit-btn {
  background: #3498db;
  color: white;
}

.edit-btn:hover {
  background: #2980b9;
}

.delete-btn {
  background: #e74c3c;
  color: white;
}

.delete-btn:hover {
  background: #c0392b;
}

.modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0,0,0,0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 4px;
  width: 90%;
  max-width: 500px;
  box-shadow: 0 4px 8px rgba(0,0,0,0.2);
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem;
  border-bottom: 1px solid #eee;
}

.modal-header h3 {
  margin: 0;
}

.close-btn {
  background: none;
  border: none;
  font-size: 1.5rem;
  cursor: pointer;
  padding: 0;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.close-btn:hover {
  background: #f5f5f5;
  border-radius: 50%;
}

.modal-body {
  padding: 1rem;
}

.form-group {
  margin-bottom: 1rem;
}

.form-group label {
  display: block;
  margin-bottom: 0.5rem;
  font-weight: bold;
}

.form-group input,
.form-group select {
  width: 100%;
  padding: 0.5rem;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 1rem;
  box-sizing: border-box;
}

.modal-footer {
  padding: 1rem;
  border-top: 1px solid #eee;
  display: flex;
  justify-content: flex-end;
  gap: 0.5rem;
}
</style>