<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-red-500">{{ alertStats.shortage }}</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">{{ alertStats.belowSafety }}</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-yellow-500">{{ alertStats.overstock }}</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-green-500">{{ alertStats.normal }}</div>
              <div class="stat-label">正常</div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 图表展示区域 -->
      <el-row :gutter="20" class="mb-4">
        <el-col :span="24">
          <el-card shadow="hover">
            <template #header>
              <span>安全库存预警分布</span>
            </template>
            <div ref="chartRef" 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="currentInventoryQty" />
<!--        <el-table-column label="安全库存值" align="center" prop="safeStockAmount" />-->
        <el-table-column label="最小库存值" align="center" prop="minStockAmount" />
        <el-table-column label="最大库存值" align="center" prop="maxStockAmount" />
        <el-table-column label="预警状态" align="center" prop="alertStatus">
          <template #default="scope">
            <el-tag :type="getAlertType(scope.row.alertStatus)">
              {{ scope.row.alertStatus }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="差异量" align="center" prop="differenceAmount" />
        <el-table-column label="最后更新时间" align="center" prop="lastUpdateTime" width="180" />
      </el-table>
    </el-card>
  </div>
</template>

<script setup name="SafetyStockAlert" lang="ts">
import { getSafetyStockAlert, exportSafetyStockAlert } from '@/api/wms/report';
import { listBaseMaterialCategoryInWMS } from '@/api/wms/baseMaterialCategory';
import { SafetyStockAlertVO, 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<SafetyStockAlertVO[]>([]);
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 alertStats = ref({
  shortage: 0,
  belowSafety: 0,
  overstock: 0,
  normal: 0
});

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

const queryFormRef = ref<ElFormInstance>();

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

/** 查询安全库存预警报表列表 */
const getList = async () => {
  loading.value = true;
  const res = await getSafetyStockAlert(queryParams.value);
  reportList.value = res.data;
  loading.value = false;

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

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

/** 计算统计数据 */
const calculateStats = () => {
  alertStats.value = {
    shortage: reportList.value.filter(item => item.alertStatus === '短缺预警').length,
    belowSafety: reportList.value.filter(item => item.alertStatus === '低于安全库存').length,
    overstock: reportList.value.filter(item => item.alertStatus === '积压预警').length,
    normal: reportList.value.filter(item => item.alertStatus === '正常').length
  };
};

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

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

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

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

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

/** 获取预警状态类型 */
const getAlertType = (status: string) => {
  switch (status) {
    case '短缺预警': return 'danger';
    case '低于安全库存': return 'warning';
    case '积压预警': return 'info';
    case '正常': return 'success';
    default: return '';
  }
};

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

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

  // 按预警状态统计
  const statusCount = reportList.value.reduce((acc, item) => {
    const status = item.alertStatus || '未知';
    acc[status] = (acc[status] || 0) + 1;
    return acc;
  }, {} as Record<string, number>);

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

  const option = {
    title: {
      text: '安全库存预警分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '预警状态',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 20,
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: pieData
      }
    ]
  };

  chart.setOption(option);
};

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

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

onUnmounted(() => {
  window.removeEventListener('resize', handleResize);
  chart?.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>
