<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <div class="card-header">
            <span>统计条件</span>
          </div>
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <!-- 完整查询条件开始 -->
            <el-form-item label="登录地址" prop="ipaddr">
              <el-input v-model="queryParams.ipaddr" placeholder="请输入登录地址" clearable />
            </el-form-item>
            <el-form-item label="用户名称" prop="userName">
              <el-input v-model="queryParams.userName" placeholder="请输入用户名称" clearable />
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="登录状态" clearable>
                <el-option v-for="dict in sys_common_status" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="统计时间" style="width: 308px">
              <el-date-picker
                v-model="dateRange"
                value-format="YYYY-MM-DD HH:mm:ss"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
              ></el-date-picker>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">统计查询</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
            <!-- 完整查询条件结束 -->
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="hover">
      <template #header>
        <div class="card-header">
          <span>统计结果</span>
        </div>
      </template>

      <!-- 统计结果展示区域 -->
      <div class="statistics-container">
        <!-- 左侧图表区域 -->
        <div class="chart-area">
          <div class="chart-tabs">
            <el-radio-group v-model="activeChart" @change="changeChart">
              <el-radio-button label="pie">饼图</el-radio-button>
              <el-radio-button label="tree">树状图</el-radio-button>
            </el-radio-group>
          </div>

          <div v-show="activeChart === 'pie'" class="chart-container">
            <div class="chart-title">登录状态分布</div>
            <div ref="pieChart" style="width: 100%; height: 300px;"></div>
          </div>

          <div v-show="activeChart === 'tree'" class="chart-container">
            <div class="chart-title">登录状态分布</div>
            <div ref="treeChart" style="width: 100%; height: 300px;"></div>
          </div>
        </div>

        <!-- 右侧统计信息区域 -->
        <div class="stats-info">
          <!-- 状态统计表格 -->
          <div class="stats-table">
            <div class="table-title">登录状态统计</div>
            <el-table :data="statusData" style="width: 100%" height="200">
              <el-table-column prop="status" label="登录状态" />
              <el-table-column prop="count" label="登录次数" />
              <el-table-column prop="percentage" label="占比" />
            </el-table>
          </div>

          <!-- 统计摘要 -->
          <div class="stats-summary">
            <div class="summary-title">统计摘要</div>
            <div class="summary-item">总登录次数：{{ totalLoginCount }}</div>
            <div class="summary-item">状态类型数：{{ statusTypeCount }}</div>
            <div class="summary-item">成功登录：{{ successCount }}</div>
            <div class="summary-item">失败登录：{{ failureCount }}</div>
            <div class="summary-item" v-if="dateRange[0] && dateRange[1]">
              统计时间范围：{{ dateRange[0] }} 至 {{ dateRange[1] }}
            </div>
            <div class="summary-item" v-else>
              统计时间范围：未选择时间范围
            </div>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup name="LogininforStats" lang="ts">
import { ref, onMounted, watch, nextTick } from 'vue';
import * as echarts from 'echarts';
import { getStatics, list } from '@/api/monitor/loginInfo';
import { LoginInfoQuery, LoginInfoVO } from '@/api/monitor/loginInfo/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_common_status } = toRefs<any>(proxy?.useDict('sys_common_status'));

// 移除冗余的状态和数据
const showSearch = ref(true);
const dateRange = ref<[DateModelType, DateModelType]>([, ]);
const queryFormRef = ref<ElFormInstance>();
const activeChart = ref('pie'); // 默认显示饼图

// 查询参数
const queryParams = ref<LoginInfoQuery>({
  ipaddr: '',
  userName: '',
  status: '',
});

// 图表和数据相关
const pieChart = ref();
const treeChart = ref();
let pieChartInstance: echarts.ECharts | null = null;
let treeChartInstance: echarts.ECharts | null = null;

// 统计数据
const statusData = ref([]);
const totalLoginCount = ref(0);
const statusTypeCount = ref(0);
const successCount = ref(0);
const failureCount = ref(0);

//** 初始化饼图 */
const initPieChart = () => {
  if (!pieChart.value) return;

  pieChartInstance = echarts.init(pieChart.value);
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      right: 10,
      top: 'center',
      data: [] // 初始为空数组
    },
    color: ['#409EFF', '#E6A23C', '#67C23A'],
    series: [
      {
        name: '登录状态',
        type: 'pie',
        radius: ['50%', '70%'],
        avoidLabelOverlap: false,
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: [] // 初始为空数组
      }
    ]
  };

  pieChartInstance.setOption(option);
};

/** 初始化树状图 */
const initTreeChart = () => {
  if (!treeChart.value) return;

  treeChartInstance = echarts.init(treeChart.value);
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c}'
    },
    series: [
      {
        type: 'treemap',
        data: [] // 初始为空数组
      }
    ]
  };

  treeChartInstance.setOption(option);
};

/** 切换图表类型 */
const changeChart = () => {
  nextTick(() => {
    if (activeChart.value === 'pie') {
      if (!pieChartInstance && pieChart.value) {
        initPieChart();
      } else if (pieChartInstance) {
        pieChartInstance.resize();
      }
    } else if (activeChart.value === 'tree') {
      if (!treeChartInstance && treeChart.value) {
        initTreeChart();
      } else if (treeChartInstance) {
        treeChartInstance.resize();
      }
    }
  });
};
/** 构建查询参数 */
const buildQueryParams = () => {
  const params: any = {
    ...queryParams.value
  };

  // 设置时间范围 - 直接传递beginTime和endTime
  if (dateRange.value && dateRange.value.length === 2) {
    params['beginTime'] = dateRange.value[0];
    params['endTime'] = dateRange.value[1];
  }

  return params;
};
/** 处理统计数据 */
const processStatsData = (data: any) => {
  // 从第一行数据中获取总登录次数（totalCount）
  const totalCount = data.rows.length > 0 ? data.rows[0].totalCount : 0;

  // 处理状态数据
  const stats = data.rows.map((item: any) => {
    // 正确计算占比（使用totalCount而不是data.total）
    const percentage = totalCount > 0 ? ((item.count / totalCount) * 100).toFixed(2) + '%' : '0%';

    // 根据状态码转换为文本
    const statusText = getStatusText(item.status);

    return {
      status: statusText,
      count: item.count,
      percentage: percentage
    };
  });

  // 计算成功和失败的数量
  const successCountValue = data.rows.find((item: any) => item.status === '0')?.count || 0;
  const failureCountValue = data.rows.find((item: any) => item.status === '1')?.count || 0;

  // 更新响应式数据
  statusData.value = stats;
  totalLoginCount.value = totalCount; // 使用totalCount而不是data.total
  statusTypeCount.value = data.total; // 使用data.total作为状态类型数
  successCount.value = successCountValue;
  failureCount.value = failureCountValue;

  // 更新图表数据
  updateCharts(data.rows, totalCount);
};
/** 获取状态文本 */
const getStatusText = (statusCode: string) => {
  const statusMap: Record<string, string> = {
    '0': '成功',
    '1': '失败',
    '2': '未知',
    '3': '其他'
  };
  return statusMap[statusCode] || '未知';
};

/** 更新图表数据 */
const updateCharts = (rows: any[], totalCount: number) => {
  // 更新饼图
  if (pieChartInstance) {
    pieChartInstance.setOption({
      legend: {
        data: rows.map((item: any) => getStatusText(item.status))
      },
      series: [{
        data: rows.map((item: any) => {
          return {
            value: item.count,
            name: getStatusText(item.status)
          };
        })
      }]
    });
  }

  // 更新树状图
  if (treeChartInstance) {
    treeChartInstance.setOption({
      series: [{
        data: rows.map((item: any) => {
          return {
            name: getStatusText(item.status),
            value: item.count,
            itemStyle: {
              color: getStatusColor(item.status)
            }
          };
        })
      }]
    });
  }
};
/** 获取状态对应的颜色 */
const getStatusColor = (statusCode: string) => {
  const colorMap: Record<string, string> = {
    '0': '#409EFF', // 成功 - 蓝色
    '1': '#E6A23C', // 失败 - 橙色
    '2': '#67C23A', // 未知 - 绿色
    '3': '#909399' // 其他 - 灰色
  };
  return colorMap[statusCode] || '#909399'; // 默认灰色
};
/** 查询登录日志统计 */
const getStats = async () => {
  try {
    // 构建查询参数（按照图片中的格式）
    const params = buildQueryParams();

    // 调用API获取数据
    const res = await getStatics(params);
    processStatsData(res);
  } catch (error) {
    proxy?.$modal.msgError('获取统计信息失败');
  }
};

/** 搜索按钮操作 */
const handleQuery = () => {
  getStats();
};

/** 重置按钮操作 */
const resetQuery = () => {
  dateRange.value = ['', '']; // 清空时间范围
  queryFormRef.value?.resetFields();
  getStats();
};

onMounted(() => {
  nextTick(() => {
    initPieChart();
    initTreeChart();
    getStats();
  });
});

// 监听窗口变化，调整图表大小
window.addEventListener('resize', () => {
  if (pieChartInstance) {
    pieChartInstance.resize();
  }
  if (treeChartInstance) {
    treeChartInstance.resize();
  }
});
</script>

<style scoped>
.statistics-container {
  display: flex;
  justify-content: space-between;
  gap: 20px;
}

.chart-area {
  flex: 1;
  border: 1px solid #e6e6e6;
  border-radius: 4px;
  padding: 15px;
}

.stats-info {
  width: 350px;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.chart-tabs {
  margin-bottom: 15px;
  text-align: center;
}

.chart-title {
  font-weight: bold;
  margin-bottom: 10px;
  text-align: center;
}

.table-title, .summary-title {
  font-weight: bold;
  margin-bottom: 10px;
  font-size: 14px;
}

.stats-table, .stats-summary {
  border: 1px solid #e6e6e6;
  border-radius: 4px;
  padding: 15px;
}

.stats-summary {
  flex: 1;
}

.summary-item {
  margin-bottom: 8px;
  font-size: 14px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.card-header span {
  font-weight: bold;
}
</style>
