<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="80px">
      <el-form-item label="设备" prop="deviceCode">
        <el-select
            v-model="queryParams.deviceCode"
            placeholder="请选择设备"
            clearable
            filterable
            style="width: 200px"
        >
          <el-option
              v-for="device in deviceOptions"
              :key="device.device_code"
              :label="device.device_name"
              :value="device.device_code"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="区域" prop="areaId">
        <el-select
            v-model="queryParams.areaId"
            placeholder="请选择区域"
            clearable
            style="width: 150px"
        >
          <el-option
              v-for="area in areaOptions"
              :key="area.value"
              :label="area.label"
              :value="area.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="楼栋" prop="buildingId">
        <el-select
            v-model="queryParams.buildingId"
            placeholder="请选择楼栋"
            clearable
            style="width: 150px"
        >
          <el-option
              v-for="building in buildingOptions"
              :key="building.value"
              :label="building.label"
              :value="building.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="时间范围" prop="timeRange">
        <el-date-picker
            v-model="queryParams.timeRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 350px"
        />
      </el-form-item>
      <el-form-item label="统计类型" prop="statType">
        <el-select v-model="queryParams.statType" placeholder="请选择" style="width: 120px">
          <el-option label="实时" value="realtime" />
          <el-option label="小时" value="hourly" />
          <el-option label="日" value="daily" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="dataList" stripe border>
      <el-table-column label="时间" align="center" prop="stat_time">
        <template #default="scope">
          <span>{{ parseTime(scope.row.stat_time, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="设备名称" align="center" prop="device_name" />
      <el-table-column label="区域" align="center" prop="area_name" />
      <el-table-column label="楼栋" align="center" prop="building_name" />
      <el-table-column label="楼层" align="center" prop="floor_name" />
      <el-table-column label="进入人数" align="center" prop="enter_count" />
      <el-table-column label="离开人数" align="center" prop="exit_count" />
      <el-table-column label="当前人数" align="center" prop="current_count" />
      <el-table-column label="峰值人数" align="center" prop="peak_count" />
      <el-table-column label="占用率" align="center" prop="occupancy_rate">
        <template #default="scope">
          <span>{{ scope.row.occupancy_rate }}%</span>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- ECharts图表 -->
    <div class="chart-container">
      <div ref="flowChart" style="height:500px; margin-top:20px;"></div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import * as echarts from 'echarts'
import { listFlowData, exportFlowData, listFlowDevices } from '@/api/subsystem/peopleflow'

const { proxy } = getCurrentInstance()
const flowChart = ref(null)
let chartInstance = null

const loading = ref(false)
const showSearch = ref(true)
const total = ref(0)
const dataList = ref([])
const deviceOptions = ref([])
const areaOptions = ref([
  { value: 'A', label: 'A区' },
  { value: 'B', label: 'B区' },
  { value: 'C', label: 'C区' }
])
const buildingOptions = ref([
  { value: 'B1', label: '研发楼' },
  { value: 'B2', label: '办公楼' },
  { value: 'B3', label: '实验楼' }
])

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  deviceCode: null,
  areaId: null,
  buildingId: null,
  timeRange: [],
  statType: 'realtime'
})

/** 查询设备列表 */
function getDeviceOptions() {
  listFlowDevices().then(response => {
    deviceOptions.value = response.data
  })
}

/** 查询客流数据列表 */
function getList() {
  loading.value = true
  // 处理时间范围参数
  const params = {
    ...queryParams,
    pageNum: queryParams.pageNum,
    pageSize: queryParams.pageSize
  }

  if (queryParams.timeRange && queryParams.timeRange.length === 2) {
    params.beginTime = queryParams.timeRange[0]
    params.endTime = queryParams.timeRange[1]
  }

  listFlowData(params).then(response => {
    dataList.value = response.rows
    total.value = response.total
    loading.value = false

    // 渲染图表
    nextTick(() => {
      renderChart()
    })
  })
}

/** 渲染图表 */
function renderChart() {
  if (!flowChart.value) return

  if (!chartInstance) {
    chartInstance = echarts.init(flowChart.value)
  }

  // 准备图表数据
  const timeData = []
  const enterData = []
  const exitData = []
  const currentData = []

  dataList.value.forEach(item => {
    timeData.push(item.stat_time)
    enterData.push(item.enter_count)
    exitData.push(item.exit_count)
    currentData.push(item.current_count)
  })

  const option = {
    title: {
      text: '客流统计趋势',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['进入人数', '离开人数', '当前人数'],
      bottom: 10
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '12%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: timeData
    },
    yAxis: {
      type: 'value',
      name: '人数'
    },
    series: [
      {
        name: '进入人数',
        type: 'line',
        data: enterData,
        smooth: true,
        lineStyle: {
          color: '#5470C6'
        }
      },
      {
        name: '离开人数',
        type: 'line',
        data: exitData,
        smooth: true,
        lineStyle: {
          color: '#91CC75'
        }
      },
      {
        name: '当前人数',
        type: 'line',
        data: currentData,
        smooth: true,
        lineStyle: {
          color: '#EE6666'
        }
      }
    ]
  }

  chartInstance.setOption(option)
  window.addEventListener('resize', () => chartInstance.resize())
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm('queryRef')
  queryParams.pageNum = 1
  handleQuery()
}

/** 导出按钮操作 */
function handleExport() {
  const params = {
    ...queryParams,
    pageNum: undefined,
    pageSize: undefined
  }

  if (queryParams.timeRange && queryParams.timeRange.length === 2) {
    params.beginTime = queryParams.timeRange[0]
    params.endTime = queryParams.timeRange[1]
  }

  proxy.$modal.confirm('确认导出客流统计数据吗？').then(() => {
    exportFlowData(params).then(response => {
      proxy.download(response.msg)
    })
  })
}

onMounted(() => {
  // 设置默认时间范围为当天
  const now = new Date()
  const start = new Date(now.getFullYear(), now.getMonth(), now.getDate())
  const end = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59, 59)

  queryParams.timeRange = [
    // parseTime(start, '{y}-{m}-{d} 00:00:00'),
    // parseTime(end, '{y}-{m}-{d} 23:59:59')
  ]

  getDeviceOptions()
  getList()
})
</script>

<style scoped>
.chart-container {
  position: relative;
  width: 100%;
  margin-top: 20px;
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
</style>