<template>
  <div class="content">
    <div class="chart-box">
      <EchartCard
        title="在线用户统计"
        ref="onlineUserChartRef"
        :charts-id="'chart-1'"
        :bar-type="'barChart'"
        @refresh="changeOnlineUserFun"
      >
        <template #formSlot>
          <el-form :model="onlineUserFromData" label-width="auto">
            <el-form-item label="日期">
              <el-date-picker
                v-model="date"
                type="date"
                placeholder="选择日期"
                :size="size"
                :clearable="false"
                :disabled-date="disabledDate"
                :teleported="true"
                @change="changeDateFun"
              />
            </el-form-item>
          </el-form>
        </template>
      </EchartCard>
    </div>
    <div class="chart-box">
      <EchartCard
        title="用户登录数分析"
        ref="userLoginChartRef"
        :charts-id="'chart-2'"
        :bar-type="'lineChart'"
        @refresh="changeUserLoginFun"
      >
        <template #formSlot>
          <el-form :model="userLoginFromData" label-width="auto">
            <el-form-item label="日期">
              <el-date-picker
                v-model="userLoginFromData.dateRange"
                type="daterange"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                :clearable="false"
                :size="size"
                value-format="YYYY-MM-DD"
                :disabled-date="disabledDate"
                @change="changeDateRangeFun"
              />
            </el-form-item>
          </el-form>
        </template>
      </EchartCard>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import { getHourlyOnlineStatisticsApi, getUserLoginStatisticsApi } from '@/api/system/systemLog';
import EchartCard from '@/components/common/echartCard/index.vue';
import dayjs from 'dayjs';
import { getThemeColor } from '@/utils/theme';

// ********************** 筛选条件部分 **********************
const size = ref<'default' | 'large' | 'small'>('default');
const date = ref(dayjs(new Date()).format('YYYY-MM-DD'));
const onlineUserFromData = ref<any>({
  date: date.value,
});
const disabledDate = (time: Date) => {
  return time.getTime() > Date.now();
};
const changeDateFun = (val: any) => {
  onlineUserFromData.value.date = dayjs(new Date(val)).format('YYYY-MM-DD');
  changeOnlineUserFun();
};

const userLoginFromData = ref<any>({
  // dateRange默认设置近7天
  dateRange: [
    dayjs(new Date()).subtract(6, 'day').format('YYYY-MM-DD'),
    dayjs(new Date()).format('YYYY-MM-DD'),
  ],
});
const changeDateRangeFun = () => {
  changeUserLoginFun();
};

onMounted(() => {
  changeOnlineUserFun();
  changeUserLoginFun();
});

// ********************** 每小时在线用户统计 **********************
const onlineUserChartRef = ref();
const changeOnlineUserFun = () => {
  onlineUserStatistics();
};

const onlineUserStatistics = async () => {
  const { data } = await getHourlyOnlineStatisticsApi({ ...onlineUserFromData.value });
  const xData: any = [];
  const yData: any = [];
  // 遍历data对象，key塞入xData，value塞入yData
  Object.keys(data).forEach((key) => {
    xData.push(key + '点');
    yData.push(data[key]);
  });
  const options = {
    title: {
      show: false,
    },
    tooltip: {
      trigger: 'axis',
    },
    legend: {
      show: false,
    },
    grid: {
      top: '5%',
    },
    xAxis: {
      type: 'category',
      data: xData,
    },
    yAxis: {
      type: 'value',
      minInterval: 1,
    },
    dataZoom:
      xData.length > 10
        ? [
            {
              type: 'slider',
              show: true,
              xAxisIndex: [0],
              start: 0,
              end: 100,
              textStyle: {
                color: 'transparent',
              },
              maxValueSpan: 10,
              minValueSpan: 10,
              moveHandleSize: 8,
              height: 0,
              filterMode: 'empty',
              bottom: 6,
            },
          ]
        : null,
    series: [
      {
        name: '在线用户数',
        type: 'bar',
        barWidth: '30%',
        data: yData,
        itemStyle: {
          color: getThemeColor('--el-color-success'),
        },
      },
    ],
  };
  onlineUserChartRef.value.commonChartRef.disposeEchartsByKey('chart-1');
  onlineUserChartRef.value.commonChartRef.option = { ...options };
  onlineUserChartRef.value.commonChartRef.initChart();
};

// ********************** 用户登录数分析 **********************
const userLoginChartRef = ref();
const changeUserLoginFun = () => {
  userLogintStatistics();
};
const userLogintStatistics = async () => {
  const createTimeArr = [
    dayjs(new Date(userLoginFromData.value.dateRange[0])).format('YYYY-MM-DD'),
    dayjs(new Date(userLoginFromData.value.dateRange[1])).format('YYYY-MM-DD'),
  ];
  const params = { createTimeArr };
  const { data } = await getUserLoginStatisticsApi(params);
  const xData: any = [];
  const yData: any = [];
  data?.forEach((item: any) => {
    xData.push(item.date);
    yData.push(item.loginUserCount);
  });
  // const xData = ['2025-12-10', '2025-12-11', '2025-12-12', '2025-12-13', '2025-12-14', '2025-12-15', '2025-12-16', '2025-12-17'];
  // const yData = [120, 200, 150, 80, 70, 110, 130, 100];
  const optionsLine = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'line',
      },
    },
    grid: {
      top: '5%',
    },
    xAxis: {
      type: 'category',
      boundaryGap: 30,
      data: xData,
    },
    yAxis: [
      {
        type: 'value',
        minInterval: 1,
      },
    ],
    series: [
      {
        name: '登录用户数',
        type: 'line',
        stack: 'Total',
        data: yData,
        lineStyle: {
          width: 2,
          color: getThemeColor('--el-color-primary'),
        },
        itemStyle: {
          normal: {
            color: getThemeColor('--el-color-primary'),
          },
        },
      },
    ],
    dataZoom:
      xData.length > 5
        ? [
            {
              type: 'slider',
              show: true,
              xAxisIndex: [0],
              start: 0,
              end: 100,
              textStyle: {
                color: 'transparent',
              },
              maxValueSpan: 5,
              minValueSpan: 5,
              moveHandleSize: 8,
              height: 0,
              filterMode: 'empty',
              bottom: 6,
            },
          ]
        : null,
    legend: {
      show: false,
    },
  };
  userLoginChartRef.value.commonChartRef.disposeEchartsByKey('chart-2');
  userLoginChartRef.value.commonChartRef.option = { ...optionsLine };
  userLoginChartRef.value.commonChartRef.initChart();
};
</script>

<style lang="scss" scoped>
.content {
  height: 80%;
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  overflow: hidden;
  .chart-box {
    width: calc(50% - 6px);
    height: 100%;
  }
}
</style>
