<template>
  <div>
    <div class="header">
      <h1>🐷 猪场管理系统</h1>
      <div class="user-info">
        <span>{{ username }}</span>
        <button class="logout-btn" @click="logout">退出登录</button>
      </div>
    </div>

    <div class="nav">
      <ul>
        <li><router-link to="/dashboard">控制台</router-link></li>
        <li><router-link to="/device" class="active">设备管理</router-link></li>
      </ul>
    </div>

    <div class="container">
      <div class="page-header">
        <h2>设备管理</h2>
        <button class="btn btn-primary" @click="openAddDeviceModal">添加设备</button>
      </div>

      <div class="device-tree" id="deviceTree">
        <!-- 设备树将通过JavaScript动态生成 -->
        <div v-if="devices.length === 0">
          暂无设备数据
        </div>
        
        <div v-for="relay in relayDevices" :key="relay.id" class="tree-node relay-node">
          <div class="node-header">
            <div class="node-title">
              <span>{{ relay.name }}</span>
              <span class="node-type relay-type">中继</span>
              <span :class="'status-' + relay.status">{{ relay.status === 'active' ? '启用' : '停用' }}</span>
            </div>
            <div class="node-actions">
              <button class="action-btn edit-btn" @click="editDevice(relay)">编辑</button>
              <button class="action-btn delete-btn" @click="deleteDevice(relay.id)">删除</button>
            </div>
          </div>
          
          <div class="children" v-if="getControllerDevices(relay.id).length > 0">
            <div 
              v-for="controller in getControllerDevices(relay.id)" 
              :key="controller.id" 
              class="tree-node controller-node"
            >
              <div class="node-header">
                <div class="node-title">
                  <span>{{ controller.name }}</span>
                  <span class="node-type controller-type">
                    {{ getDeviceTypeText(controller.type) }}
                  </span>
                  <span :class="'status-' + controller.status">{{ controller.status === 'active' ? '启用' : '停用' }}</span>
                </div>
                <div class="node-actions">
                  <button class="action-btn edit-btn" @click="editDevice(controller)">编辑</button>
                  <button class="action-btn delete-btn" @click="deleteDevice(controller.id)">删除</button>
                </div>
              </div>
              
              <div class="children" v-if="getLeafDevices(controller.id).length > 0">
                <div 
                  v-for="device in getLeafDevices(controller.id)" 
                  :key="device.id" 
                  class="tree-node device-node"
                >
                  <div class="node-header">
                    <div class="node-title">
                      <span>{{ device.name }}</span>
                      <span class="node-type device-type">{{ getDeviceTypeText(device.type) }}</span>
                      <span :class="'status-' + device.status">{{ device.status === 'active' ? '启用' : '停用' }}</span>
                    </div>
                    <div class="node-actions">
                      <button class="action-btn edit-btn" @click="editDevice(device)">编辑</button>
                      <button class="action-btn delete-btn" @click="deleteDevice(device.id)">删除</button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 添加/编辑设备模态框 -->
    <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 }
      delete this.deviceForm.status
      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 response
        if (this.editingDevice) {
          // 更新设备
          response = await fetch('/api/v1/device/update', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
              'Authorization': 'Bearer ' + localStorage.getItem('authToken')
            },
            body: JSON.stringify({
              id: this.deviceForm.id,
              name: this.deviceForm.name,
              type: this.deviceForm.type,
              parent_id: this.deviceForm.parent_id
            })
          })
        } else {
          // 创建设备
          response = await fetch('/api/v1/device/create', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
              'Authorization': 'Bearer ' + localStorage.getItem('authToken')
            },
            body: JSON.stringify({
              name: this.deviceForm.name,
              type: this.deviceForm.type,
              parent_id: this.deviceForm.parent_id
            })
          })
        }
        
        const data = await response.json()
        
        if (response.ok && data.code === 0) {
          this.closeDeviceModal()
          this.loadDevices() // 重新加载设备列表
        } else {
          alert('操作失败: ' + data.message)
        }
      } catch (error) {
        console.error('操作失败:', error)
        alert('操作失败，请查看控制台了解详情')
      }
    },
    
    // 删除设备
    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) {
          this.loadDevices() // 重新加载设备列表
        } else {
          alert('删除失败: ' + data.message)
        }
      } catch (error) {
        console.error('删除失败:', error)
        alert('删除失败，请查看控制台了解详情')
      }
    }
  }
}
</script>

<style scoped>
.header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header h1 {
  font-size: 24px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.logout-btn {
  background: rgba(255, 255, 255, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.3);
  color: white;
  padding: 8px 15px;
  border-radius: 5px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.logout-btn:hover {
  background: rgba(255, 255, 255, 0.3);
}

.nav {
  background: white;
  padding: 15px 20px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
}

.nav ul {
  display: flex;
  list-style: none;
  gap: 20px;
}

.nav a {
  text-decoration: none;
  color: #666;
  padding: 8px 15px;
  border-radius: 5px;
  transition: all 0.3s ease;
}

.nav a:hover, .nav a.active {
  background: #667eea;
  color: white;
}

.container {
  max-width: 1200px;
  margin: 30px auto;
  padding: 0 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  color: #333;
}

.btn {
  padding: 10px 20px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s ease;
}

.btn-primary {
  background: #667eea;
  color: white;
}

.btn-primary:hover {
  background: #5a6fd8;
}

.device-tree {
  background: white;
  border-radius: 15px;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.08);
  padding: 25px;
  margin-bottom: 30px;
}

.tree-node {
  margin-bottom: 15px;
  border-left: 2px solid #e1e1e1;
  padding-left: 20px;
}

.relay-node {
  border-left-color: #667eea;
}

.controller-node {
  border-left-color: #764ba2;
}

.device-node {
  border-left-color: #ffa500;
}

.node-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  background: #f8f9fa;
  border-radius: 5px;
  margin-bottom: 10px;
}

.relay-node > .node-header {
  background: rgba(102, 126, 234, 0.1);
}

.controller-node > .node-header {
  background: rgba(118, 75, 162, 0.1);
}

.device-node > .node-header {
  background: rgba(255, 165, 0, 0.1);
}

.node-title {
  font-weight: bold;
  display: flex;
  align-items: center;
  gap: 10px;
}

.node-type {
  font-size: 12px;
  padding: 2px 8px;
  border-radius: 10px;
  color: white;
}

.relay-type {
  background: #667eea;
}

.controller-type {
  background: #764ba2;
}

.device-type {
  background: #ffa500;
}

.node-actions {
  display: flex;
  gap: 10px;
}

.action-btn {
  padding: 5px 10px;
  border: none;
  border-radius: 3px;
  cursor: pointer;
  font-size: 12px;
}

.edit-btn {
  background: #ffc107;
  color: #333;
}

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

.children {
  margin-left: 20px;
}

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

.modal-content {
  background: white;
  border-radius: 15px;
  width: 100%;
  max-width: 500px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
}

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

.modal-header h3 {
  margin: 0;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #999;
}

.modal-body {
  padding: 20px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  font-weight: 500;
  color: #333;
}

.form-group input, .form-group select {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
  font-size: 14px;
}

.modal-footer {
  padding: 20px;
  border-top: 1px solid #eee;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.btn-secondary {
  background: #6c757d;
  color: white;
}

.status-active {
  color: #28a745;
  font-weight: bold;
}

.status-inactive {
  color: #dc3545;
  font-weight: bold;
}

@media (max-width: 768px) {
  .dashboard-grid {
    grid-template-columns: 1fr;
  }
  
  .header {
    flex-direction: column;
    gap: 15px;
  }
  
  .page-header {
    flex-direction: column;
    gap: 15px;
    align-items: flex-start;
  }
}
</style>