<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="6">
          <el-card shadow="hover" class="stat-card">
            <div class="stat-item">
              <div class="stat-value text-green-500">{{ turnoverStats.fast }}</div>
              <div class="stat-label">快速周转</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="stat-card">
            <div class="stat-item">
              <div class="stat-value text-blue-500">{{ turnoverStats.normal }}</div>
              <div class="stat-label">正常周转</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="stat-card">
            <div class="stat-item">
              <div class="stat-value text-orange-500">{{ turnoverStats.slow }}</div>
              <div class="stat-label">缓慢周转</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="stat-card">
            <div class="stat-item">
              <div class="stat-value text-gray-500">{{ turnoverStats.noFlow }}</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="statisticsMonth" />
        <el-table-column label="月初库存数量" align="center" prop="beginInventoryQty" />
        <el-table-column label="月末库存数量" align="center" prop="endInventoryQty" />
        <el-table-column label="月出库数量" align="center" prop="monthOutstockQty" />
        <el-table-column label="库存周转率(%)" align="center" prop="inventoryTurnoverRate" />
        <el-table-column label="简化周转率(%)" align="center" prop="simpleTurnoverRate" />
        <el-table-column label="周转评价" align="center" prop="turnoverEvaluation">
          <template #default="scope">
            <el-tag :type="getTurnoverEvaluationType(scope.row.turnoverEvaluation)">
              {{ scope.row.turnoverEvaluation }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup name="InventoryTurnover" lang="ts">
import { getInventoryTurnover, exportInventoryTurnover } from '@/api/wms/report';
import { listBaseMaterialCategoryInWMS } from '@/api/wms/baseMaterialCategory';
import { InventoryTurnoverVO, 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<InventoryTurnoverVO[]>([]);
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 turnoverStats = ref({
  fast: 0,
  normal: 0,
  slow: 0,
  noFlow: 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 getInventoryTurnover(queryParams.value);
  reportList.value = res.data;
  loading.value = false;

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

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

/** 计算统计数据 */
const calculateStats = () => {
  turnoverStats.value = {
    fast: reportList.value.filter(item => item.turnoverEvaluation === '快速周转').length,
    normal: reportList.value.filter(item => item.turnoverEvaluation === '正常周转').length,
    slow: reportList.value.filter(item => item.turnoverEvaluation === '缓慢周转').length,
    noFlow: reportList.value.filter(item => item.turnoverEvaluation === '无流动').length
  };
};

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

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

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

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

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

/** 获取周转评价类型 */
const getTurnoverEvaluationType = (evaluation: string) => {
  switch (evaluation) {
    case '快速周转': return 'success';
    case '正常周转': return 'primary';
    case '缓慢周转': return 'warning';
    case '无流动': return 'danger';
    default: 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 evaluationCount = reportList.value.reduce((acc, item) => {
    const evaluation = item.turnoverEvaluation || '未知';
    acc[evaluation] = (acc[evaluation] || 0) + 1;
    return acc;
  }, {} as Record<string, number>);

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

  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)'
          }
        }
      }
    ]
  };

  // 柱状图：周转率排行（取前10名）
  const sortedData = [...reportList.value]
    .sort((a, b) => (b.inventoryTurnoverRate || 0) - (a.inventoryTurnoverRate || 0))
    .slice(0, 10);

  const barCategories = sortedData.map(item => item.materialCode);
  const barData = sortedData.map(item => item.inventoryTurnoverRate);

  const barOption = {
    title: {
      text: '库存周转率排行（前10名）',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      formatter: '{b}<br/>周转率: {c}%'
    },
    xAxis: {
      type: 'category',
      data: barCategories,
      axisLabel: {
        rotate: 45
      }
    },
    yAxis: {
      type: 'value',
      name: '周转率(%)'
    },
    series: [
      {
        name: '周转率',
        type: 'bar',
        data: barData,
        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>
