<template>
  <scroll-seamless :list="list" title="查获通道分布">
    <template #thead>
      <span class="item"></span>
      <span v-for="item in itemNameList" :key="item.channelCode" class="item">
        {{ item.label }}<br />（{{ item.total }}）
      </span>
      <span class="item total">总数</span>
    </template>
    <template #default="{ row, index }">
      <span class="item">{{ row.channelName }}</span>
      <span v-for="(item, index) in row.item" :key="index" :class="{ num1: item.total < 15, num2: item.total > 15 }"
        class="item num">
        {{ item.total }}
      </span>
      <span class="item total">{{ row.totalQuantity }}</span>
    </template>
  </scroll-seamless>
</template>

<script setup>
import { onMounted, ref } from 'vue';
import { executeSqlByKeyAndParam } from '@/api/system/sql.js';
import ScrollSeamless from '@/views/dataBigScreen/dashboard/components/ScrollSeamless.vue';
import { getChannel } from "@/api/largeScreen/largeScreen.js"
import { treeSelectByType } from "@/api/system/common.js"



let itemNameList = ref([]);
let tabData = ref([])
let list = ref([]);
const pollingInterval = ref(null);
onMounted(() => {
  // fetchData()
  pollingInterval.value = setInterval(fetchData(), 5000);
});
function fetchData() {
  treeSelectByType("ITEM_CATEGORY", 1).then(res => {
    tabData.value = res.data
  })
  getChannel().then(res => {
    const resultMap = {};

    let newArr = []
    res.data.forEach(item => {
      const { categoryCode, total } = item;
      tabData.value.forEach(it => {
        const { code, label, id } = it
      

        if (categoryCode == id) {
          newArr.push(item)
        }
        if (!resultMap[id] && categoryCode == id) {


          resultMap[id] = {
            id,
            label,
            total
          };
        } else {

          if (resultMap[id]) {
            resultMap[id].total = id == categoryCode ? resultMap[id].total + total : resultMap[id].total;
          }
        }
        // if (id == 10 && categoryCode == 10) {
        //   console.log("锐器")
        //   debugger

        // }


      })
    });
    itemNameList.value = Object.values(resultMap);

    const groupedData = newArr.reduce((acc, item) => {
      const key = item.channelName;
      if (!acc[key]) {
        acc[key] = {
          channelName: key,
          categoryCode: item.categoryCode,
          item: [],
        };
      }
      itemNameList.value.map((ite, index) => {
        if (item.categoryCode == ite.id) {
          acc[key].item[index] = item
        } else if (acc[key].item[index]) {
          acc[key].item[index] = acc[key].item[index]
        } else {
          acc[key].item[index] = { total: 0 }
        }
      })
      // 只添加需要的字段
      // const existingChannel = acc[key].item.find(
      //   ch => {
      //     ch.channelCode === item.channelCode
      //   },
      // );
      // if (!existingChannel) {
      //   acc[key].item.push(item);
      // } else {y，可累加
      //   existingChannel.total += item.total;
      //   // 可选：如果需要合并同 channel 的 quantit
      // }
      acc[key].totalQuantity = acc[key].item.reduce((acc, item) => acc + item.total, 0);
      return acc;
    }, {});
  

    // 转换为数组格式
    list.value = Object.values(groupedData).map(el => {
      if (el.item.length !== itemNameList.value.length) {
        el.item.push(...new Array(Math.max(0, itemNameList.value.length - el.item.length)).fill({ total: 0 }));
      }
      return el;
    });

  }).catch(error => {
    console.error(error);
    clearInterval(pollingInterval.value);
  });
  return fetchData
}
</script>

<style lang="less" scoped>
.item {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: calc(18% - 4px);
  white-space: nowrap;
  height: 28px;
  margin: 2px;
  overflow: hidden;

  &.total {
    width: 10%;
  }
}

.channel-distribution {
  position: relative;
  height: calc(100% - 50px);
  overflow: hidden;
}

.channel-distribution-thead,
.channel-distribution-tbody {
  display: flex;
  justify-content: center;
  align-items: center;

  span {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    color: #fbffff;
    font-size: 12px;
    width: calc(16.66% - 4px);
    white-space: nowrap;
    height: 28px;
    margin: 2px;
  }
}

.num {
  display: inline-flex;
  background: #bbe1ff;
  padding: 2px;

  &.num1 {
    background: #7daaff;
  }

  &.num2 {
    background: #3d76dd;
  }
}
</style>