<script setup lang="ts">
import { watch, onMounted, defineProps } from 'vue';
import { $t } from '@/locales';
import { useAppStore } from '@/store/modules/app';
import { useEcharts } from '@/hooks/common/echarts';
import { api_logCount } from "@/api/index.ts";

defineOptions({
  name: 'LineChart'
});

// 柔和颜色随机
const getRandomColor = () => {
  // 定义艳丽颜色的RGB范围
  const min = 0;
  const max = 255;

  // 生成三个在指定范围内的随机数，分别代表R、G、B
  const r = Math.floor(Math.random() * (max - min + 1)) + min;
  const g = Math.floor(Math.random() * (max - min + 1)) + min;
  const b = Math.floor(Math.random() * (max - min + 1)) + min;

  // 为了确保颜色清新，适当调整色差
  const adjustColor = (color) => {
    if (Math.random() > 0.5) {
      return Math.min(255, color + Math.floor((255 - color) * 0.2));
    } else {
      return Math.max(0, color - Math.floor(color * 0.2));
    }
  };

  const adjustedR = adjustColor(r);
  const adjustedG = adjustColor(g);
  const adjustedB = adjustColor(b);

  // 确保颜色组合舒适自然
  const ensureComfortable = (r, g, b) => {
    // 计算颜色的亮度
    const brightness = (0.299 * r + 0.587 * g + 0.114 * b) / 255;
    // 如果亮度太低或太高，调整其中一个颜色分量
    if (brightness < 0.3) {
      return [Math.min(255, r + 50), g, b];
    } else if (brightness > 0.7) {
      return [Math.max(0, r - 50), g, b];
    }
    return [r, g, b];
  };

  const [finalR, finalG, finalB] = ensureComfortable(adjustedR, adjustedG, adjustedB);

  // 将RGB值转换为16进制字符串
  const hexR = finalR.toString(16).padStart(2, '0');
  const hexG = finalG.toString(16).padStart(2, '0');
  const hexB = finalB.toString(16).padStart(2, '0');

  // 返回带有#前缀的十六进制颜色字符串
  return `#${hexR}${hexG}${hexB}`;
}

const props = defineProps({
  date: {
    type: Array,
    default: () => []
  }
});

watch(props, () => {
  getLogCount();
})

// 获取日志报警的数据
const getLogCount = async () => {


  await api_logCount(props.date).then(res => {
    if (res.data.code === 200) {
      console.log("================= res", res.data.data);
      let data = res.data.data;
      console.log("=================== data", data);
      updateOptions(opts => {
        console.log("========================= opts", opts)
        // opts.series[1].data = [2208, 2016, 2916, 4512, 8281, 2008, 1963, 2367, 2956, 678];
        opts.xAxis.data = data.dateLabel;
        opts.legend.data = data.result.map(item => {
          return {
            icon: 'pin',
            name: item
          }
        });

        opts.series.forEach((item, index) => {
          opts.series[index].data = [];
        });


        const service = (name = (Math.random() * 100).toFixed(0)) => {
          const color = getRandomColor();
          return {
            color,
            name,
            type: 'line',
            smooth: true,
            stack: 'Total',
            areaStyle: {
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [
                  {
                    offset: 0.25,
                    color
                  },
                  {
                    offset: 1,
                    color: '#fff'
                  }
                ]
              }
            },
            emphasis: {
              focus: 'series'
            },
            data: new Array(data[0].countList.length).fill(100)
          };
        }


        data.countLabel.forEach((item, index) => {
          const color = getRandomColor();
          opts.series.push({
            color,
            name: data.result[index],
            type: 'line',
            smooth: true,
            stack: 'Total',
            areaStyle: {
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [
                  {
                    offset: 0.25,
                    color
                  },
                  {
                    offset: 1,
                    color: '#fff'
                  }
                ]
              }
            },
            emphasis: {
              focus: 'series'
            },
            data: item
          })
        })

        // opts.series = new Array(data[0].countList.length).fill(
        //   series
        // );
        //  date 10
        //  countList 17
        //  opts.series[0].data = [0xxx]



        // data.forEach(wrapItem => {
        //   wrapItem.countList.forEach((item, index) => {
        //     opts.series[index].name = item.algorithmName;
        //   })
        // });


        // data[0].countList((item, index) => {
        //   series.data[index] = item.count;
        // })



        console.log("========================= opts", opts.xAxis.data, opts.legend.data)
        return opts;
      })
    }
  })
}

onMounted(() => {
  getLogCount()

  // window.addEventListener('resize', () => {
  //   var width = document.getElementById('main').offsetWidth;
  //           var height = document.getElementById('main').offsetHeight;
  //           myChart.resize({ width: width, height: height });
  //   // getLogCount()
  //   // getLogData();
  //   // getAlarmLog();
  //   // getAlarmLogAll();
  //   // getCameraList();
  //   // getAlarmResultData();
  // })
});

const appStore = useAppStore();

const { domRef, updateOptions } = useEcharts(() => ({
  title: {
    textStyle: {
      color: 'white' // 设置标题文字颜色为白色
    }
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'cross',
      label: {
        backgroundColor: '#6a7985'
      }
    }
  },
  legend: {
    data: [$t('page.home.downloadCount'), $t('page.home.registerCount')],
    textStyle: {
      color: 'white' // 设置图例字体颜色为白色
    },

  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true,
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: [] as string[],
    axisLabel: {
      color: 'white' // 设置 X 轴标签文字颜色为白色
    }
  },
  yAxis: {
    type: 'value',
    axisLabel: {
      color: 'white' // 设置 Y 轴标签文字颜色为白色
    }
  },
  series: [
    {
      color: '#8e9dff',
      name: $t('page.home.downloadCount'),
      type: 'line',
      smooth: true,
      stack: 'Total',
      areaStyle: {
        color: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [
            {
              offset: 0.25,
              color: '#8e9dff'
            },
            {
              offset: 1,
              color: '#fff'
            }
          ]
        }
      },
      emphasis: {
        focus: 'series'
      },
      data: [] as number[]
    },
    {
      color: '#26deca',
      name: $t('page.home.registerCount'),
      type: 'line',
      smooth: true,
      stack: 'Total',
      areaStyle: {
        color: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [
            {
              offset: 0.25,
              color: '#26deca'
            },
            {
              offset: 1,
              color: '#fff'
            }
          ]
        }
      },
      emphasis: {
        focus: 'series'
      },
      data: []
    }
  ]
}));

async function mockData() {
  await new Promise(resolve => {
    setTimeout(resolve, 1000);
  });

  updateOptions(opts => {
    [
      {
        label: "10/15",
        num: 502
      },
    ]
    return opts;
  });
}

function updateLocale() {
  updateOptions((opts, factory) => {
    const originOpts = factory();

    opts.legend.data = originOpts.legend.data;
    opts.series[0].name = originOpts.series[0].name;
    opts.series[1].name = originOpts.series[1].name;

    return opts;
  });
}

async function init() {
  mockData();
}

</script>

<template>
  <!-- <NCard :bordered="false" class="card-wrapper"> -->
  <!-- overflow-hidden  -->
  <div ref="domRef" style="cursor: pointer;" class="h-360px text-focus-in"></div>
  <!-- </NCard> -->
</template>

<style scoped>
.text-focus-in {
  -webkit-animation: text-focus-in 1s cubic-bezier(0.550, 0.085, 0.680, 0.530) both;
  animation: text-focus-in 1s cubic-bezier(0.550, 0.085, 0.680, 0.530) both;
}

/* ----------------------------------------------
 * Generated by Animista on 2024-10-29 15:10:15
 * Licensed under FreeBSD License.
 * See http://animista.net/license for more info.
 * w: http://animista.net, t: @cssanimista
 * ---------------------------------------------- */

/**
 * ----------------------------------------
 * animation text-focus-in
 * ----------------------------------------
 */
@-webkit-keyframes text-focus-in {
  0% {
    -webkit-filter: blur(12px);
    filter: blur(12px);
    opacity: 0;
  }

  100% {
    -webkit-filter: blur(0px);
    filter: blur(0px);
    opacity: 1;
  }
}

@keyframes text-focus-in {
  0% {
    -webkit-filter: blur(12px);
    filter: blur(12px);
    opacity: 0;
  }

  100% {
    -webkit-filter: blur(0px);
    filter: blur(0px);
    opacity: 1;
  }
}
</style>
