<template>
  <div class="static-container">

    <div class="search-row">
      <el-date-picker v-model="filterParams.timeAfter" :teleported="false" type="datetime" placeholder="请选择开始时间"
        prefix-icon="CaretBottom" popper-class="popperClass"></el-date-picker>
      <el-date-picker v-model="filterParams.timeBefore" :teleported="false" type="datetime" placeholder="请选择结束时间"
        prefix-icon="CaretBottom" popper-class="popperClass"></el-date-picker>
      <el-button type="primary" @click="handleFilter" class="alert-bt">查询</el-button>
      <el-button type="primary" @click="handleReset" class="alert-bt">清空</el-button>
    </div>

    <div class="second-row">
      <el-row class="top-part">
        <el-col :sm="24" :md="6">
          <div class="camera-stats">
            <div id="camera-chart-container" class="camera-status-chart"></div>
          </div>
        </el-col>
        <el-col :sm="24" :md="6">
          <div class="event-stats">
            <div id="event-chart-container" class="event-status-chart"></div>
          </div>
        </el-col>
        <el-col :sm="24" :md="12">
          <div class="part-three">
            <AlertChart />
          </div>
        </el-col>
        <!-- <el-col :sm="24" :md="6" >
          <div class="part-four">
            
          </div>
        </el-col> -->
      </el-row>

      <el-row class="bottom-part">
        <el-col :span="24">
          <div class="bottom-row">
            <div id="code-chart-container" class="code-status-chart"></div>
          </div>
        </el-col>
      </el-row>
    </div>







    <!-- <el-row>
      <el-col :span="24">
        <div class="statistics-container">
          <p v-for="(name, code) in typeMapping" :key="code">
            {{ name }}: {{ typeCounts[code] || 0 }} 次
          </p>
        </div>
      </el-col>
    </el-row> -->

    <!--<p v-for="(name, code) in typeMapping" :key="code">
          {{ name }}: 总数 {{ typeCounts[code]?.total || 0 }} 次, 处理中 {{ typeCounts[code]?.pending || 0 }} 次, 已处理 {{
        typeCounts[code]?.closed || 0 }} 次
        </p> -->
    <!-- 摄像总数{{ cameraCount }}
        摄像在线{{ cameraOnlineCount }}
        摄像离线{{ cameraOfflineCount }}
        事件总数{{ eventCount }}
        处理中{{ pendingEventCount }}
        已处理{{ closedEventCount }} -->
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onBeforeUnmount, computed } from 'vue';
import { BoxApi } from '@/utils/boxApi.ts';
import * as echarts from 'echarts';
import AlertChart from '@/components/AlertChart.vue';

const apiInstance = new BoxApi();
const typeMapping = reactive({});
const typeCounts = reactive({});
const filterParams = reactive({
  timeAfter: null,
  timeBefore: null,
});

const xData = ref([]);
const totalData = ref([]);
const pendingData = ref([]);

const cameraCount = ref(0);
const cameraOfflineCount = ref(0);
const cameraOnlineCount = ref(0);

const eventCount = ref(0);
const pendingEventCount = ref(0);
const closedEventCount = ref(0);

const formatDateTimeToISO = (datetime) => {
  return new Date(datetime).toISOString().replace('.000', '');
};

const handleReset = () => {
  // filterParams.types = null;
  filterParams.timeAfter = null;
  filterParams.timeBefore = null;
  // filterParams.cameraId = null;
  // filterParams.status = null;
  handleFilter();
};

const formatDateTime = (datetime) => {
  const date = new Date(datetime);
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, '0');
  const day = date.getDate().toString().padStart(2, '0');
  const hours = date.getHours().toString().padStart(2, '0');
  const minutes = date.getMinutes().toString().padStart(2, '0');
  const seconds = date.getSeconds().toString().padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};


const fetchAllCounts = async (timeAfter, timeBefore) => {
  try {
    const token = localStorage.getItem('alertToken');
    const totalResponse = await apiInstance.getEventsByParams(token, 1, 1, timeBefore, timeAfter);
    eventCount.value = totalResponse.count;

    // const pendingResponse = await apiInstance.getEventsByParams(token, 1, 1, timeBefore, timeAfter, null, null, 'pending');
    // pendingEventCount.value = pendingResponse.count;
    const { count: pendingCount } = await apiInstance.getEventsByParams(token, 1, 1, timeBefore, timeAfter, null, null, 'pending');
    pendingEventCount.value = pendingCount;


    const closedResponse = await apiInstance.getEventsByParams(token, 1, 1, timeBefore, timeAfter, null, null, 'closed');
    closedEventCount.value = closedResponse.count;
  } catch (error) {
    console.error('Error fetching all counts:', error);
  }
};



const fetchCameras = async () => {
  try {
    const token = localStorage.getItem('alertToken');
    const limit = 20;
    let offset = 0;
    let allCameras = [];

    const firstResponse = await apiInstance.getCameras(limit, offset, token);
    cameraCount.value = firstResponse.count;
    // console.log("总数》》》》》》》》》》》》》", cameraCount.value)
    allCameras = firstResponse.results;


    const total = cameraCount.value;
    while (offset + limit < total) {
      offset += limit;
      const response = await apiInstance.getCameras(limit, offset, token);
      allCameras = allCameras.concat(response.results);
    }

    allCameras.forEach((camera) => {
      if (camera.status === 'online') {
        cameraOnlineCount.value++;
      } else if (camera.status === 'offline') {
        cameraOfflineCount.value++;
      } else {
        exceptionCount.value++;
      }
    });
  } catch (error) {
    console.error('Error fetching cameras:', error);
  }
};


// 获取告警类型并初始化每种类型的count
const fetchTypeMapping = async (token) => {
  try {
    const algorithms = await apiInstance.getAlgorithms(token);
    const additionalMappings = [{ code_name: 'minizawu:532', name: '杂物堆积' }];

    algorithms.forEach((algorithm) => {
      typeMapping[algorithm.code_name] = algorithm.name;
      typeCounts[algorithm.code_name] = { total: 0, pending: 0, closed: 0 };
    });

    additionalMappings.forEach((item) => {
      typeMapping[item.code_name] = item.name;
      typeCounts[item.code_name] = { total: 0, pending: 0, closed: 0 };
    });
  } catch (error) {
    console.error("Error fetching algorithms:", error);
  }
};

const fetchTypeCounts = async (timeAfter, timeBefore) => {
  const token = localStorage.getItem('alertToken');
  const tempCounts = []; // 临时数组用于存储类型和总数

  // 清空数据以确保每次查询更新时数据正确
  xData.value = [];
  totalData.value = [];
  pendingData.value = [];

  // 遍历每种类型，根据 code_name 获取总数
  for (const code in typeMapping) {
    try {
      const { count: totalCount } = await apiInstance.getEventsByParams(token, 1, 1, timeBefore, timeAfter, code);
      tempCounts.push({ code, name: typeMapping[code], total: totalCount });
    } catch (error) {
      console.error(`Error fetching total count for type ${code}:`, error);
      tempCounts.push({ code, name: typeMapping[code], total: 0 }); // 如果有错误，默认总数为 0
    }
  }

  // 根据总数降序排序
  tempCounts.sort((a, b) => b.total - a.total);

  // 更新 xData、totalData 和 pendingData 按排序后的顺序
  xData.value = tempCounts.map(item => item.name); // 排序后的名称顺序
  totalData.value = tempCounts.map(item => item.total); // 排序后的总数顺序

  // 获取每种类型的处理中数量，并按排序顺序赋值到 pendingData
  for (const item of tempCounts) {
    try {
      const { count: pendingCount } = await apiInstance.getEventsByParams(token, 1, 1, timeBefore, timeAfter, item.code, null, 'pending');
      pendingData.value.push(pendingCount);
    } catch (error) {
      console.error(`Error fetching pending count for type ${item.code}:`, error);
      pendingData.value.push(0); // 如果有错误，默认处理中数量为 0
    }
  }
};

const handleFilter = async () => {
  const timeAfter = filterParams.timeAfter ? formatDateTimeToISO(filterParams.timeAfter) : null;
  const timeBefore = filterParams.timeBefore ? formatDateTimeToISO(filterParams.timeBefore) : null;

  console.log('timeAfter:', timeAfter);
  await fetchTypeCounts(timeAfter, timeBefore);
  await fetchAllCounts(timeAfter, timeBefore);


  renderChart();
  renderCameraChart();
  renderEventChart();
};


const renderCameraChart = () => {
  const chartDom = document.getElementById('camera-chart-container');
  const chart = echarts.init(chartDom);

  const chartData = { ONE: cameraOnlineCount.value, TWO: cameraOfflineCount.value, num: cameraCount.value };
  const seriesData = [];
  const legendData = [];
  const nameList = [
    { key: 'ONE', text: '在线', color: '#243eff' },
    { key: 'TWO', text: '离线', color: '#2490ff' },
    // { key: 'num', text: '总数' },
  ];

  nameList.forEach((item) => {
    seriesData.push({
      value: chartData[item.key],
      name: item.text,
      itemStyle: { color: item.color },
    });
    legendData.push(item.text); // 直接添加到 legendData 数组中
  });

  const option = {
    backgroundColor: '#001529',
    tooltip: {
      trigger: 'item',
      formatter: ({ name, value, percent }) => {
        const color = nameList.find((item) => item.text === name).color;
        return `<span style="color:${color};">●</span> ${name} 数量: ${value}<br><span style="color:${color};">●</span> ${name} 比例: ${percent}%`;
      },
    },
    legend: {
      orient: 'vertical', // 设置纵向排列
      top: '8%',
      left: '10%',
      textStyle: {
        color: '#fff',
        fontSize: 14,
      },
      icon: 'circle',
      data: legendData, // 使用 legendData 数组作为数据
      formatter: (name) => {
        const item = nameList.find((n) => n.text === name);
        return `${name} ${chartData[item.key] || 0}`;
      },
      rich: nameList.reduce((acc, item) => {
        acc[item.key] = {
          color: item.color,
          fontSize: 14,
        };
        return acc;
      }, {}),
    },
    color: ['#243eff', '#2490ff', '#30f3e3'],
    series: [
      {
        name: '摄像头状态',
        type: 'pie',
        center: ['50%', '60%'],
        radius: ['40%', '50%'],
        itemStyle: {
          borderRadius: 10,
        },
        label: {
          show: true,
          position: 'center',
          color: '#fff',
          fontSize: 15,
          formatter: () => `摄像状态`,
        },
        labelLine: { show: false },
        data: seriesData,
      },
    ],
  };

  chart.setOption(option);
};

const renderEventChart = () => {
  const chartDom = document.getElementById('event-chart-container');
  const chart = echarts.init(chartDom);

  const chartData = { ONE: pendingEventCount.value, TWO: closedEventCount.value, num: eventCount.value };
  const seriesData = [];
  const legendData = [];
  const nameList = [
    { key: 'ONE', text: '处理中', color: '#243eff' },
    { key: 'TWO', text: '已处理', color: '#2490ff' },
  ];

  nameList.forEach((item) => {
    seriesData.push({
      value: chartData[item.key],
      name: item.text,
      itemStyle: { color: item.color },
    });
    legendData.push(item.text);
  });

  const option = {
    backgroundColor: '#001529',
    color: ['#243eff', '#2490ff', '#30f3e3'],
    tooltip: {
      trigger: 'item',
      formatter: ({ name, value, percent }) => {
        const color = nameList.find((item) => item.text === name).color;
        return `<span style="color:${color};">●</span> ${name} 数量: ${value}<br><span style="color:${color};">●</span> ${name} 比例: ${percent}%`;
      }
    },
    legend: {
      orient: 'vertical',
      top: '5%',
      left: '10%',
      textStyle: {
        color: '#fff',
        fontSize: 14,
      },
      icon: 'circle',
      data: legendData,
      formatter: (name) => {
        const item = nameList.find((n) => n.text === name);
        return `${name} ${chartData[item.key] || 0}`;
      }
    },
    rich: nameList.reduce((acc, item) => {
      acc[item.key] = {
        color: item.color,
        fontSize: 14,
      };
      return acc;
    }, {}),
    series: [
      {
        name: '',
        type: 'pie',
        center: ['50%', '60%'],
        radius: ['40%', '50%'],
        itemStyle: {
          borderRadius: 10,
        },
        label: {
          show: true,
          position: 'center',
          color: '#fff',
          fontSize: 15,
          formatter: () => `事件概览 `,
        },
        labelLine: { show: false },
        data: seriesData,
      },
    ],
  };

  chart.setOption(option);
};



const renderChart = () => {
  const chartDom = document.getElementById('code-chart-container');
  const chart = echarts.init(chartDom);

  const option = {
    backgroundColor: '#001529',
    title: {
      text: ` 算法摄像头分布`,  // 添加标题文本
      left: '2%',       // 设置标题位置为居中
      top: '10%',            // 设置标题距离顶部的位置
      textStyle: {
        color: '#5BFCF4',      // 标题颜色
        fontSize: 16,       // 标题字体大小
      },
    },
    grid: {
      top: '10%',
      left: '10%',
      bottom: '5%',
      right: '5%',
      containLabel: true,
    },
    tooltip: {
      trigger: 'item',
    },
    xAxis: [
      {
        type: 'category',
        data: xData.value, // 使用排序后的 xData
        axisTick: { alignWithLabel: true },
        axisLine: { show: false },
        axisLabel: { textStyle: { color: '#ddd' }, margin: 30 },
      },
    ],
    yAxis: [
      {
        show: false,
        type: 'value',
      },
    ],
    series: [
      {
        name: '上部圆 - 总数',
        type: 'pictorialBar',
        silent: true,
        symbolSize: [40, 10],
        symbolOffset: [0, -6],
        symbolPosition: 'end',
        z: 12,
        label: {
          show: true,
          position: 'top',
          fontSize: 15,
          fontWeight: 'bold',
          color: '#5BFCF4',
        },
        color: '#5BFCF4',
        data: totalData.value,
      },
      {
        name: '底部圆 - 处理中',
        type: 'pictorialBar',
        silent: true,
        symbolSize: [40, 10],
        symbolOffset: [0, 7],
        z: 12,
        color: '#FE9C5A',
        data: pendingData.value,
      },
      {
        name: '内层波浪',
        type: 'pictorialBar',
        silent: true,
        symbolSize: [50, 15],
        symbolOffset: [0, 12],
        z: 10,
        itemStyle: {
          color: 'transparent',
          borderColor: '#5BFCF4',
          borderWidth: 8,
        },
        data: totalData.value,
      },
      {
        name: '外层波浪',
        type: 'pictorialBar',
        silent: true,
        symbolSize: [70, 20],
        symbolOffset: [0, 18],
        z: 10,
        itemStyle: {
          color: 'transparent',
          borderColor: 'rgba(91,252,244,0.5)',
          borderWidth: 5,
        },
        data: totalData.value,
      },
      {
        name: '设备数量 - 总数',
        type: 'bar',
        barWidth: '40',
        barGap: '10%',
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 0.7, [
            { offset: 0, color: 'rgba(210,210,210,0.3)' },
            { offset: 1, color: '#5BFCF4' },
          ]),
          opacity: 0.8,
        },
        data: totalData.value,
      },
      {
        name: '告警数量 - 处理中',
        type: 'bar',
        barWidth: 40,
        z: 12,
        barGap: '-100%',
        itemStyle: {
          opacity: 0.7,
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#EB3B5A' },
            { offset: 1, color: '#FE9C5A' },
          ]),
        },
        data: pendingData.value,
      },
      {
        name: '上部圆 - 总数',
        type: 'pictorialBar',
        silent: true,
        symbolSize: [40, 10],
        symbolOffset: [0, -6],
        symbolPosition: 'end',
        z: 12,
        color: '#5BFCF4',
        data: totalData.value,
      },
      {
        name: '底部圆 - 处理中',
        type: 'pictorialBar',
        silent: true,
        symbolSize: [40, 10],
        symbolOffset: [0, 7],
        z: 12,
        color: '#FE9C5A',
        data: pendingData.value,
      },
    ],
  };

  chart.setOption(option);
};




onMounted(async () => {
  const token = localStorage.getItem('alertToken');


  await fetchTypeMapping(token);
  await fetchTypeCounts();
  await fetchAllCounts();
  await fetchCameras();

  renderChart();
  renderCameraChart();
  renderEventChart();

  window.addEventListener('resize', () => echarts.getInstanceByDom(document.getElementById('chart-container')).resize());
});

onBeforeUnmount(() => {
  window.removeEventListener('resize', () => echarts.getInstanceByDom(document.getElementById('chart-container')).resize());
});
</script>

<style scoped>
.static-container {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  background-color: #001529;
  /* background: linear-gradient(to right bottom, rgb(0, 21, 41), rgba(3, 55, 153, 0.3)); */
  /* background: repeating-radial-gradient(circle, rgb(7, 7, 7), rgba(14, 14, 211, 0.5) 20px, rgba(3, 0, 151, 0.979) 100px); */
  /* background: repeating-linear-gradient(45deg, rgba(0, 21, 41, 0.9), rgba(12, 203, 209, 0.5) 20px); */
  /* background: 
  radial-gradient(circle at 0% 0%, rgba(0, 21, 41,1), rgba(12, 203, 209, 0.2)),
  radial-gradient(circle at 100% 100%, rgba(12, 203, 209, 0.3), rgba(0, 21, 41, 1)),
  radial-gradient(circle at top left, rgba(255, 255, 255, 0.5), transparent); */

  /* box-sizing: border-box; */
}

.search-row {
  width: 82vw;
  display: flex;
  flex-direction: row;
  align-items: center;
  height: 15vh;
  /* background-color: #4587dd; */
   background: repeating-linear-gradient(-45deg, rgba(0, 21, 41), rgba(58, 61, 214, 0.3) 100px);
  gap: 1vw;
  padding: 0 2vw;
  margin: 2vh 0vw 2vh 3vw;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.3);
  border-radius: 8px;
}

.second-row {
  /* display: flex; */
  /* flex-direction: column; */
  /* align-items: center; */
  /* gap: 10px; */
  padding: 0;
  box-sizing: border-box;
  margin-left: 3vw;
  width: 86vw;
  height: 70vh;
  border-radius: 10px;
  background-color: #001529;

}

.top-part {
  margin-left: 1vw;
  height: 30vh;
  /* border: solid 1px #70ce18; */
}

.camera-status-chart,
.event-status-chart {
  height: 30vh;
  width: 20vw;
  padding: 0;
  margin: 1vh 0vw 0 0vw;
  padding: 0;
  border: none;
  /* border: solid 1px #ce1827; */
}

.part-three,
.part-four {
  height: 30vh;
  width: 41vw;
  /* padding: 2px 0; */
  margin: 1vh 0vw 0 0;
  /* border: solid 1px #a418ce; */
  /* margin: 1vh 1vw 0 0; */
}

/* .event-status-chart{
  height: 30vh;
  width: 24vw;
  padding: 0;
  margin: 1vh 1vh 0 0;
} */

.camera-stats,
.event-stats {
  padding: 0;
  margin: 0;
  background-color: #001529;
  border: none;
}

/* .bottom-part{
  box-sizing: border-box;
  height: 45vh;
  width: 86vw;

} */

.bottom-row {
  /* margin: 10px; */

}



.code-status-chart {
  width: 84vw;
  height: 40vh;
  padding: 0vh 1vw 0 1vw;
  /* margin: 0vh 1vw; */
}
</style>
