<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="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="returnReasonCategory" />
        <el-table-column label="退库单数" align="center" prop="returnOrderCount" />
        <el-table-column label="退库总数量" align="center" prop="totalReturnAmount" />
        <el-table-column label="退库单数占比(%)" align="center" prop="orderCountRatio" />
        <el-table-column label="退库数量占比(%)" align="center" prop="amountRatio" />
        <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="materialCode" />
      </el-table>
    </el-card>
  </div>
</template>

<script setup name="ReturnReasonAnalysis" lang="ts">
import { getReturnReasonAnalysis, exportReturnReasonAnalysis } from '@/api/wms/report';
import { listBaseMaterialCategoryInWMS } from '@/api/wms/baseMaterialCategory';
import { ReturnReasonAnalysisVO, 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<ReturnReasonAnalysisVO[]>([]);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const materialCategoryOptions = ref<BaseMaterialCategoryVO[]>([]);

// 图表引用
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 getReturnReasonAnalysis(queryParams.value);
  reportList.value = res.data;
  loading.value = false;

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

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

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

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

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

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

/** 初始化图表 */
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 pieData = reportList.value.map(item => ({
    name: item.returnReasonCategory,
    value: item.returnOrderCount
  }));

  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 barData = reportList.value.map(item => item.totalReturnAmount);
  const barCategories = reportList.value.map(item => item.returnReasonCategory);

  const barOption = {
    title: {
      text: '退库数量统计',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: barCategories,
      axisLabel: {
        rotate: 45
      }
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '退库数量',
        type: 'bar',
        data: barData,
        itemStyle: {
          color: '#409EFF'
        }
      }
    ]
  };

  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;
}
</style>
