<template>
  <div class="p-2 report-page">
    <el-card shadow="hover" class="mb-[10px]">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="统计时间" style="width: 320px">
          <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-form-item>
        <el-form-item label="任务类型" prop="taskTypeKey">
          <el-input v-model="queryParams.taskTypeKey" placeholder="请输入任务类型Key" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="仓库" prop="warehouseId">
          <el-select v-model="queryParams.warehouseId" placeholder="请选择仓库" clearable filterable>
            <el-option
              v-for="item in warehouseOptions"
              :key="item.warehouseId"
              :label="formatWarehouseLabel(item)"
              :value="Number(item.warehouseId)"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" :loading="loading" @click="handleQuery">查询</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-row :gutter="12" class="mb-[10px]">
      <el-col v-for="item in metricCards" :key="item.label" :xs="12" :sm="8" :lg="4">
        <div class="metric-card">
          <div class="metric-label">{{ item.label }}</div>
          <div class="metric-value" :class="item.className">{{ item.value }}</div>
        </div>
      </el-col>
    </el-row>

    <el-row :gutter="12">
      <el-col :xs="24" :lg="14">
        <el-card shadow="hover" class="mb-[10px]">
          <template #header>
            <span>任务完成趋势</span>
          </template>
          <div ref="trendChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
      <el-col :xs="24" :lg="10">
        <el-card shadow="hover" class="mb-[10px]">
          <template #header>
            <span>任务类型分布</span>
          </template>
          <div ref="typeChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="12">
      <el-col :xs="24" :lg="14">
        <el-card shadow="hover" class="mb-[10px]">
          <template #header>
            <span>库位利用率</span>
          </template>
          <div ref="locationChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
      <el-col :xs="24" :lg="10">
        <el-card shadow="hover" class="mb-[10px]">
          <template #header>
            <span>库位统计明细</span>
          </template>
          <el-table border size="small" :data="locationUtilizationList" max-height="320">
            <el-table-column label="仓库" min-width="140" :show-overflow-tooltip="true">
              <template #default="scope">
                <span>{{ scope.row.warehouseName || scope.row.warehouseCode || scope.row.warehouseId }}</span>
              </template>
            </el-table-column>
            <el-table-column label="总数" prop="totalCount" width="70" align="center" />
            <el-table-column label="占用" prop="occupiedCount" width="70" align="center" />
            <el-table-column label="空闲" prop="emptyCount" width="70" align="center" />
            <el-table-column label="锁定" prop="lockedCount" width="70" align="center" />
            <el-table-column label="占用率" width="90" align="center">
              <template #default="scope">
                <el-tag :type="getUtilizationTag(scope.row.occupancyRate)">{{ formatPercent(scope.row.occupancyRate) }}</el-tag>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <el-card shadow="hover">
      <template #header>
        <span>异常任务列表</span>
      </template>
      <el-table border :data="taskStat.errorTaskList || []" max-height="360">
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column label="任务编码" prop="taskCode" min-width="150" :show-overflow-tooltip="true" />
        <el-table-column label="任务名称" prop="taskName" min-width="150" :show-overflow-tooltip="true" />
        <el-table-column label="任务类型" prop="taskTypeName" min-width="130" :show-overflow-tooltip="true" />
        <el-table-column label="状态" prop="status" width="110" align="center">
          <template #default="scope">
            <dict-tag :options="task_status" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="结果码" prop="resultCode" width="90" align="center" />
        <el-table-column label="错误信息" prop="errorMessage" min-width="220" :show-overflow-tooltip="true" />
        <el-table-column label="创建时间" prop="createtime" width="170" align="center">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createtime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup name="WcsReport" lang="ts">
import * as echarts from 'echarts';
import { getLocationUtilization, getTaskStat } from '@/api/wcs/report';
import { WcsLocationUtilizationVO, WcsReportQuery, WcsTaskStatVO } from '@/api/wcs/report/types';
import { listWarehouse } from '@/api/wcs/warehouse';
import { WarehouseVO } from '@/api/wcs/warehouse/types';

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

const loading = ref(false);
const dateRange = ref<[string, string]>(['', '']);
const warehouseOptions = ref<WarehouseVO[]>([]);
const locationUtilizationList = ref<WcsLocationUtilizationVO[]>([]);
const trendChartRef = ref<HTMLElement>();
const typeChartRef = ref<HTMLElement>();
const locationChartRef = ref<HTMLElement>();

let trendChart: echarts.ECharts | undefined;
let typeChart: echarts.ECharts | undefined;
let locationChart: echarts.ECharts | undefined;

const emptyTaskStat = (): WcsTaskStatVO => ({
  totalCount: 0,
  successCount: 0,
  failedCount: 0,
  runningCount: 0,
  pendingCount: 0,
  avgDurationSeconds: 0,
  trendList: [],
  typeList: [],
  errorTaskList: []
});

const taskStat = ref<WcsTaskStatVO>(emptyTaskStat());
const queryParams = ref<WcsReportQuery>({
  beginTime: undefined,
  endTime: undefined,
  taskTypeKey: undefined,
  warehouseId: undefined
});

const metricCards = computed(() => [
  { label: '任务总数', value: taskStat.value.totalCount || 0, className: 'text-primary' },
  { label: '成功任务', value: taskStat.value.successCount || 0, className: 'text-success' },
  { label: '失败任务', value: taskStat.value.failedCount || 0, className: 'text-danger' },
  { label: '执行中', value: taskStat.value.runningCount || 0, className: 'text-warning' },
  { label: '待执行', value: taskStat.value.pendingCount || 0, className: 'text-info' },
  { label: '平均耗时', value: `${formatSeconds(taskStat.value.avgDurationSeconds)}s`, className: 'text-primary' }
]);

const buildQuery = () => {
  // 报表接口显式接收 beginTime/endTime，前端统一从日期范围转换，避免时间字段散落在多个查询对象里。
  queryParams.value.beginTime = dateRange.value?.[0] || undefined;
  queryParams.value.endTime = dateRange.value?.[1] || undefined;
  return queryParams.value;
};

const getWarehouseOptions = async () => {
  const res = await listWarehouse({ pageNum: 1, pageSize: 1000 });
  warehouseOptions.value = res.rows || [];
};

const getReportData = async () => {
  loading.value = true;
  try {
    const query = buildQuery();
    const [taskRes, locationRes] = await Promise.all([getTaskStat(query), getLocationUtilization(query)]);
    taskStat.value = taskRes.data || emptyTaskStat();
    locationUtilizationList.value = locationRes.data || [];
    await nextTick();
    renderCharts();
  } finally {
    loading.value = false;
  }
};

const handleQuery = () => {
  getReportData();
};

const resetQuery = () => {
  dateRange.value = ['', ''];
  queryParams.value = {
    beginTime: undefined,
    endTime: undefined,
    taskTypeKey: undefined,
    warehouseId: undefined
  };
  getReportData();
};

const initCharts = () => {
  if (trendChartRef.value && !trendChart) {
    trendChart = echarts.init(trendChartRef.value);
  }
  if (typeChartRef.value && !typeChart) {
    typeChart = echarts.init(typeChartRef.value);
  }
  if (locationChartRef.value && !locationChart) {
    locationChart = echarts.init(locationChartRef.value);
  }
};

const renderCharts = () => {
  initCharts();
  renderTrendChart();
  renderTypeChart();
  renderLocationChart();
};

const renderTrendChart = () => {
  const trendList = taskStat.value.trendList || [];
  trendChart?.setOption({
    tooltip: { trigger: 'axis' },
    legend: { top: 0, data: ['总数', '成功', '失败'] },
    grid: { left: 40, right: 20, top: 48, bottom: 32 },
    xAxis: { type: 'category', data: trendList.map((item) => item.statDate) },
    yAxis: { type: 'value', minInterval: 1 },
    series: [
      { name: '总数', type: 'line', smooth: true, data: trendList.map((item) => item.totalCount), itemStyle: { color: '#409eff' } },
      { name: '成功', type: 'line', smooth: true, data: trendList.map((item) => item.successCount), itemStyle: { color: '#67c23a' } },
      { name: '失败', type: 'line', smooth: true, data: trendList.map((item) => item.failedCount), itemStyle: { color: '#f56c6c' } }
    ]
  });
};

const renderTypeChart = () => {
  const typeList = taskStat.value.typeList || [];
  typeChart?.setOption({
    tooltip: { trigger: 'item' },
    legend: { type: 'scroll', bottom: 0 },
    series: [
      {
        name: '任务类型',
        type: 'pie',
        radius: ['42%', '68%'],
        center: ['50%', '44%'],
        data: typeList.map((item) => ({
          name: item.taskTypeName || item.taskTypeKey,
          value: item.totalCount
        })),
        label: { formatter: '{b}: {c}' }
      }
    ]
  });
};

const renderLocationChart = () => {
  const list = locationUtilizationList.value || [];
  locationChart?.setOption({
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' },
      valueFormatter: (value: number) => `${value}%`
    },
    grid: { left: 44, right: 24, top: 24, bottom: 56 },
    xAxis: {
      type: 'category',
      data: list.map((item) => item.warehouseName || item.warehouseCode || item.warehouseId),
      axisLabel: { rotate: 28 }
    },
    yAxis: { type: 'value', max: 100, axisLabel: { formatter: '{value}%' } },
    series: [
      {
        name: '占用率',
        type: 'bar',
        data: list.map((item) => Number(item.occupancyRate || 0)),
        itemStyle: {
          color: (params: any) => {
            const value = Number(params.value);
            if (value >= 90) {
              return '#f56c6c';
            }
            if (value >= 70) {
              return '#e6a23c';
            }
            return '#67c23a';
          }
        },
        label: { show: true, position: 'top', formatter: '{c}%' }
      }
    ]
  });
};

const handleResize = () => {
  trendChart?.resize();
  typeChart?.resize();
  locationChart?.resize();
};

const formatWarehouseLabel = (item: WarehouseVO) => {
  return `${item.warehouseName || '未命名仓库'}（${item.warehouseId}）`;
};

const formatSeconds = (value?: number) => {
  return Number(value || 0).toFixed(1);
};

const formatPercent = (value?: number) => {
  return `${Number(value || 0).toFixed(1)}%`;
};

const getUtilizationTag = (value?: number) => {
  const rate = Number(value || 0);
  if (rate >= 90) {
    return 'danger';
  }
  if (rate >= 70) {
    return 'warning';
  }
  return 'success';
};

onMounted(async () => {
  await getWarehouseOptions();
  await getReportData();
  window.addEventListener('resize', handleResize);
});

onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize);
  trendChart?.dispose();
  typeChart?.dispose();
  locationChart?.dispose();
});
</script>

<style scoped>
.report-page :deep(.el-card__header) {
  font-weight: 600;
}

.metric-card {
  min-height: 86px;
  padding: 14px 16px;
  border: 1px solid var(--el-border-color-lighter);
  border-radius: 6px;
  background: var(--el-bg-color);
}

.metric-label {
  color: var(--el-text-color-secondary);
  font-size: 13px;
}

.metric-value {
  margin-top: 10px;
  font-size: 24px;
  font-weight: 700;
  line-height: 1;
}

.chart-container {
  height: 320px;
}

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

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

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

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

.text-info {
  color: var(--el-text-color-secondary);
}
</style>
