<template>
  <el-drawer v-model="visible" title="操作日志统计" direction="rtl" size="80%">
    <div class="p-4">
      <!-- 查询条件 -->
      <el-card shadow="hover" class="mb-4">
        <template #header>
          <span class="font-bold">统计条件</span>
        </template>
        <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="120px">
          <el-form-item label="统计时间" prop="dateRange" :rules="[{ required: true, message: '请选择统计时间范围' }]">
            <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)]"
              style="width: 350px"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="操作人员" prop="operName">
            <el-input v-model="queryParams.operName" placeholder="请输入操作人员" clearable style="width: 200px" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery" :loading="loading"> 统计查询 </el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 统计结果 -->
      <el-card v-if="statisticsData.length > 0" shadow="hover">
        <template #header>
          <div class="flex justify-between items-center">
            <span class="font-bold">统计结果</span>
            <el-radio-group v-model="chartType" @change="renderChart">
              <el-radio-button value="pie">饼图</el-radio-button>
              <el-radio-button value="bar">柱状图</el-radio-button>
            </el-radio-group>
          </div>
        </template>

        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
          <!-- 图表区域 -->
          <div>
            <div ref="chartRef" style="width: 100%; height: 400px"></div>
          </div>

          <!-- 数据表格 -->
          <div>
            <el-table :data="statisticsData" border stripe>
              <el-table-column label="操作类型" align="center">
                <template #default="{ row }">
                  <dict-tag :options="sys_oper_type" :value="row.code" />
                </template>
              </el-table-column>
              <el-table-column label="操作次数" prop="value" align="center">
                <template #default="{ row }">
                  <span class="font-bold text-primary">{{ row.value }}</span>
                </template>
              </el-table-column>
              <el-table-column label="占比" align="center">
                <template #default="{ row }">
                  <span class="text-sm text-gray-600"> {{ ((row.value / totalCount) * 100).toFixed(2) }}% </span>
                </template>
              </el-table-column>
            </el-table>

            <!-- 统计摘要 -->
            <div class="mt-4 p-4 bg-gray-50 rounded-lg">
              <h4 class="text-lg font-bold mb-3">统计摘要</h4>
              <div class="grid grid-cols-2 gap-4 text-sm">
                <div>
                  <span class="text-gray-600">总操作次数：</span>
                  <span class="font-bold text-blue-600">{{ totalCount }}</span>
                </div>
                <div>
                  <span class="text-gray-600">操作类型数：</span>
                  <span class="font-bold text-green-600">{{ statisticsData.length }}</span>
                </div>
                <div>
                  <span class="text-gray-600">新增操作：</span>
                  <span class="font-bold text-green-600">{{ getCountByType('1') }}</span>
                </div>
                <div>
                  <span class="text-gray-600">删除操作：</span>
                  <span class="font-bold text-red-600">{{ getCountByType('3') }}</span>
                </div>
                <div>
                  <span class="text-gray-600">统计时间范围：</span>
                  <span class="font-bold text-purple-600">{{ dateRangeText }}</span>
                </div>
                <div v-if="queryParams.operName">
                  <span class="text-gray-600">操作人员：</span>
                  <span class="font-bold text-orange-600">{{ queryParams.operName }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-card>

      <!-- 空状态 -->
      <el-empty v-else-if="!loading && hasQueried" description="暂无统计数据" />
    </div>
  </el-drawer>
</template>

<script setup lang="ts">
import { statistics } from '@/api/monitor/operlog';
import * as echarts from 'echarts';

interface StatisticsData {
  code: string;
  name?: string;
  value: number;
}

// 注入全局属性和字典
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_oper_type } = toRefs<any>(proxy?.useDict('sys_oper_type'));

const visible = ref(false);
const loading = ref(false);
const hasQueried = ref(false);
const chartType = ref<'pie' | 'bar'>('pie');
const statisticsData = ref<StatisticsData[]>([]);
const dateRange = ref<[string, string]>(['', '']);
const chartRef = ref<HTMLDivElement>();
let chartInstance: echarts.ECharts | null = null;

const queryFormRef = ref<ElFormInstance>();

const queryParams = ref({
  operName: '',
  params: {} as Record<string, any>
});

const totalCount = computed(() => {
  return statisticsData.value.reduce((sum, item) => sum + item.value, 0);
});

const dateRangeText = computed(() => {
  if (dateRange.value[0] && dateRange.value[1]) {
    return `${dateRange.value[0]} 至 ${dateRange.value[1]}`;
  }
  return '';
});

// 获取操作类型名称
const getTypeName = (code: string) => {
  if (!sys_oper_type.value) return '未知';
  const dict = sys_oper_type.value.find((item: any) => item.value === code);
  return dict?.label || '未知';
};

// 根据类型获取数量
const getCountByType = (type: string) => {
  const item = statisticsData.value.find((data) => data.code === type);
  return item ? item.value : 0;
};

// 打开抽屉
const openDrawer = () => {
  visible.value = true;
  hasQueried.value = false;
  statisticsData.value = [];
};

// 关闭抽屉
const closeDrawer = () => {
  visible.value = false;
  if (chartInstance) {
    chartInstance.dispose();
    chartInstance = null;
  }
};

// 查询统计数据
const handleQuery = async () => {
  if (!dateRange.value[0] || !dateRange.value[1]) {
    ElMessage.warning('请选择统计时间范围');
    return;
  }

  loading.value = true;
  hasQueried.value = true;

  try {
    // 构造查询参数
    const params = {
      ...queryParams.value,
      params: {
        beginTime: dateRange.value[0],
        endTime: dateRange.value[1]
      }
    };

    const response = await statistics(params);
    statisticsData.value = response.data || [];

    if (statisticsData.value.length > 0) {
      nextTick(() => {
        renderChart();
      });
    }
  } catch (error) {
    ElMessage.error('统计查询失败');
  } finally {
    loading.value = false;
  }
};

// 重置查询条件
const resetQuery = () => {
  queryParams.value.operName = '';
  dateRange.value = ['', ''];
  statisticsData.value = [];
  hasQueried.value = false;
  if (chartInstance) {
    chartInstance.clear();
  }
};

// 渲染图表
const renderChart = () => {
  if (!chartRef.value || statisticsData.value.length === 0) return;

  if (chartInstance) {
    chartInstance.dispose();
  }

  chartInstance = echarts.init(chartRef.value);

  const option = chartType.value === 'pie' ? getPieOption() : getBarOption();

  chartInstance.setOption(option);

  // 监听窗口大小变化
  window.addEventListener('resize', () => {
    chartInstance?.resize();
  });
};

// 饼图配置
const getPieOption = () => {
  const data = statisticsData.value.map((item) => ({
    name: getTypeName(item.code),
    value: item.value
  }));

  return {
    title: {
      text: '操作类型分布',
      left: 'center',
      top: 20,
      textStyle: {
        fontSize: 16
      }
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      type: 'scroll',
      orient: 'vertical',
      right: 10,
      top: 60,
      bottom: 20
    },
    series: [
      {
        name: '操作统计',
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['40%', '60%'],
        data: data,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
        label: {
          show: true,
          formatter: '{b}: {d}%'
        }
      }
    ]
  };
};

// 柱状图配置
const getBarOption = () => {
  const xData = statisticsData.value.map((item) => getTypeName(item.code));
  const yData = statisticsData.value.map((item) => item.value);

  return {
    title: {
      text: '操作类型统计',
      left: 'center',
      top: 20,
      textStyle: {
        fontSize: 16
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: '{a} <br/>{b}: {c} 次'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: '15%',
      containLabel: true
    },
    xAxis: [
      {
        type: 'category',
        data: xData,
        axisTick: {
          alignWithLabel: true
        }
      }
    ],
    yAxis: [
      {
        type: 'value',
        name: '操作次数'
      }
    ],
    series: [
      {
        name: '操作统计',
        type: 'bar',
        barWidth: '60%',
        data: yData,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#83bff6' },
            { offset: 0.5, color: '#188df0' },
            { offset: 1, color: '#188df0' }
          ])
        },
        emphasis: {
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#2378f7' },
              { offset: 0.7, color: '#2378f7' },
              { offset: 1, color: '#83bff6' }
            ])
          }
        }
      }
    ]
  };
};

// 监听抽屉关闭事件
watch(visible, (newVal) => {
  if (!newVal) {
    closeDrawer();
  }
});

// 暴露方法给父组件
defineExpose({
  openDrawer
});

onUnmounted(() => {
  if (chartInstance) {
    chartInstance.dispose();
    chartInstance = null;
  }
  window.removeEventListener('resize', () => {
    chartInstance?.resize();
  });
});
</script>

<style scoped>
.grid {
  display: grid;
}

.grid-cols-1 {
  grid-template-columns: repeat(1, minmax(0, 1fr));
}

.grid-cols-2 {
  grid-template-columns: repeat(2, minmax(0, 1fr));
}

@media (min-width: 1024px) {
  .lg\:grid-cols-2 {
    grid-template-columns: repeat(2, minmax(0, 1fr));
  }
}

.gap-4 {
  gap: 1rem;
}

.gap-6 {
  gap: 1.5rem;
}

.font-bold {
  font-weight: 700;
}

.text-primary {
  color: var(--el-color-primary);
}

.text-blue-600 {
  color: #2563eb;
}

.text-green-600 {
  color: #16a34a;
}

.text-red-600 {
  color: #dc2626;
}

.text-purple-600 {
  color: #9333ea;
}

.text-orange-600 {
  color: #ea580c;
}

.text-gray-600 {
  color: #4b5563;
}

.bg-gray-50 {
  background-color: #f9fafb;
}

.rounded-lg {
  border-radius: 0.5rem;
}

.p-4 {
  padding: 1rem;
}

.mb-3 {
  margin-bottom: 0.75rem;
}

.mb-4 {
  margin-bottom: 1rem;
}

.mt-4 {
  margin-top: 1rem;
}

.text-lg {
  font-size: 1.125rem;
  line-height: 1.75rem;
}

.text-sm {
  font-size: 0.875rem;
  line-height: 1.25rem;
}

.flex {
  display: flex;
}

.justify-between {
  justify-content: space-between;
}

.items-center {
  align-items: center;
}
</style>
