<template>
  <div class="content">
    <div class="chart-box" v-loading="onlineLoading">
      <EchartCard
        title="在线用户统计"
        ref="onlineUserChartRef"
        :charts-id="'chart-1'"
        :bar-type="'barChart'"
        :option="onlineUserOptions"
      >
        <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'"
        :option="ouserLoginOptions"
      >
        <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 onlineUserOptions = ref<any>();
const changeOnlineUserFun = () => {
  onlineUserStatistics();
};
const onlineLoading = ref(false);
const onlineUserStatistics = async () => {
  onlineLoading.value = true;
  try {
    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 = {
      grid: {
        bottom: '45',
      },
      xAxis: {
        data: xData,
      },
      yAxis: {
        minInterval: 1,
      },
      dataZoom: xData.length > 10,
      series: [
        {
          name: '在线用户数',
          data: yData,
          itemStyle: {
            color: getThemeColor('--el-color-success'),
          },
        },
      ],
    };
    onlineUserOptions.value = { ...options };
  } catch {
  } finally {
    onlineLoading.value = false;
  }
};

// ********************** 用户登录数分析 **********************
const userLoginChartRef = ref();
const ouserLoginOptions = ref<any>();
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 optionsLine = {
    xAxis: {
      data: xData,
    },
    series: [
      {
        name: '登录用户数',
        data: yData,
        lineStyle: {
          color: getThemeColor('--el-color-primary'),
        },
        itemStyle: {
          normal: {
            color: getThemeColor('--el-color-primary'),
          },
        },
      },
    ],
    dataZoom: xData.length > 5,
  };
  ouserLoginOptions.value = { ...optionsLine };
};
</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>
