<template>
  <el-drawer
    title="车辆详情"
    :visible.sync="drawerVisible"
    direction="rtl"
    size="600px"
    :before-close="handleClose"
    @opened="handleOpened"
  >
    <div v-if="loading" class="drawer-loading">
      <i class="el-icon-loading"></i>
      <span>加载中...</span>
    </div>
    
    <div v-else-if="vehicleData" class="vehicle-drawer-content">
      <!-- Header Section -->
      <div class="drawer-header">
        <div class="vehicle-title">
          <span class="vehicle-name">{{ vehicleData.vehicleName || vehicleData.plateNo }}</span>
          <el-tag :type="getStatusTagType(vehicleData.status)" size="medium">
            {{ getStatusLabel(vehicleData.status) }}
          </el-tag>
        </div>
      </div>

      <!-- Basic Information -->
      <el-divider content-position="left">基本信息</el-divider>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="车辆名称">{{ vehicleData.vehicleName || '-' }}</el-descriptions-item>
        <el-descriptions-item label="车牌号">{{ vehicleData.plateNo || '-' }}</el-descriptions-item>
        <el-descriptions-item label="车辆类型">{{ getVehicleTypeLabel(vehicleData.vehicleType) }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusTagType(vehicleData.status)" size="small">
            {{ getStatusLabel(vehicleData.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="所属队伍" :span="2">
          {{ vehicleData.teamName || '-' }}
        </el-descriptions-item>
      </el-descriptions>

      <!-- Device Information -->
      <el-divider content-position="left">定位设备</el-divider>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="设备提供商">{{ getDeviceProviderLabel(vehicleData.deviceProvider) }}</el-descriptions-item>
        <el-descriptions-item label="定位设备ID">{{ vehicleData.deviceId || '-' }}</el-descriptions-item>
        <el-descriptions-item label="最后定位时间" :span="2">
          <span v-if="vehicleData.lastSeenAt">{{ parseTime(vehicleData.lastSeenAt) }}</span>
          <span v-else style="color: #909399;">-</span>
        </el-descriptions-item>
      </el-descriptions>

      <!-- Capabilities -->
      <el-divider content-position="left">能力标签</el-divider>
      <div class="capabilities-section">
        <el-tag
          v-for="tag in formatCapabilities(vehicleData.capabilities)"
          :key="tag"
          size="small"
          type="success"
          class="capability-tag"
        >
          {{ tag }}
        </el-tag>
        <span v-if="!formatCapabilities(vehicleData.capabilities).length" class="text-placeholder">-</span>
      </div>

      <!-- Map Section (if GPS coordinates available) -->
      <div v-if="hasLocation() && mapReady" class="drawer-map-section">
        <el-divider content-position="left">当前位置</el-divider>
        <div class="map-container">
          <Amap
            container-id="vehicle-detail-map"
            width="100%"
            height="300px"
            :center="[vehicleData.gpsLng, vehicleData.gpsLat]"
            :zoom="15"
            :markers="[{
              lat: vehicleData.gpsLat,
              lng: vehicleData.gpsLng,
              title: vehicleData.vehicleName || vehicleData.plateNo || '车辆',
              content: vehicleData.vehicleName || vehicleData.plateNo || '车辆'
            }]"
          />
        </div>
      </div>

      <!-- Remark -->
      <el-divider v-if="vehicleData.remark" content-position="left">备注</el-divider>
      <div v-if="vehicleData.remark" class="remark-section">
        {{ vehicleData.remark }}
      </div>
    </div>
    
    <div v-else class="drawer-error">
      <el-alert
        title="加载失败"
        type="error"
        :closable="false"
        show-icon
      >
        <template slot="default">
          <p>无法加载车辆详情，请稍后重试</p>
          <el-button size="mini" @click="loadVehicleDetail">重试</el-button>
        </template>
      </el-alert>
    </div>
  </el-drawer>
</template>

<script>
import Amap from '@/components/Amap'
import { getVehicle } from '@/api/resource/vehicle'
import { parseTime } from '@/utils/shuyu-utils'

export default {
  name: 'VehicleDetailDrawer',
  components: {
    Amap
  },
  dicts: ['vehicle_status', 'vehicle_type', 'device_provider'],
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    vehicleId: {
      type: [Number, String],
      default: null
    }
  },
  data() {
    return {
      drawerVisible: false,
      loading: false,
      vehicleData: null,
      mapReady: false
    }
  },
  watch: {
    visible(newVal) {
      this.drawerVisible = newVal
      if (newVal && this.vehicleId) {
        this.loadVehicleDetail()
      }
    },
    vehicleId(newVal) {
      if (newVal && this.drawerVisible) {
        this.loadVehicleDetail()
      }
    },
    drawerVisible(newVal) {
      if (!newVal) {
        this.$emit('update:visible', false)
        this.reset()
      }
    }
  },
  methods: {
    parseTime,
    async loadVehicleDetail() {
      if (!this.vehicleId) return
      
      this.loading = true
      this.mapReady = false
      try {
        const response = await getVehicle(this.vehicleId)
        if (response.code === 200) {
          this.vehicleData = response.data
        } else {
          this.$message.error(response.msg || '加载失败')
          this.vehicleData = null
        }
      } catch (error) {
        console.error('加载车辆详情失败:', error)
        this.$message.error('加载失败，请稍后重试')
        this.vehicleData = null
      } finally {
        this.loading = false
      }
    },
    handleClose(done) {
      this.reset()
      done()
    },
    handleOpened() {
      this.$nextTick(() => {
        setTimeout(() => {
          this.mapReady = true
        }, 100)
      })
    },
    reset() {
      this.vehicleData = null
      this.mapReady = false
    },
    hasLocation() {
      return this.vehicleData && 
             this.vehicleData.gpsLat && 
             this.vehicleData.gpsLng
    },
    formatCapabilities(capabilities) {
      if (!capabilities) return []
      try {
        const result = JSON.parse(capabilities)
        if (Array.isArray(result)) {
          return result.map(item => item && item.toString()).filter(Boolean)
        }
      } catch (e) {
        // ignore parse error
      }
      return capabilities
        .split(/[,，\s]+/)
        .map(item => item.trim())
        .filter(item => !!item)
    },
    getStatusLabel(status) {
      if (!status) return '-'
      if (this.dict && this.dict.type && this.dict.type.vehicle_status) {
        const dict = this.dict.type.vehicle_status.find(item => item.value === status)
        if (dict) return dict.label
      }
      const statusMap = {
        'available': '可用',
        'busy': '占用',
        'maintenance': '维护中'
      }
      return statusMap[status] || status || '-'
    },
    getStatusTagType(status) {
      const typeMap = {
        'available': 'success',
        'busy': 'warning',
        'maintenance': 'info'
      }
      return typeMap[status] || 'info'
    },
    getVehicleTypeLabel(vehicleType) {
      if (!vehicleType) return '-'
      if (this.dict && this.dict.type && this.dict.type.vehicle_type) {
        const dict = this.dict.type.vehicle_type.find(item => item.value === vehicleType)
        if (dict) return dict.label
      }
      return vehicleType || '-'
    },
    getDeviceProviderLabel(deviceProvider) {
      if (!deviceProvider) return '-'
      if (this.dict && this.dict.type && this.dict.type.device_provider) {
        const dict = this.dict.type.device_provider.find(item => item.value === deviceProvider)
        if (dict) return dict.label
      }
      return deviceProvider || '-'
    }
  }
}
</script>

<style lang="scss" scoped>
.drawer-loading {
  text-align: center;
  padding: 40px 20px;
  color: #909399;
}

.drawer-loading i {
  font-size: 24px;
  margin-right: 8px;
  animation: rotating 2s linear infinite;
}

@keyframes rotating {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.vehicle-drawer-content {
  padding: 20px;
}

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

.vehicle-title {
  display: flex;
  align-items: center;
  gap: 12px;
}

.vehicle-name {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.capabilities-section {
  padding: 12px 0;
  
  .capability-tag {
    margin-right: 8px;
    margin-bottom: 8px;
  }
  
  .text-placeholder {
    color: #909399;
  }
}

.drawer-map-section {
  margin-top: 20px;
}

.map-container {
  border-radius: 4px;
  overflow: hidden;
}

.remark-section {
  padding: 12px;
  background: #f5f7fa;
  border-radius: 4px;
  line-height: 1.6;
  color: #606266;
  white-space: pre-wrap;
  word-break: break-word;
}

.drawer-error {
  padding: 20px;
}
</style>