<template>
  <div class="home">
    <div class="map" id="map"></div>
    <div class="event-tips">
      <div class="event-tips-row">
        <span>总事件数：</span>
        <span>{{ totalEvents }}</span>
      </div>
      <div class="event-tips-row">
        <span>重点事件数：</span>
        <span>{{ importantEvents }}</span>
      </div>
      <div class="event-tips-row">
        <span>待处理：</span>
        <span>{{ unprocessedEvents }}</span>
      </div>
    </div>
    <div class="event-image">
      <div class="block" v-for="item, index in mediaList" :key="index">
        <div class="image-tips">
            <div>{{item.pointName}}</div>
            <div>{{item.createTime}}</div>
        </div>
        <el-image :src="item.imgUrl" />
      </div>
    </div>
    <div class="left-part">
      <el-card>
        <template #header>
          <span>实时事件</span>
        </template>
        <el-table :data="eventData">
          <el-table-column prop="eventName" show-overflow-tooltip width="90" label="事件名称" />
          <el-table-column prop="pointName" show-overflow-tooltip label="点位名称" />
          <el-table-column prop="time" show-overflow-tooltip label="时间" />
        </el-table>
      </el-card>
      <el-card style="margin-top: 10px;">
        <template #header>
          <div class="event-category">
            <span>重点事件分类统计</span>
            <el-radio-group v-model="eventDateType" @change="getImportantEvents" size="small">
              <el-radio-button label="今天" value="1" />
              <el-radio-button label="近7天" value="7" />
              <el-radio-button label="近30天" value="30" />
            </el-radio-group>
          </div>
        </template>
        <BaseChart width="100%" height="300px" :option="pieOptions" />
      </el-card>
    </div>
    <div class="right-part">
      <el-card>
        <template #header>
          <div class="event-category">
            <span>重点路段流量分析</span>
          </div>
        </template>
        <BaseChart width="100%" height="200px" :option="lineOptions" />
      </el-card>
      <el-card style="margin-top: 10px;">
        <template #header>
          <div class="event-category">
            <span>机占非TOP10</span>
            <el-radio-group v-model="motorInLanesDate" @change="getMotorInLanesTop10" size="small">
              <el-radio-button label="今天" value="1" />
              <el-radio-button label="近7天" value="7" />
              <el-radio-button label="近30天" value="30" />
            </el-radio-group>
          </div>
        </template>

        <div class="custom-progress">
          <div class="progress-item" v-for="(item, index) in progressData" :key="index">
            <div class="rank-num" :style="{ background: item.color }">{{ index + 1 }}</div>
            <div class="rank-name" :style="{ color: item.color }">{{ item.name }}</div>
            <el-progress :stroke-width="12" :color="item.color" :percentage="50">
              <el-button text>{{ item.num }}</el-button>
            </el-progress>
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>
<script lang="ts" setup>
import BaseChart from '@/components/BaseChart/index.vue'
import monitorIcon from '@/assets/images/monitor.svg'
import { eventsCount, importantEventsStat, motorInLanesTop10, eventsMediaList } from '@/api/sense/events'
import { lineCharts } from '@/api/sense/flowDetail/index'
import { getListByAreaTree } from '@/api/manage/monitorPoint/index'
const bdmap = ref(null);
const marks = ref([]);
const totalEvents = ref<String | Number>(null);
const importantEvents = ref<String | Number>(null);
const unprocessedEvents = ref<String | Number>(null);
const eventData = ref([])
const eventDateType = ref('1')
const motorInLanesDate = ref('1')
const importatEvents = ref([])
const lineData = ref([])
const mediaList = ref([])
const imgSuffix = import.meta.env.VITE_APP_FILEPATH
const pieOptions = computed(() => {
  let options = {
    tooltip: {
      trigger: 'item'
    },
    legend: {
      orient: 'horizontal',
      left: 'left',
      itemWidth: 10,
      itemHeight: 10,
      itemGap: 5
    },
    series: [
      {
        type: 'pie',
        radius: '50%',
        data: importatEvents.value,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  };
  return options
})
const lineOptions = computed(() => {
  const dates = [];
  const pointNames = {};
  lineData.value.forEach((item) => {
    dates.push(item.date);
    if (!pointNames[item.point_name]) {
      pointNames[item.point_name] = [];
    }
    pointNames[item.point_name].push(item.daily_vehicle_count);
  });
  const options = {
    tooltip: {
      trigger: 'axis',
      appendToBody: true
    },
    legend: {
      data: Object.keys(pointNames)
    },
    grid: {
      left: 0,
      right: '6%',
      bottom: 0,
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: [...new Set(dates)]
    },
    yAxis: {
      type: 'value'
    },
    series: Object.keys(pointNames).map((pointName) => {
      return {
        name: pointName,
        type: 'line',
        symbol: 'circle', // 默认是空心圆（中间是白色的），改成实心圆
        showAllSymbol: true,
        symbolSize: 0,
        data: pointNames[pointName]
      };
    })
  };
  return options
})
const progressData = ref([])
onMounted(() => {
  var map = new BMapGL.Map("map"); // 创建地图实例
  var point = new BMapGL.Point(118.879999, 32.016216); // 创建点坐标
  map.centerAndZoom(point, 14);
  map.enableScrollWheelZoom(true);
  bdmap.value = map;
  getEventCount();
  getAreaTree(100);
  getImportantEvents()
  getMotorInLanesTop10()
  getLineChart()
  getLatestEventMeida()
});
const getAreaTree = (areaId) => {
  getListByAreaTree({ areaId }).then(({ code, data }) => {
    if (code === 200) {
      marks.value = data
      showMarks()
    }
  })
}
const showMarks = () => {
  bdmap.value.clearOverlays();
  marks.value.forEach(item => {
    var pt = new BMapGL.Point(Number(item.longitude), Number(item.latitude));
    let icon = new BMapGL.Icon(monitorIcon, new BMapGL.Size(40, 40))
    var marker = new BMapGL.Marker(pt, { icon });
    bdmap.value.addOverlay(marker);
  })
};
const getEventCount = () => {
  eventsCount().then(({ code, data }) => {
    if (code === 200) {
      totalEvents.value = data.totalEvents
      importantEvents.value = data.importantEvents
      unprocessedEvents.value = data.unprocessedEvents
      eventData.value = (data.latestData || []).map(item => ({
        ...item,
        time: item.createTime.substr(11)
      }))
    }
  })
}
const getImportantEvents = () => {
  importantEventsStat({ dateType: eventDateType.value }).then(({ code, data }) => {
    if (code === 200) {
      importatEvents.value = data
    }
  })
}
const getMotorInLanesTop10 = () => {
  motorInLanesTop10({ dateType: motorInLanesDate.value }).then(({ code, data }) => {
    if (code === 200) {
      progressData.value = (data.list || []).map((item, index) => ({
        name: item.pointName,
        percent: item.eventCount / data.totalCount,
        num: item.eventCount,
        color: index < 3 ? '#D9001B' : index < 5 ? '#F59A23' : '#01A7F0'
      }))
    }
  })
}
const getLineChart = () => {
  lineCharts().then(({ code, data }) => {
    if (code === 200) {
      lineData.value = (data || []).map(item => ({
        ...item,
        date: item.date.substr(5)
      }))
    }
  })
}
const getLatestEventMeida = () => {
  eventsMediaList({ pageNum: 1, pageSize: 3 }).then(({ code, rows }) => {
    if (code === 200) {
      mediaList.value = (rows || []).map(item => ({
        pointName: item.pointName,
        createTime: item.createTime,
        imgUrl: item.mediaList.length > 0 ? `${imgSuffix}${item.mediaList[0].filePath}` : ''
      }))
    }
  })
}
</script>
<style lang="scss" scoped>
.home {
  height: 100%;
  background-color: #F0F2F5;
  position: relative;

  .left-part {
    position: absolute;
    width: 28%;
    top: 10px;
    left: 10px;
    z-index: 10;
  }

  .right-part {
    position: absolute;
    top: 10px;
    width: 28%;
    right: 10px;
    z-index: 10;
  }
}

.event-category {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.map {
  width: 100%;
  height: 100%;
}

.custom-progress {
  .progress-item {
    display: flex;
    align-items: center;
    font-size: 12px;

    .rank-num {
      width: 18px;
      height: 18px;
      line-height: 15px;
      border-radius: 50%;
      border: 1px solid;
      text-align: center;
      margin-right: 3px;
      color: #fff;
    }

    .rank-name {
      width: 100px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }

    .el-progress {
      flex: 1;
      flex-shrink: 0;
      margin-left: 10px;

      .el-progress__text .el-button {
        padding: 0 5px;
      }
    }
  }
}

.event-tips {
  position: absolute;
  top: 10px;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  align-items: center;
  z-index: 10;
  background: #fff;
  padding: 15px;
  border-radius: 4px;

  .event-tips-row {
    display: flex;
    align-items: center;
    font-size: 14px;

    &:not(:first-of-type) {
      margin-left: 20px;
    }

    span:first-of-type {
      color: #C9843F;
      font-weight: 500;
    }

    span:last-of-type {
      font-size: 15px;
      color: #00D6E7;
    }
  }
}

.event-image {
  position: absolute;
  bottom: 20px;
  width: 40%;
  height: 150px;
  z-index: 10;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  background: #fff;
  padding: 15px;
  border-radius: 4px;

  .block {
    flex:1;
    position: relative;
    &:not(:first-of-type) {
      margin-left: 10px;
    }
    .image-tips{
      position: absolute;
      left: 5px;
      bottom: 2px;
      color: #fff;
      font-size: 10px;
      z-index: 10;
    }
    .el-image{
      height: 100%;
      width: 100%;
    }
  }
}
</style>
