<template>
  <div class="app-container">
    <el-tabs v-model="activeTab">
      <!-- 车位管理标签页 -->
      <el-tab-pane label="车位管理" name="spaces">
        <el-form :model="spaceQuery" :inline="true" label-width="80px">
          <el-form-item label="车位编号">
            <el-input v-model="spaceQuery.spaceCode" placeholder="请输入车位编号" clearable />
          </el-form-item>
          <el-form-item label="车位名称">
            <el-input v-model="spaceQuery.spaceName" placeholder="请输入车位名称" clearable />
          </el-form-item>
          <el-form-item label="楼栋">
            <el-select v-model="spaceQuery.buildingId" placeholder="请选择楼栋" clearable>
              <el-option v-for="building in buildingList" :key="building.id" :label="building.name" :value="building.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="车位状态">
            <el-select v-model="spaceQuery.spaceStatus" placeholder="请选择状态" clearable>
              <el-option label="空闲" :value="0" />
              <el-option label="占用" :value="1" />
              <el-option label="预约" :value="2" />
              <el-option label="故障" :value="3" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="getSpaceList">搜索</el-button>
            <el-button @click="resetSpaceQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain @click="handleAddSpace">新增</el-button>
          </el-col>
        </el-row>

        <el-table v-loading="spaceLoading" :data="spaceList" stripe border>
          <el-table-column label="车位编号" prop="space_code"  />
          <el-table-column label="车位名称" prop="space_name"  />
          <el-table-column label="楼栋" prop="building_name"  />
          <el-table-column label="楼层" prop="floor_name" />
          <el-table-column label="车位状态" prop="space_status">
            <template #default="scope">
              <el-tag :type="statusTag(scope.row.space_status)">
                {{ statusText(scope.row.space_status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="车牌号" prop="license_plate"  />
          <el-table-column label="入场时间" prop="entry_time"  />
          <el-table-column label="停车费用" prop="parking_fee" >
            <template #default="scope">
              ¥{{ scope.row.parking_fee || '0.00' }}
            </template>
          </el-table-column>
          <el-table-column label="车位类型" prop="space_type" >
            <template #default="scope">
              <el-tag :type="typeTag(scope.row.space_type)">
                {{ typeText(scope.row.space_type) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="200">
            <template #default="scope">
              <el-button link type="primary" @click="handleUpdateSpace(scope.row)">修改</el-button>
              <el-button link type="primary" @click="handleViewSpace(scope.row)">详情</el-button>
              <el-button link type="danger" @click="handleDeleteSpace(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-pagination
            v-model:current-page="spaceQuery.pageNum"
            v-model:page-size="spaceQuery.pageSize"
            :page-sizes="[10, 20, 50]"
            :total="spaceTotal"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="getSpaceList"
            @current-change="getSpaceList"
        />
      </el-tab-pane>

      <!-- 实时监控标签页 -->
      <el-tab-pane label="实时监控" name="monitor">
        <div class="monitor-container">
          <!-- 统计卡片 -->
          <el-row :gutter="20" class="statistics-row">
            <el-col :span="6">
              <el-card>
                <el-statistic title="总车位数" :value="statistics.totalSpaces" />
              </el-card>
            </el-col>
            <el-col :span="6">
              <el-card>
                <el-statistic title="空闲车位" :value="statistics.freeSpaces" />
              </el-card>
            </el-col>
            <el-col :span="6">
              <el-card>
                <el-statistic title="占用车位" :value="statistics.occupiedSpaces" />
              </el-card>
            </el-col>
            <el-col :span="6">
              <el-card>
                <el-statistic title="占用率" :value="Number(statistics.occupancyRate)" suffix="%" />
              </el-card>
            </el-col>
          </el-row>

          <!-- 楼层车位分布 -->
          <el-row :gutter="20" style="margin-top: 20px;">
            <el-col :span="24">
              <el-card>
                <template #header>
                  <div class="card-header">
                    <span>车位分布图</span>
                  </div>
                </template>
                <div class="parking-map">
                  <div v-for="floor in currentFloors" :key="floor.id" class="floor-section">
                    <h4>{{ floor.name }}</h4>
                    <div class="parking-grid">
                      <div v-for="space in getFloorSpaces(floor.id)" :key="space.id"
                           :class="['parking-space', `status-${space.space_status}`]"
                           @click="handleSpaceClick(space)">
                        <div class="space-number">{{ space.space_code }}</div>
                        <div class="space-info">
                          <span v-if="space.space_status === 1">{{ space.license_plate }}</span>
                          <span v-else-if="space.space_status === 0">空闲</span>
                          <span v-else-if="space.space_status === 2">预约</span>
                          <span v-else>故障</span>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </el-card>
            </el-col>
          </el-row>

          <!-- 实时进出记录 -->
          <el-row :gutter="20" style="margin-top: 20px;">
            <el-col :span="12">
              <el-card>
                <template #header>
                  <span>最近入场</span>
                </template>
                <el-table :data="recentEntries" height="300">
                  <el-table-column label="车牌号" prop="license_plate" />
                  <el-table-column label="车位" prop="space_code" />
                  <el-table-column label="入场时间" prop="entry_time" />
                </el-table>
              </el-card>
            </el-col>
            <el-col :span="12">
              <el-card>
                <template #header>
                  <span>最近出场</span>
                </template>
                <el-table :data="recentExits" height="300">
                  <el-table-column label="车牌号" prop="license_plate" />
                  <el-table-column label="车位" prop="space_code" />
                  <el-table-column label="停车时长" prop="duration" />
                  <el-table-column label="费用" prop="fee">
                    <template #default="scope">
                      ¥{{ scope.row.fee }}
                    </template>
                  </el-table-column>
                </el-table>
              </el-card>
            </el-col>
          </el-row>
        </div>
      </el-tab-pane>

      <!-- 统计报表标签页 -->
      <el-tab-pane label="统计报表" name="report">
        <div class="report-container">
          <el-form :model="reportQuery" :inline="true" label-width="80px">
            <el-form-item label="统计类型">
              <el-select v-model="reportQuery.reportType" placeholder="请选择" style="width: 150px">
                <el-option label="日报表" value="daily" />
                <el-option label="周报表" value="weekly" />
                <el-option label="月报表" value="monthly" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="generateReport">生成报表</el-button>
            </el-form-item>
          </el-form>

          <!-- 详细数据表格 -->
          <el-card style="margin-top: 20px;">
            <template #header>
              <span>详细数据</span>
            </template>
            <el-table :data="reportData" stripe border>
              <el-table-column label="日期" prop="date" />
              <el-table-column label="总车位数" prop="totalSpaces" />
              <el-table-column label="使用车位" prop="usedSpaces" />
              <el-table-column label="占用率" prop="occupancyRate">
                <template #default="scope">
                  {{ scope.row.occupancyRate }}%
                </template>
              </el-table-column>
              <el-table-column label="车辆进入" prop="entryCount" />
              <el-table-column label="车辆离开" prop="exitCount" />
              <el-table-column label="收入金额" prop="revenue">
                <template #default="scope">
                  ¥{{ scope.row.revenue }}
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 车位新增/修改对话框 -->
    <el-dialog :title="spaceTitle" v-model="spaceOpen" width="600px">
      <el-form ref="spaceFormRef" :model="spaceForm" :rules="spaceRules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="车位编号" prop="spaceCode">
              <el-input v-model="spaceForm.spaceCode" placeholder="请输入车位编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="车位名称" prop="spaceName">
              <el-input v-model="spaceForm.spaceName" placeholder="请输入车位名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="楼栋" prop="buildingId">
              <el-select v-model="spaceForm.buildingId" placeholder="请选择楼栋" style="width: 100%">
                <el-option v-for="building in buildingList" :key="building.id" :label="building.name" :value="building.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="楼层" prop="floorId">
              <el-select v-model="spaceForm.floorId" placeholder="请选择楼层" style="width: 100%">
                <el-option v-for="floor in floorList" :key="floor.id" :label="floor.name" :value="floor.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="车位类型" prop="spaceType">
              <el-select v-model="spaceForm.spaceType" placeholder="请选择类型" style="width: 100%">
                <el-option label="普通" value="normal" />
                <el-option label="VIP" value="vip" />
                <el-option label="残疾人" value="disabled" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitSpaceForm">确 定</el-button>
          <el-button @click="cancelSpace">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 车位详情对话框 -->
    <el-dialog title="车位详情" v-model="spaceDetailOpen" width="800px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="车位编号">{{ spaceDetail.space_code }}</el-descriptions-item>
        <el-descriptions-item label="车位名称">{{ spaceDetail.space_name }}</el-descriptions-item>
        <el-descriptions-item label="楼栋">{{ spaceDetail.building_name }}</el-descriptions-item>
        <el-descriptions-item label="楼层">{{ spaceDetail.floor_name }}</el-descriptions-item>
        <el-descriptions-item label="车位类型">
          <el-tag :type="typeTag(spaceDetail.space_type)">
            {{ typeText(spaceDetail.space_type) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="车位状态">
          <el-tag :type="statusTag(spaceDetail.space_status)">
            {{ statusText(spaceDetail.space_status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="车牌号">{{ spaceDetail.license_plate || '-' }}</el-descriptions-item>
        <el-descriptions-item label="入场时间">{{ spaceDetail.entry_time || '-' }}</el-descriptions-item>
        <el-descriptions-item label="停车费用">¥{{ spaceDetail.parking_fee || '0.00' }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ spaceDetail.remark || '-' }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, reactive, onMounted, onUnmounted} from 'vue'
import {
  listParkingSpace,
  getParkingSpace,
  addParkingSpace,
  updateParkingSpace,
  delParkingSpace
} from '@/api/parking/space'
import {getParkingStatistics, getRealtimeData, getParkingReport} from '@/api/parking/monitor'
import {ElMessage, ElMessageBox} from 'element-plus'

const activeTab = ref('spaces')

// 车位相关
const spaceQuery = reactive({
  pageNum: 1,
  pageSize: 10,
  spaceCode: null,
  spaceName: null,
  buildingId: null,
  floorId: null,
  spaceStatus: null,
  spaceType: null
})
const spaceList = ref([])
const spaceTotal = ref(0)
const spaceLoading = ref(false)
const spaceTitle = ref('')
const spaceOpen = ref(false)
const spaceForm = ref({})
const spaceFormRef = ref(null)
const spaceDetailOpen = ref(false)
const spaceDetail = ref({})
const spaceRules = {
  spaceCode: [{required: true, message: '车位编号不能为空', trigger: 'blur'}],
  spaceName: [{required: true, message: '车位名称不能为空', trigger: 'blur'}],
  buildingId: [{required: true, message: '请选择楼栋', trigger: 'change'}],
  floorId: [{required: true, message: '请选择楼层', trigger: 'change'}],
  spaceType: [{required: true, message: '请选择车位类型', trigger: 'change'}]
}

// 监控相关
const statistics = ref({
  totalSpaces: 0,
  freeSpaces: 0,
  occupiedSpaces: 0,
  occupancyRate: 0
})
const currentFloors = ref([])
const floorSpaces = ref([])
const recentEntries = ref([])
const recentExits = ref([])
const monitorTimer = ref(null)

// 报表相关
const reportQuery = reactive({
  reportType: 'daily',
  dateRange: []
})
const reportData = ref([])

// 其他数据
const buildingList = ref([])
const floorList = ref([])

// 状态相关函数
const statusTag = (status) => {
  const map = {0: 'success', 1: 'warning', 2: 'info', 3: 'danger'}
  return map[status] || 'info'
}

const statusText = (status) => {
  const map = {0: '空闲', 1: '占用', 2: '预约', 3: '故障'}
  return map[status] || '未知'
}

const typeTag = (type) => {
  const map = {normal: '', vip: 'warning', disabled: 'info'}
  return map[type] || ''
}

const typeText = (type) => {
  const map = {normal: '普通', vip: 'VIP', disabled: '残疾人'}
  return map[type] || type
}

// 查询车位列表
async function getSpaceList() {
  spaceLoading.value = true
  try {
    const response = await listParkingSpace(spaceQuery)
    spaceList.value = response.rows
    spaceTotal.value = response.total
  } catch (error) {
    ElMessage.error('获取车位列表失败')
  } finally {
    spaceLoading.value = false
  }
}

// 重置查询
function resetSpaceQuery() {
  spaceQuery.spaceCode = null
  spaceQuery.spaceName = null
  spaceQuery.buildingId = null
  spaceQuery.floorId = null
  spaceQuery.spaceStatus = null
  spaceQuery.spaceType = null
  getSpaceList()
}

// 新增车位
function handleAddSpace() {
  resetSpace()
  spaceOpen.value = true
  spaceTitle.value = '添加车位'
}

// 修改车位
async function handleUpdateSpace(row) {
  resetSpace()
  try {
    const response = await getParkingSpace(row.id)
    spaceForm.value = response.data
    spaceOpen.value = true
    spaceTitle.value = '修改车位'
  } catch (error) {
    ElMessage.error('获取车位信息失败')
  }
}

// 删除车位
function handleDeleteSpace(row) {
  ElMessageBox.confirm(`是否确认删除车位编号为"${row.space_code}"的数据项？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await delParkingSpace(row.id)
      ElMessage.success('删除成功')
      getSpaceList()
    } catch (error) {
      ElMessage.error('删除失败')
    }
  })
}

// 查看车位详情
async function handleViewSpace(row) {
  try {
    const response = await getParkingSpace(row.id)
    spaceDetail.value = response.data
    spaceDetailOpen.value = true
  } catch (error) {
    ElMessage.error('获取车位详情失败')
  }
}

// 提交车位表单
async function submitSpaceForm() {
  const valid = await spaceFormRef.value.validate()
  if (valid) {
    try {
      if (spaceForm.value.id) {
        await updateParkingSpace(spaceForm.value)
        ElMessage.success('修改成功')
      } else {
        await addParkingSpace(spaceForm.value)
        ElMessage.success('新增成功')
      }
      spaceOpen.value = false
      getSpaceList()
    } catch (error) {
      ElMessage.error('操作失败')
    }
  }
}

// 取消车位对话框
function cancelSpace() {
  spaceOpen.value = false
  resetSpace()
}

// 重置车位表单
function resetSpace() {
  spaceForm.value = {
    id: null,
    spaceCode: null,
    spaceName: null,
    buildingId: null,
    floorId: null,
    spaceType: 'normal',
    spaceStatus: 0,
    positionX: null,
    positionY: null,
    positionZ: null,
    deviceId: null,
    isOnline: 1,
    remark: null
  }
  if (spaceFormRef.value) {
    spaceFormRef.value.resetFields()
  }
}

// 获取楼层车位
function getFloorSpaces(floorId) {
  return floorSpaces.value.filter(space => space.floor_id === floorId)
}

// 点击车位
function handleSpaceClick(space) {
  if (space.space_status === 1) {
    ElMessage.info(`车位 ${space.space_code} 已被 ${space.license_plate} 占用`)
  }
}

// 加载统计数据
async function loadStatistics() {
  try {
    const response = await getParkingStatistics()
    statistics.value = response.data
  } catch (error) {
    console.error('获取统计数据失败', error)
  }
}

// 加载实时数据
async function loadRealtimeData() {
  try {
    const response = await getRealtimeData()
    const data = response.data
    recentEntries.value = data.recentEntries || []
    recentExits.value = data.recentExits || []
    floorSpaces.value = data.floorSpaces || []
  } catch (error) {
    console.error('获取实时数据失败', error)
  }
}

// 启动实时监控
function startMonitor() {
  loadStatistics()
  loadRealtimeData()
  if (monitorTimer.value) {
    clearInterval(monitorTimer.value)
  }
  monitorTimer.value = setInterval(() => {
    loadStatistics()
    loadRealtimeData()
  }, 10000) // 每10秒刷新一次
}

// 生成报表
async function generateReport() {
  try {
    const response = await getParkingReport(reportQuery)
    reportData.value = response.data.details || []
    ElMessage.success('报表生成成功')
  } catch (error) {
    ElMessage.error('生成报表失败')
  }
}

// 初始化数据
function initData() {
  buildingList.value = [
    {id: 'B1', name: 'A栋'},
    {id: 'B2', name: 'B栋'},
    {id: 'B3', name: 'C栋'}
  ]

  floorList.value = [
    {id: 'B1', name: 'B1层'},
    {id: 'B2', name: 'B2层'},
    {id: 'F1', name: '1层'}
  ]

  currentFloors.value = [
    {id: 'B1', name: 'B1层'},
    {id: 'B2', name: 'B2层'}
  ]
}

// 监听标签页切换
let watchActiveTab = null
onMounted(() => {
  initData()
  getSpaceList()

  watchActiveTab = () => {
    if (activeTab.value === 'monitor') {
      startMonitor()
    } else if (monitorTimer.value) {
      clearInterval(monitorTimer.value)
    }
  }
})

onUnmounted(() => {
  if (monitorTimer.value) {
    clearInterval(monitorTimer.value)
  }
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.mb8 {
  margin-bottom: 8px;
}

.statistics-row {
  margin-bottom: 20px;
}

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

.parking-map {
  padding: 20px;
}

.floor-section {
  margin-bottom: 30px;
}

.floor-section h4 {
  margin-bottom: 15px;
  font-size: 16px;
  font-weight: bold;
}

.parking-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
  gap: 10px;
}

.parking-space {
  border: 2px solid #dcdfe6;
  border-radius: 4px;
  padding: 10px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s;
  background-color: #f5f7fa;
}

.parking-space:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.parking-space.status-0 {
  background-color: #f0f9ff;
  border-color: #67c23a;
}

.parking-space.status-1 {
  background-color: #fdf6ec;
  border-color: #e6a23c;
}

.parking-space.status-2 {
  background-color: #f4f4f5;
  border-color: #909399;
}

.parking-space.status-3 {
  background-color: #fef0f0;
  border-color: #f56c6c;
}

.space-number {
  font-weight: bold;
  font-size: 14px;
  margin-bottom: 5px;
}

.space-info {
  font-size: 12px;
  color: #606266;
}

.report-container {
  padding: 20px;
}

.dialog-footer {
  text-align: right;
}
</style>