<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="8">
          <el-card shadow="hover" class="stat-card">
            <div class="stat-item">
              <div class="stat-value text-red-500">{{ stagnantStats.neverOut }}</div>
              <div class="stat-label">从未出库</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card shadow="hover" class="stat-card">
            <div class="stat-item">
              <div class="stat-value text-orange-500">{{ stagnantStats.overSixMonths }}</div>
              <div class="stat-label">超过6个月未出库</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card shadow="hover" class="stat-card">
            <div class="stat-item">
              <div class="stat-value text-blue-500">{{ stagnantStats.totalQty }}</div>
              <div class="stat-label">呆滞库存总量</div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 图表展示区域 -->
      <el-row :gutter="20" class="mb-4">
        <el-col :span="12">
          <el-card shadow="hover">
            <template #header>
              <span>呆滞原因分布</span>
            </template>
            <div ref="pieChartRef" style="height: 300px;"></div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card shadow="hover">
            <template #header>
              <span>呆滞天数分布</span>
            </template>
            <div ref="barChartRef" style="height: 300px;"></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="stagnantInventoryQty" />
        <el-table-column label="计量单位" align="center" prop="materialUnit" />
        <el-table-column label="最后出库时间" align="center" prop="lastOutstockTime" width="180" />
        <el-table-column label="呆滞天数" align="center" prop="stagnantDays">
          <template #default="scope">
            <el-tag :type="getStagnantDaysType(scope.row.stagnantDays)">
              {{ scope.row.stagnantDays }}天
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="呆滞原因" align="center" prop="stagnantReason" />
        <el-table-column label="物料规格" align="center" prop="materialSpec" show-overflow-tooltip />
        <el-table-column label="所在仓库" align="center" prop="warehouseName" />
      </el-table>
    </el-card>
  </div>
</template>

<script setup name="StagnantInventory" lang="ts">
import { getStagnantInventory, exportStagnantInventory } from '@/api/wms/report';
import { listBaseMaterialCategoryInWMS } from '@/api/wms/baseMaterialCategory';
import { StagnantInventoryVO, 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<StagnantInventoryVO[]>([]);
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 stagnantStats = ref({
  neverOut: 0,
  overSixMonths: 0,
  totalQty: 0
});

// 图表引用
const pieChartRef = ref<HTMLDivElement>();
const barChartRef = ref<HTMLDivElement>();
let pieChart: echarts.ECharts;
let barChart: echarts.ECharts;

const queryFormRef = ref<ElFormInstance>();

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

/** 查询呆滞料库存报表列表 */
const getList = async () => {
  loading.value = true;
  const res = await getStagnantInventory(queryParams.value);
  reportList.value = res.data;
  loading.value = false;

  // 计算统计数据
  calculateStats();

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

/** 计算统计数据 */
const calculateStats = () => {
  stagnantStats.value = {
    neverOut: reportList.value.filter(item => item.stagnantReason === '从未出库').length,
    overSixMonths: reportList.value.filter(item => item.stagnantReason === '超过6个月未出库').length,
    totalQty: reportList.value.reduce((sum, item) => sum + (item.stagnantInventoryQty || 0), 0)
  };
};

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

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

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

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('/wms/report/stagnantInventory/export', {
    ...queryParams.value
  }, `呆滞料库存报表_${new Date().getTime()}.xlsx`);
};

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

/** 获取呆滞天数类型 */
const getStagnantDaysType = (days: number) => {
  if (days >= 365) return 'danger';
  if (days >= 180) return 'warning';
  return 'info';
};

/** 初始化图表 */
const initCharts = () => {
  if (pieChartRef.value) {
    pieChart = echarts.init(pieChartRef.value);
  }
  if (barChartRef.value) {
    barChart = echarts.init(barChartRef.value);
  }
};

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

  // 饼图：呆滞原因分布
  const reasonCount = reportList.value.reduce((acc, item) => {
    const reason = item.stagnantReason || '未知';
    acc[reason] = (acc[reason] || 0) + 1;
    return acc;
  }, {} as Record<string, number>);

  const pieData = Object.keys(reasonCount).map(reason => ({
    name: reason,
    value: reasonCount[reason]
  }));

  const pieOption = {
    title: {
      text: '呆滞原因分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '呆滞原因',
        type: 'pie',
        radius: '50%',
        data: pieData,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  };

  // 柱状图：呆滞天数分布
  const daysRanges = ['0-90天', '91-180天', '181-365天', '365天以上'];
  const daysData = daysRanges.map(range => {
    switch (range) {
      case '0-90天':
        return reportList.value.filter(item => (item.stagnantDays || 0) <= 90).length;
      case '91-180天':
        return reportList.value.filter(item => (item.stagnantDays || 0) > 90 && (item.stagnantDays || 0) <= 180).length;
      case '181-365天':
        return reportList.value.filter(item => (item.stagnantDays || 0) > 180 && (item.stagnantDays || 0) <= 365).length;
      case '365天以上':
        return reportList.value.filter(item => (item.stagnantDays || 0) > 365).length;
      default:
        return 0;
    }
  });

  const barOption = {
    title: {
      text: '呆滞天数分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: daysRanges
    },
    yAxis: {
      type: 'value',
      name: '物料数量'
    },
    series: [
      {
        name: '物料数量',
        type: 'bar',
        data: daysData,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#83bff6' },
            { offset: 0.5, color: '#188df0' },
            { offset: 1, color: '#188df0' }
          ])
        }
      }
    ]
  };

  pieChart?.setOption(pieOption);
  barChart?.setOption(barOption);
};

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

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

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

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

.stat-card {
  text-align: center;
}

.stat-item {
  padding: 20px;
}

.stat-value {
  font-size: 2rem;
  font-weight: bold;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 0.9rem;
  color: #666;
}
</style>
