<template>
  <div class="department-efficiency-view">
    <!-- 1. 页面头部 -->
    <header class="page-header">
      <h1 class="page-title">综合运营分析</h1>
      <p class="page-description">分析各部门的平均销售额与渠道商品多样性。</p>
    </header>

    <!-- 2. 部门运营效率分析 -->
    <section class="chart-area">
      <div v-if="barChart.loading" class="status-overlay">
        <p>hina正在努力加载部门效率数据中...</p>
      </div>
      <div v-else-if="barChart.error" class="status-overlay error">
        <p>部门效率数据加载失败</p>
        <p class="error-message">{{ barChart.error }}</p>
      </div>
      <div ref="barChartRef" style="width: 100%; height: 500px;"></div>
    </section>

    <!-- 3. 渠道商品多样性分析 -->
    <section class="chart-area">
      <div v-if="pieChart.loading" class="status-overlay">
        <p>hina正在努力加载渠道多样性数据中...</p>
      </div>
      <div v-else-if="pieChart.error" class="status-overlay error">
        <p>渠道多样性数据加载失败</p>
        <p class="error-message">{{ pieChart.error }}</p>
      </div>
      <div ref="pieChartRef" style="width: 100%; height: 500px;"></div>
    </section>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import { getShopChannelDiversity, getShopDepartmentEfficiency } from '@/api/order';

export default {
  name: 'OrderEfficiency',
  data() {
    return {
      barChartInstance: null,
      pieChartInstance: null,
      barChart: { loading: true, error: null },
      pieChart: { loading: true, error: null }
    };
  },
  mounted() {
    this.initBarChart();
    this.initPieChart();
    window.addEventListener('resize', this.handleResize);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize);
    if (this.barChartInstance) this.barChartInstance.dispose();
    if (this.pieChartInstance) this.pieChartInstance.dispose();
  },
  methods: {
    async initBarChart() {
      this.barChart.loading = true;
      try {
        const response = await axios.get('/api/shop/import/department-efficiency');
        if (!response.data || !response.data.success) {
          throw new Error(response.data.message || 'REPLACED__');
        }
        const rawData = response.data;
        const chartData = Object.entries(rawData).map(([name, value]) => ({
          name,
          value: parseFloat(value).toFixed(2)
        }));

        await this.$nextTick();
        const chartEl = this.$refs.barChartRef;
        if (chartEl) {
          this.barChartInstance = echarts.init(chartEl);
          const option = {
            title: { text: '部门效率分析', left: 'center' },
            tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' }, formatter: '{b}<br/>平均销售额: {c} 元' },
            grid: { left: '3%', right: '4%', bottom: '15%', containLabel: true },
            xAxis: { type: 'category', data: chartData.map(item => item.name), axisLabel: { rotate: 30, interval: 0 } },
            yAxis: { type: 'value', name: '平均销售额(元)' },
            series: [{
              name: '平均销售额',
              type: 'bar',
              data: chartData.map(item => item.value),
              barWidth: '40%',
              itemStyle: {
                borderRadius: [5, 5, 0, 0],
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: '#83bff6' },
                  { offset: 1, color: '#188df0' }
                ])
              }
            }]
          };
          this.barChartInstance.setOption(option);
        }
      } catch (err) {
        this.barChart.error = err.message || '部门效率数据加载失败';
      } finally {
        this.barChart.loading = false;
      }
    },
    async initPieChart() {
      this.pieChart.loading = true;
      try {
        const response = await axios.get('/api/shop/import/channel-diversity');
        if (!response.data || !response.data.success) {
          throw new Error(response.data.message || '渠道多样性数据获取失败');
        }
        const rawData = response.data;
        const chartData = Object.entries(rawData).map(([name, value]) => ({ name, value }));

        await this.$nextTick();
        const chartEl = this.$refs.pieChartRef;
        if (chartEl) {
          this.pieChartInstance = echarts.init(chartEl);
          const option = {
            title: { text: '渠道商品多样性', left: 'center' },
            tooltip: { trigger: 'item', formatter: '{a} <br/>{b} : {c} ({d}%)' },
            legend: { orient: 'vertical', left: 'left', top: '10%' },
            series: [{
              name: '渠道',
              type: 'pie',
              radius: [20, 140],
              center: ['50%', '60%'],
              roseType: 'area',
              itemStyle: { borderRadius: 5 },
              data: chartData
            }]
          };
          this.pieChartInstance.setOption(option);
        }
      } catch (err) {
        this.pieChart.error = err.message || '渠道多样性数据加载失败';
      } finally {
        this.pieChart.loading = false;
      }
    },
    handleResize() {
      if (this.barChartInstance) this.barChartInstance.resize();
      if (this.pieChartInstance) this.pieChartInstance.resize();
    }
  }
};
</script>


<style scoped>
.department-efficiency-view {
  display: flex;
  flex-direction: column;
  gap: 20px;
  padding: 20px;
}
.page-header {
  padding: 15px 20px;
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}
.page-title {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #333;
}
.page-description {
  margin: 4px 0 0;
  font-size: 14px;
  color: #666;
}
.chart-area {
  position: relative;
  padding: 20px;
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  min-height: 540px;
}
.status-overlay {
  position: absolute;
  inset: 0; /* a shorthand for top, right, bottom, left */
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: rgba(255, 255, 255, 0.8);
  border-radius: 8px;
  z-index: 10;
  color: #555;
  font-size: 16px;
}
.status-overlay.error {
  color: #f56c6c;
}
.error-message {
  font-size: 14px;
  color: #999;
  margin-top: 8px;
}
</style>
// __MARKER__
