<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">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">

            <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="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <!-- 图表展示区域 -->
      <el-row :gutter="20" class="mb-4">
        <el-col :span="24">
          <el-card shadow="hover">
            <template #header>
              <span>库存变动趋势图</span>
            </template>
            <div ref="lineChartRef" style="height: 400px;"></div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 数据表格 -->
      <el-table v-loading="loading" :data="reportList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="物料编码" align="center" prop="materialCode" />
        <el-table-column label="物料名称" align="center" prop="materialName" show-overflow-tooltip />
        <el-table-column label="物料大类" align="center" prop="materialCategoryName" />
        <el-table-column label="统计月份" align="center" prop="statisticsMonth" />
        <el-table-column label="统计周" align="center" prop="statisticsWeek" />
        <el-table-column label="当前库存数量" align="center" prop="currentInventoryQty" />
        <el-table-column label="本周入库数量" align="center" prop="weekInstockQty" />
        <el-table-column label="本周出库数量" align="center" prop="weekOutstockQty" />
        <el-table-column label="上周结存数量" align="center" prop="lastWeekInventoryQty" />
        <el-table-column label="关键节点标注" align="center" prop="keyNodeMark">
          <template #default="scope">
            <el-tag :type="getNodeMarkType(scope.row.keyNodeMark)">
              {{ scope.row.keyNodeMark }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup name="InventoryTrendAnalysis" lang="ts">
import { getInventoryTrendAnalysis, exportInventoryTrendAnalysis } from '@/api/wms/report';
import { listBaseMaterialCategoryInWMS } from '@/api/wms/baseMaterialCategory';
import { InventoryTrendAnalysisVO, ReportQuery } from '@/api/wms/report/types';
import { BaseMaterialCategoryVO } from '@/api/wms/baseMaterialCategory/types';
import * as echarts from 'echarts';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const reportList = ref<InventoryTrendAnalysisVO[]>([]);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const materialCategoryOptions = ref<BaseMaterialCategoryVO[]>([]);

// 图表引用
const lineChartRef = ref<HTMLDivElement>();
let lineChart: echarts.ECharts;

const queryFormRef = ref<ElFormInstance>();

const queryParams = ref<ReportQuery>({
  tenantId: undefined,
  materialCategoryId: undefined
});

/** 查询库存变动趋势分析报表列表 */
const getList = async () => {
  loading.value = true;
  const res = await getInventoryTrendAnalysis(queryParams.value);
  reportList.value = res.data;
  loading.value = false;

  // 更新图表
  nextTick(() => {
    updateChart();
  });
};

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

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: InventoryTrendAnalysisVO[]) => {
  ids.value = selection.map(item => item.materialId!);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('/wms/report/inventoryTrendAnalysis/export', {
    ...queryParams.value
  }, `库存变动趋势分析报表_${new Date().getTime()}.xlsx`);
};

/** 获取物料大类选项 */
const getMaterialCategoryOptions = async () => {
  const res = await listBaseMaterialCategoryInWMS({});
  materialCategoryOptions.value = res.data.rows || [];
};

/** 获取关键节点标注类型 */
const getNodeMarkType = (mark: string) => {
  switch (mark) {
    case '大额入库': return 'success';
    case '大额出库': return 'danger';
    default: return 'info';
  }
};

/** 初始化图表 */
const initChart = () => {
  if (lineChartRef.value) {
    lineChart = echarts.init(lineChartRef.value);
  }
};

/** 更新图表数据 */
const updateChart = () => {
  if (!reportList.value.length || !lineChart) return;

  // 按物料分组数据
  const materialGroups = reportList.value.reduce((groups, item) => {
    const key = item.materialName || '';
    if (!groups[key]) {
      groups[key] = [];
    }
    groups[key].push(item);
    return groups;
  }, {} as Record<string, InventoryTrendAnalysisVO[]>);

  const series: any[] = [];
  const xAxisData = [...new Set(reportList.value.map(item => `第${item.statisticsWeek}周`))];

  Object.keys(materialGroups).slice(0, 5).forEach((materialName, index) => {
    const data = xAxisData.map(week => {
      const weekNum = parseInt(week.replace('第', '').replace('周', ''));
      const item = materialGroups[materialName].find(d => d.statisticsWeek === weekNum);
      return item?.currentInventoryQty || 0;
    });

    series.push({
      name: materialName,
      type: 'line',
      data: data,
      smooth: true
    });
  });

  const option = {
    title: {
      text: '库存变动趋势',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: Object.keys(materialGroups).slice(0, 5),
      top: 30
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: xAxisData
    },
    yAxis: {
      type: 'value',
      name: '库存数量'
    },
    series: series
  };

  lineChart.setOption(option);
};

/** 窗口大小改变时重新调整图表 */
const handleResize = () => {
  lineChart?.resize();
};

onMounted(() => {
  getMaterialCategoryOptions();
  getList();
  initChart();
  window.addEventListener('resize', handleResize);
});

onUnmounted(() => {
  window.removeEventListener('resize', handleResize);
  lineChart?.dispose();
});
</script>

<style scoped>
.el-card {
  margin-bottom: 20px;
}
</style>
