<template>
  <div class="business-unit-dashboard">
    <!-- 顶部状态栏 & 筛选器 -->
    <div class="cockpit-header">
      <div class="header-left">
        <h1 class="page-title">事业部驾驶舱 <span class="subtitle">实时经营态势感知</span></h1>
      </div>
      <div class="header-right">
        <el-form :inline="true" class="search-form-compact">
          <el-form-item label="时间范围">
            <el-date-picker v-model="query.month" type="month" value-format="yyyy-MM" placeholder="选择年月" size="mini"
              style="width: 150px;" @change="handleMonthChange" />
          </el-form-item>
          <el-form-item label="事业部">
            <el-select v-model="query.businessUnitId" placeholder="请选择事业部" filterable clearable
              @change="handleBusinessUnitChange" size="mini" style="width: 150px;">
              <el-option v-for="dept in businessUnitOptions" :key="dept.Id || dept.id"
                :label="dept.FullName || dept.fullName" :value="dept.Id || dept.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="mini" icon="el-icon-refresh" @click="search()">更新看板</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>

    <!-- KPI 指标区域 -->
    <el-row :gutter="16" class="kpi-row">
      <el-col :span="6" v-for="(kpi, index) in allKpiList" :key="index">
        <div class="kpi-card" :class="kpi.type" @click="kpi.clickable ? scrollToDetailList(kpi) : null" :style="{ cursor: kpi.clickable ? 'pointer' : 'default' }">
          <div class="kpi-icon"><i :class="kpi.icon"></i></div>
          <div class="kpi-info">
            <el-tooltip v-if="kpi.tooltip" class="item" effect="dark" :content="kpi.tooltip" placement="right-start">
              <div class="kpi-label">{{ kpi.label }}</div>
            </el-tooltip>
            <div v-else class="kpi-label">{{ kpi.label }}</div>
            <div class="kpi-value">
              <span class="unit" v-if="kpi.isMoney">￥</span>
              {{ kpi.value }}
              <span class="unit" v-if="kpi.isPercent">%</span>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 第三层：深度分析区 (趋势 + 分布) -->
    <el-row :gutter="16" class="analysis-row">
      <!-- 业绩趋势 -->
      <el-col :span="16">
        <el-card class="dashboard-card" shadow="hover">
          <div slot="header" class="card-title">
            <span><i class="el-icon-data-line"></i> 业绩趋势</span>
            <el-radio-group v-model="trendMonthCount" size="mini" style="float: right" @change="handleTrendMonthCountChange">
              <el-radio-button :label="3">近3月</el-radio-button>
              <el-radio-button :label="6">近6月</el-radio-button>
              <el-radio-button :label="12">近12月</el-radio-button>
            </el-radio-group>
          </div>
          <div id="performanceTrendChart" class="chart-box"></div>
        </el-card>
      </el-col>
      <!-- 门店业绩分布 -->
      <el-col :span="8">
        <el-card class="dashboard-card" shadow="hover">
          <div slot="header" class="card-title">
            <span><i class="el-icon-pie-chart"></i> 门店业绩分布</span>
          </div>
          <div id="storeDistributionChart" class="chart-box"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 经理分布和趋势 -->
    <el-row :gutter="16" class="analysis-row" v-if="managerDistribution.DistributionData && managerDistribution.DistributionData.length > 0">
      <!-- 经理业绩分布 -->
      <el-col :span="8">
        <el-card class="dashboard-card" shadow="hover">
          <div slot="header" class="card-title">
            <span><i class="el-icon-pie-chart"></i> 经理业绩分布</span>
          </div>
          <div id="managerDistributionChart" class="chart-box"></div>
        </el-card>
      </el-col>
      <!-- 经理业绩趋势 -->
      <el-col :span="16">
        <el-card class="dashboard-card" shadow="hover">
          <div slot="header" class="card-title">
            <span><i class="el-icon-data-line"></i> 经理业绩趋势</span>
            <el-radio-group v-model="trendMonthCount" size="mini" style="float: right" @change="handleTrendMonthCountChange">
              <el-radio-button :label="3">近3月</el-radio-button>
              <el-radio-button :label="6">近6月</el-radio-button>
              <el-radio-button :label="12">近12月</el-radio-button>
            </el-radio-group>
          </div>
          <div id="managerTrendChart" class="chart-box"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 第五层：竞技排行区 -->
    <el-row :gutter="16" class="ranking-row">
      <!-- 门店排行榜 -->
      <el-col :span="12">
        <el-card class="dashboard-card" shadow="hover">
          <div slot="header" class="card-title"><span><i class="el-icon-office-building"></i> 门店业绩排行</span></div>
          <el-table :data="storeRanking" size="mini" style="width: 100%">
            <el-table-column type="index" label="排名" width="60"></el-table-column>
            <el-table-column prop="StoreName" label="门店名称"></el-table-column>
            <el-table-column prop="NetPerformance" label="净业绩" align="right">
              <template slot-scope="scope">￥{{ formatMoney(scope.row.NetPerformance) }}</template>
            </el-table-column>
            <el-table-column prop="CompletionRate" label="完成率" width="100" align="right">
              <template slot-scope="scope">{{ formatPercent(scope.row.CompletionRate) }}%</template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
      <!-- 经理排行 -->
      <el-col :span="12">
        <el-card class="dashboard-card" shadow="hover">
          <div slot="header" class="card-title"><span><i class="el-icon-user"></i> 经理业绩排行</span></div>
          <el-table :data="managerRanking" size="mini" style="width: 100%">
            <el-table-column type="index" label="排名" width="60"></el-table-column>
            <el-table-column prop="ManagerName" label="经理姓名"></el-table-column>
            <el-table-column prop="TotalBillingPerformance" label="总业绩" align="right">
              <template slot-scope="scope">￥{{ formatMoney(scope.row.TotalBillingPerformance) }}</template>
            </el-table-column>
            <el-table-column prop="ManagedStoreCount" label="管理门店数" width="100" align="right">
              <template slot-scope="scope">{{ scope.row.ManagedStoreCount || 0 }}</template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <!-- 店长和健康师排行 -->
    <el-row :gutter="16" class="ranking-row" v-if="storeManagerRanking.length > 0 || healthCoachRanking.length > 0">
      <!-- 店长排行 -->
      <el-col :span="12" v-if="storeManagerRanking.length > 0">
        <el-card class="dashboard-card" shadow="hover">
          <div slot="header" class="card-title"><span><i class="el-icon-user-solid"></i> 店长业绩排行</span></div>
          <el-table :data="storeManagerRanking" size="mini" style="width: 100%">
            <el-table-column type="index" label="排名" width="60"></el-table-column>
            <el-table-column prop="StoreManagerName" label="店长姓名"></el-table-column>
            <el-table-column prop="StoreName" label="门店"></el-table-column>
            <el-table-column prop="TotalPerformance" label="总业绩" align="right">
              <template slot-scope="scope">￥{{ formatMoney(scope.row.TotalPerformance) }}</template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
      <!-- 健康师排行 -->
      <el-col :span="12" v-if="healthCoachRanking.length > 0">
        <el-card class="dashboard-card" shadow="hover">
          <div slot="header" class="card-title"><span><i class="el-icon-user"></i> 健康师业绩排行</span></div>
          <el-table :data="healthCoachRanking" size="mini" style="width: 100%">
            <el-table-column type="index" label="排名" width="60"></el-table-column>
            <el-table-column prop="HealthCoachName" label="健康师姓名"></el-table-column>
            <el-table-column prop="StoreName" label="门店"></el-table-column>
            <el-table-column prop="TotalPerformance" label="总业绩" align="right">
              <template slot-scope="scope">￥{{ formatMoney(scope.row.TotalPerformance) }}</template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <!-- 第六层：运营统计 -->
    <el-row :gutter="16" class="insight-row">
      <el-col :span="8">
        <el-card class="dashboard-card" shadow="hover">
          <div slot="header" class="card-title"><span><i class="el-icon-shopping-cart-2"></i> 开单分析</span></div>
          <div class="operation-stats">
            <div class="stat-item">
              <div class="stat-label">开单次数</div>
              <div class="stat-value">{{ formatNumber((operationStatistics && operationStatistics.BillingAnalysis && operationStatistics.BillingAnalysis.BillingCount) || 0) }}</div>
            </div>
            <div class="stat-item">
              <div class="stat-label">平均开单金额</div>
              <div class="stat-value">￥{{ formatMoney((operationStatistics && operationStatistics.BillingAnalysis && operationStatistics.BillingAnalysis.AverageBillingAmount) || 0) }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card class="dashboard-card" shadow="hover">
          <div slot="header" class="card-title"><span><i class="el-icon-medal"></i> 消耗分析</span></div>
          <div class="operation-stats">
            <div class="stat-item">
              <div class="stat-label">消耗次数</div>
              <div class="stat-value">{{ formatNumber((operationStatistics && operationStatistics.ConsumeAnalysis && operationStatistics.ConsumeAnalysis.ConsumeCount) || 0) }}</div>
            </div>
            <div class="stat-item">
              <div class="stat-label">消耗金额</div>
              <div class="stat-value">￥{{ formatMoney((operationStatistics && operationStatistics.ConsumeAnalysis && operationStatistics.ConsumeAnalysis.ConsumeAmount) || 0) }}</div>
            </div>
            <div class="stat-item">
              <div class="stat-label">消耗率</div>
              <div class="stat-value">{{ formatPercent((operationStatistics && operationStatistics.ConsumeAnalysis && operationStatistics.ConsumeAnalysis.ConsumeRate) || 0) }}%</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card class="dashboard-card" shadow="hover">
          <div slot="header" class="card-title"><span><i class="el-icon-warning-outline"></i> 退卡分析</span></div>
          <div class="operation-stats">
            <div class="stat-item">
              <div class="stat-label">退卡次数</div>
              <div class="stat-value">{{ formatNumber((operationStatistics && operationStatistics.RefundAnalysis && operationStatistics.RefundAnalysis.RefundCount) || 0) }}</div>
            </div>
            <div class="stat-item">
              <div class="stat-label">退卡金额</div>
              <div class="stat-value">￥{{ formatMoney((operationStatistics && operationStatistics.RefundAnalysis && operationStatistics.RefundAnalysis.RefundAmount) || 0) }}</div>
            </div>
            <div class="stat-item">
              <div class="stat-label">退卡率</div>
              <div class="stat-value">{{ formatPercent((operationStatistics && operationStatistics.RefundAnalysis && operationStatistics.RefundAnalysis.RefundRate) || 0) }}%</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 第七层：对比分析 -->
    <el-row :gutter="16" class="insight-row">
      <el-col :span="24">
        <el-card class="dashboard-card" shadow="hover">
          <div slot="header" class="card-title"><span><i class="el-icon-s-data"></i> 对比分析</span></div>
          <div class="comparison-content">
            <div class="comparison-section">
              <h4>环比对比（与上月对比）</h4>
              <el-row :gutter="16">
                <el-col :span="6">
                  <div class="comparison-item">
                    <div class="comparison-label">开单业绩变化率</div>
                    <div class="comparison-value" :class="getComparisonClass(monthOverMonthComparison.BillingPerformanceChangeRate)">
                      {{ formatPercent(monthOverMonthComparison.BillingPerformanceChangeRate) }}%
                    </div>
                  </div>
                </el-col>
                <el-col :span="6">
                  <div class="comparison-item">
                    <div class="comparison-label">消耗业绩变化率</div>
                    <div class="comparison-value" :class="getComparisonClass(monthOverMonthComparison.ConsumePerformanceChangeRate)">
                      {{ formatPercent(monthOverMonthComparison.ConsumePerformanceChangeRate) }}%
                    </div>
                  </div>
                </el-col>
                <el-col :span="6">
                  <div class="comparison-item">
                    <div class="comparison-label">净业绩变化率</div>
                    <div class="comparison-value" :class="getComparisonClass(monthOverMonthComparison.NetPerformanceChangeRate)">
                      {{ formatPercent(monthOverMonthComparison.NetPerformanceChangeRate) }}%
                    </div>
                  </div>
                </el-col>
                <el-col :span="6">
                  <div class="comparison-item">
                    <div class="comparison-label">完成率变化</div>
                    <div class="comparison-value" :class="getComparisonClass(monthOverMonthComparison.CompletionRateChange)">
                      {{ formatPercent(monthOverMonthComparison.CompletionRateChange) }}%
                    </div>
                  </div>
                </el-col>
              </el-row>
            </div>
            <div class="comparison-section">
              <h4>同比对比（与去年同月对比）</h4>
              <el-row :gutter="16">
                <el-col :span="6">
                  <div class="comparison-item">
                    <div class="comparison-label">开单业绩变化率</div>
                    <div class="comparison-value" :class="getComparisonClass(yearOverYearComparison.BillingPerformanceChangeRate)">
                      {{ formatPercent(yearOverYearComparison.BillingPerformanceChangeRate) }}%
                    </div>
                  </div>
                </el-col>
                <el-col :span="6">
                  <div class="comparison-item">
                    <div class="comparison-label">消耗业绩变化率</div>
                    <div class="comparison-value" :class="getComparisonClass(yearOverYearComparison.ConsumePerformanceChangeRate)">
                      {{ formatPercent(yearOverYearComparison.ConsumePerformanceChangeRate) }}%
                    </div>
                  </div>
                </el-col>
                <el-col :span="6">
                  <div class="comparison-item">
                    <div class="comparison-label">净业绩变化率</div>
                    <div class="comparison-value" :class="getComparisonClass(yearOverYearComparison.NetPerformanceChangeRate)">
                      {{ formatPercent(yearOverYearComparison.NetPerformanceChangeRate) }}%
                    </div>
                  </div>
                </el-col>
                <el-col :span="6">
                  <div class="comparison-item">
                    <div class="comparison-label">完成率变化</div>
                    <div class="comparison-value" :class="getComparisonClass(yearOverYearComparison.CompletionRateChange)">
                      {{ formatPercent(yearOverYearComparison.CompletionRateChange) }}%
                    </div>
                  </div>
                </el-col>
              </el-row>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 明细列表 - 第一行 -->
    <el-row class="detail-list-row" :gutter="16">
      <!-- 门店明细列表 -->
      <el-col id="store-detail-list" :span="12">
        <el-card class="dashboard-card" shadow="hover">
          <div slot="header" class="card-header">
            <span class="card-title">门店明细列表</span>
          </div>
          <el-table
            :data="storeDetailList.data"
            v-loading="storeDetailList.loading"
            size="mini"
            border
            style="width: 100%"
            :max-height="500">
            <el-table-column prop="StoreName" label="门店名称" width="150"></el-table-column>
            <el-table-column prop="BillingPerformance" label="开单业绩" width="120" align="right">
              <template slot-scope="scope">￥{{ formatMoney(scope.row.BillingPerformance) }}</template>
            </el-table-column>
            <el-table-column prop="ConsumePerformance" label="消耗业绩" width="120" align="right">
              <template slot-scope="scope">￥{{ formatMoney(scope.row.ConsumePerformance) }}</template>
            </el-table-column>
            <el-table-column prop="NetPerformance" label="净业绩" width="120" align="right">
              <template slot-scope="scope">￥{{ formatMoney(scope.row.NetPerformance) }}</template>
            </el-table-column>
            <el-table-column prop="CompletionRate" label="完成率" width="100" align="right">
              <template slot-scope="scope">{{ formatPercent(scope.row.CompletionRate) }}%</template>
            </el-table-column>
          </el-table>
          <div class="detail-pagination" v-if="storeDetailList.pagination.total > 0">
            <el-pagination
              @size-change="handleStoreDetailPageSizeChange"
              @current-change="handleStoreDetailPageChange"
              :current-page="storeDetailList.pagination.currentPage"
              :page-sizes="[10, 20, 50, 100]"
              :page-size="storeDetailList.pagination.pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="storeDetailList.pagination.total">
            </el-pagination>
          </div>
        </el-card>
      </el-col>
      <!-- 经理明细列表 -->
      <el-col id="manager-detail-list" :span="12">
        <el-card class="dashboard-card" shadow="hover">
          <div slot="header" class="card-header">
            <span class="card-title">经理明细列表</span>
          </div>
          <el-table
            :data="managerDetailList.data"
            v-loading="managerDetailList.loading"
            size="mini"
            border
            style="width: 100%"
            :max-height="500">
            <el-table-column prop="ManagerName" label="经理姓名" width="120"></el-table-column>
            <el-table-column prop="ManagedStoreCount" label="管理门店数" width="100" align="right"></el-table-column>
            <el-table-column prop="TotalBillingPerformance" label="总业绩" width="120" align="right">
              <template slot-scope="scope">￥{{ formatMoney(scope.row.TotalBillingPerformance) }}</template>
            </el-table-column>
            <el-table-column prop="TotalConsumePerformance" label="总消耗业绩" width="120" align="right">
              <template slot-scope="scope">￥{{ formatMoney(scope.row.TotalConsumePerformance) }}</template>
            </el-table-column>
          </el-table>
          <div class="detail-pagination" v-if="managerDetailList.pagination.total > 0">
            <el-pagination
              @size-change="handleManagerDetailPageSizeChange"
              @current-change="handleManagerDetailPageChange"
              :current-page="managerDetailList.pagination.currentPage"
              :page-sizes="[10, 20, 50, 100]"
              :page-size="managerDetailList.pagination.pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="managerDetailList.pagination.total">
            </el-pagination>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 明细列表 - 第二行 -->
    <el-row class="detail-list-row" :gutter="16">
      <!-- 店长明细列表 -->
      <el-col id="store-manager-detail-list" :span="12">
        <el-card class="dashboard-card" shadow="hover">
          <div slot="header" class="card-header">
            <span class="card-title">店长明细列表</span>
          </div>
          <el-table
            :data="storeManagerDetailList.data"
            v-loading="storeManagerDetailList.loading"
            size="mini"
            border
            style="width: 100%"
            :max-height="500">
            <el-table-column prop="StoreManagerName" label="店长姓名" width="120"></el-table-column>
            <el-table-column prop="StoreName" label="门店" width="150"></el-table-column>
            <el-table-column prop="TotalPerformance" label="总业绩" width="120" align="right">
              <template slot-scope="scope">￥{{ formatMoney(scope.row.TotalPerformance) }}</template>
            </el-table-column>
          </el-table>
          <div class="detail-pagination" v-if="storeManagerDetailList.pagination.total > 0">
            <el-pagination
              @size-change="handleStoreManagerDetailPageSizeChange"
              @current-change="handleStoreManagerDetailPageChange"
              :current-page="storeManagerDetailList.pagination.currentPage"
              :page-sizes="[10, 20, 50, 100]"
              :page-size="storeManagerDetailList.pagination.pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="storeManagerDetailList.pagination.total">
            </el-pagination>
          </div>
        </el-card>
      </el-col>
      <!-- 健康师明细列表 -->
      <el-col id="health-coach-detail-list" :span="12">
        <el-card class="dashboard-card" shadow="hover">
          <div slot="header" class="card-header">
            <span class="card-title">健康师明细列表</span>
          </div>
          <el-table
            :data="healthCoachDetailList.data"
            v-loading="healthCoachDetailList.loading"
            size="mini"
            border
            style="width: 100%"
            :max-height="500">
            <el-table-column prop="HealthCoachName" label="健康师姓名" width="120"></el-table-column>
            <el-table-column prop="StoreName" label="门店" width="150"></el-table-column>
            <el-table-column prop="TotalPerformance" label="总业绩" width="120" align="right">
              <template slot-scope="scope">￥{{ formatMoney(scope.row.TotalPerformance) }}</template>
            </el-table-column>
          </el-table>
          <div class="detail-pagination" v-if="healthCoachDetailList.pagination.total > 0">
            <el-pagination
              @size-change="handleHealthCoachDetailPageSizeChange"
              @current-change="handleHealthCoachDetailPageChange"
              :current-page="healthCoachDetailList.pagination.currentPage"
              :page-sizes="[10, 20, 50, 100]"
              :page-size="healthCoachDetailList.pagination.pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="healthCoachDetailList.pagination.total">
            </el-pagination>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import request from '@/utils/request'
import * as echarts from 'echarts'
import dayjs from 'dayjs'

export default {
  name: 'BusinessUnitDashboard',
  data() {
    return {
      query: {
        month: dayjs().format('YYYY-MM'),
        businessUnitId: undefined
      },
      businessUnitOptions: [],
      trendMonthCount: 12,
      loading: false,
      charts: {},
      // 统计数据
      statistics: {},
      performanceTrend: { TrendData: [] },
      storeRanking: [],
      storeDistribution: { DistributionData: [] },
      managerRanking: [],
      operationStatistics: {
        BillingAnalysis: {},
        ConsumeAnalysis: {},
        RefundAnalysis: {}
      },
      comparisonAnalysis: {
        TimeComparison: {
          MonthOverMonth: {},
          YearOverYear: {}
        }
      },
      // 经理分布和趋势
      managerDistribution: { DistributionData: [] },
      managerTrend: { ManagerTrendData: [] },
      // 店长和健康师排行
      storeManagerRanking: [],
      healthCoachRanking: [],
      // 明细列表数据
      storeDetailList: {
        loading: false,
        data: [],
        pagination: {
          currentPage: 1,
          pageSize: 20,
          total: 0
        }
      },
      managerDetailList: {
        loading: false,
        data: [],
        pagination: {
          currentPage: 1,
          pageSize: 20,
          total: 0
        }
      },
      storeManagerDetailList: {
        loading: false,
        data: [],
        pagination: {
          currentPage: 1,
          pageSize: 20,
          total: 0
        }
      },
      healthCoachDetailList: {
        loading: false,
        data: [],
        pagination: {
          currentPage: 1,
          pageSize: 20,
          total: 0
        }
      }
    }
  },
  computed: {
    // 合并所有 KPI 为一个数组，一行显示4个
    allKpiList() {
      return [...this.kpiList, ...this.categoryKpiList]
    },
    kpiList() {
      const d = this.statistics || {}
      return [
        {
          tooltip: '开单实付业绩总和',
          key: 'billing',
          label: '开单业绩',
          value: this.formatMoney(d.BillingPerformance),
          raw: d.BillingPerformance || 0,
          icon: 'el-icon-wallet',
          type: 'primary',
          isMoney: true,
          clickable: true
        },
        {
          tooltip: '消耗金额总和',
          key: 'consume',
          label: '消耗业绩',
          value: this.formatMoney(d.ConsumePerformance),
          raw: d.ConsumePerformance || 0,
          icon: 'el-icon-medal',
          type: 'success',
          isMoney: true,
          clickable: true
        },
        {
          tooltip: '开单业绩 - 退卡金额',
          key: 'net',
          label: '净业绩',
          value: this.formatMoney(d.NetPerformance),
          raw: d.NetPerformance || 0,
          icon: 'el-icon-trophy',
          type: 'warning',
          isMoney: true,
          clickable: true
        },
        {
          tooltip: '管理的所有门店的事业部业绩目标总和',
          key: 'target',
          label: '目标业绩',
          value: this.formatMoney(d.TargetPerformance),
          raw: d.TargetPerformance || 0,
          icon: 'el-icon-aim',
          type: 'info',
          isMoney: true,
          clickable: true
        },
        {
          tooltip: '净业绩 / 目标业绩 × 100%',
          key: 'completion',
          label: '完成率',
          value: this.formatPercent(d.CompletionRate),
          raw: d.CompletionRate || 0,
          icon: 'el-icon-data-line',
          type: d.CompletionRate >= 100 ? 'success' : 'danger',
          isPercent: true,
          clickable: true
        },
        {
          tooltip: '管理的门店数量',
          key: 'managed',
          label: '管理门店数',
          value: d.ManagedStoreCount || 0,
          raw: d.ManagedStoreCount || 0,
          icon: 'el-icon-office-building',
          type: 'info',
          isMoney: false,
          clickable: true
        },
        {
          tooltip: '有开单或消耗的门店数量',
          key: 'active',
          label: '活跃门店数',
          value: d.ActiveStoreCount || 0,
          raw: d.ActiveStoreCount || 0,
          icon: 'el-icon-success',
          type: 'success',
          isMoney: false,
          clickable: true
        },
        {
          tooltip: '退卡实退金额总和',
          key: 'refund',
          label: '退卡金额',
          value: this.formatMoney(d.RefundAmount),
          raw: d.RefundAmount || 0,
          icon: 'el-icon-warning-outline',
          type: 'danger',
          isMoney: true,
          clickable: true
        }
      ]
    },
    categoryKpiList() {
      const d = this.statistics || {}
      return [
        {
          key: 'lifeBeauty',
          label: '生美业绩',
          value: this.formatMoney(d.LifeBeautyPerformance),
          raw: d.LifeBeautyPerformance || 0,
          icon: 'el-icon-star-on',
          type: 'primary',
          isMoney: true,
          clickable: false
        },
        {
          key: 'techBeauty',
          label: '科美业绩',
          value: this.formatMoney(d.TechBeautyPerformance),
          raw: d.TechBeautyPerformance || 0,
          icon: 'el-icon-star-on',
          type: 'success',
          isMoney: true,
          clickable: false
        },
        {
          key: 'medicalBeauty',
          label: '医美业绩',
          value: this.formatMoney(d.MedicalBeautyPerformance),
          raw: d.MedicalBeautyPerformance || 0,
          icon: 'el-icon-star-on',
          type: 'warning',
          isMoney: true,
          clickable: false
        },
        {
          key: 'product',
          label: '产品业绩',
          value: this.formatMoney(d.ProductPerformance),
          raw: d.ProductPerformance || 0,
          icon: 'el-icon-star-on',
          type: 'info',
          isMoney: true,
          clickable: false
        }
      ]
    },
    // 对比分析数据简化
    monthOverMonthComparison() {
      if (!this.comparisonAnalysis || !this.comparisonAnalysis.TimeComparison || !this.comparisonAnalysis.TimeComparison.MonthOverMonth) {
        return {
          BillingPerformanceChangeRate: 0,
          ConsumePerformanceChangeRate: 0,
          NetPerformanceChangeRate: 0,
          CompletionRateChange: 0
        }
      }
      const data = this.comparisonAnalysis.TimeComparison.MonthOverMonth
      return {
        BillingPerformanceChangeRate: (data.BillingPerformance && data.BillingPerformance.GrowthRate) || 0,
        ConsumePerformanceChangeRate: (data.ConsumePerformance && data.ConsumePerformance.GrowthRate) || 0,
        NetPerformanceChangeRate: (data.NetPerformance && data.NetPerformance.GrowthRate) || 0,
        CompletionRateChange: (data.CompletionRate && data.CompletionRate.GrowthRate) || 0
      }
    },
    yearOverYearComparison() {
      if (!this.comparisonAnalysis || !this.comparisonAnalysis.TimeComparison || !this.comparisonAnalysis.TimeComparison.YearOverYear) {
        return {
          BillingPerformanceChangeRate: 0,
          ConsumePerformanceChangeRate: 0,
          NetPerformanceChangeRate: 0,
          CompletionRateChange: 0
        }
      }
      const data = this.comparisonAnalysis.TimeComparison.YearOverYear
      return {
        BillingPerformanceChangeRate: (data.BillingPerformance && data.BillingPerformance.GrowthRate) || 0,
        ConsumePerformanceChangeRate: (data.ConsumePerformance && data.ConsumePerformance.GrowthRate) || 0,
        NetPerformanceChangeRate: (data.NetPerformance && data.NetPerformance.GrowthRate) || 0,
        CompletionRateChange: (data.CompletionRate && data.CompletionRate.GrowthRate) || 0
      }
    }
  },
  watch: {
    trendMonthCount() {
      this.loadPerformanceTrend()
      this.loadManagerTrend()
    }
  },
  async mounted() {
    await this.loadBusinessUnitOptions()
    // 如果列表有数据且未选择事业部，默认选择第一个
    if (this.businessUnitOptions.length > 0 && !this.query.businessUnitId) {
      const firstDept = this.businessUnitOptions[0]
      this.query.businessUnitId = firstDept.Id || firstDept.id
    }
    if (this.query.businessUnitId) {
      this.search()
    }
    window.addEventListener('resize', this.handleResize)
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize)
    Object.values(this.charts).forEach(c => c && c.dispose())
  },
  methods: {
    // 年月选择器变化处理
    handleMonthChange() {
    },
    // 事业部变化处理
    handleBusinessUnitChange() {
      // 事业部变化时自动刷新数据
      if (this.query.businessUnitId) {
        this.search()
      }
    },
    // 趋势月份数量变化
    handleTrendMonthCountChange() {
      // watch中已处理
    },
    // 加载事业部选项
    async loadBusinessUnitOptions() {
      try {
        const res = await request({
          url: '/api/Extend/Organize/GetByName',
          method: 'GET',
          data: {
            organizeName: '事业部'
          }
        })
        this.businessUnitOptions = res.data || []
      } catch (error) {
        console.error('加载事业部列表失败:', error)
        this.businessUnitOptions = []
      }
    },
    // 主搜索方法
    async search() {
      if (!this.query.month) {
        this.$message.warning('请选择月份')
        return
      }
      if (!this.query.businessUnitId) {
        this.$message.warning('请选择事业部')
        return
      }
      try {
        this.loading = true
        const statisticsMonth = this.query.month.replace('-', '')
        const params = {
          statisticsMonth,
          businessUnitId: this.query.businessUnitId,
          storeIds: []
        }
        await Promise.all([
          this.loadStatistics(params),
          this.loadPerformanceTrend(),
          this.loadStoreRanking(params),
          this.loadStoreDistribution(params),
          this.loadManagerRanking(params),
          this.loadManagerDistribution(params),
          this.loadManagerTrend(),
          this.loadStoreManagerRanking(params),
          this.loadHealthCoachRanking(params),
          this.loadOperationStatistics(params),
          this.loadComparisonAnalysis(params),
          this.loadStoreDetailList(params),
          this.loadManagerDetailList(params),
          this.loadStoreManagerDetailList(params),
          this.loadHealthCoachDetailList(params)
        ])
        await this.$nextTick()
        this.initAllCharts()
      } catch (error) {
        console.error('加载数据失败:', error)
        this.$message.error('数据加载失败，请重试')
      } finally {
        this.loading = false
      }
    },
    // 加载统计数据
    async loadStatistics(params) {
      try {
        const res = await request({
          url: '/api/Extend/LqBusinessUnitDashboard/GetStatistics',
          method: 'POST',
          data: params
        })
        if (res.code === 200) {
          this.statistics = res.data || {}
        }
      } catch (error) {
        console.error('加载统计数据失败:', error)
      }
    },
    // 加载业绩趋势
    async loadPerformanceTrend() {
      if (!this.query.month) return
      try {
        const statisticsMonth = this.query.month.replace('-', '')
        const res = await request({
          url: '/api/Extend/LqBusinessUnitDashboard/GetPerformanceTrend',
          method: 'POST',
          data: {
            statisticsMonth,
            businessUnitId: this.query.businessUnitId,
            storeIds: [],
            monthCount: this.trendMonthCount
          }
        })
        if (res.code === 200) {
          this.performanceTrend = res.data || { TrendData: [] }
          this.$nextTick(() => {
            this.renderPerformanceTrendChart()
          })
        }
      } catch (error) {
        console.error('加载业绩趋势失败:', error)
      }
    },
    // 加载门店排行
    async loadStoreRanking(params) {
      try {
        const res = await request({
          url: '/api/Extend/LqBusinessUnitDashboard/GetStoreRanking',
          method: 'POST',
          data: params
        })
        if (res.code === 200) {
          this.storeRanking = (res.data && res.data.RankingData) || []
        }
      } catch (error) {
        console.error('加载门店排行失败:', error)
      }
    },
    // 加载门店分布
    async loadStoreDistribution(params) {
      try {
        const res = await request({
          url: '/api/Extend/LqBusinessUnitDashboard/GetStoreDistribution',
          method: 'POST',
          data: params
        })
        if (res.code === 200) {
          this.storeDistribution = res.data || { DistributionData: [] }
          this.$nextTick(() => {
            this.renderStoreDistributionChart()
          })
        }
      } catch (error) {
        console.error('加载门店分布失败:', error)
      }
    },
    // 加载经理排行
    async loadManagerRanking(params) {
      try {
        const res = await request({
          url: '/api/Extend/LqBusinessUnitDashboard/GetManagerRanking',
          method: 'POST',
          data: params
        })
        if (res.code === 200) {
          this.managerRanking = (res.data && res.data.RankingData) || []
          // 经理排行加载完成后，加载经理趋势
          await this.loadManagerTrend()
        }
      } catch (error) {
        console.error('加载经理排行失败:', error)
      }
    },
    // 加载运营统计
    async loadOperationStatistics(params) {
      try {
        const res = await request({
          url: '/api/Extend/LqBusinessUnitDashboard/GetOperationStatistics',
          method: 'POST',
          data: params
        })
        if (res.code === 200) {
          this.operationStatistics = res.data || {
            BillingAnalysis: {},
            ConsumeAnalysis: {},
            RefundAnalysis: {}
          }
        }
      } catch (error) {
        console.error('加载运营统计失败:', error)
      }
    },
    // 加载对比分析
    async loadComparisonAnalysis(params) {
      try {
        const res = await request({
          url: '/api/Extend/LqBusinessUnitDashboard/GetComparisonAnalysis',
          method: 'POST',
          data: params
        })
        if (res.code === 200) {
          this.comparisonAnalysis = res.data || {
            TimeComparison: {
              MonthOverMonth: {},
              YearOverYear: {}
            }
          }
        }
      } catch (error) {
        console.error('加载对比分析失败:', error)
      }
    },
    // 加载门店明细列表
    async loadStoreDetailList(params) {
      this.storeDetailList.loading = true
      try {
        const res = await request({
          url: '/api/Extend/LqBusinessUnitDashboard/GetStoreDetailList',
          method: 'POST',
          data: {
            ...params,
            currentPage: this.storeDetailList.pagination.currentPage,
            pageSize: this.storeDetailList.pagination.pageSize
          }
        })
        if (res.code === 200 && res.data) {
          this.storeDetailList.data = res.data.list || []
          this.storeDetailList.pagination.total = (res.data.pagination && res.data.pagination.total) || 0
        }
      } catch (error) {
        console.error('加载门店明细列表失败:', error)
      } finally {
        this.storeDetailList.loading = false
      }
    },
    // 加载经理明细列表
    async loadManagerDetailList(params) {
      this.managerDetailList.loading = true
      try {
        const res = await request({
          url: '/api/Extend/LqBusinessUnitDashboard/GetManagerDetailList',
          method: 'POST',
          data: {
            ...params,
            currentPage: this.managerDetailList.pagination.currentPage,
            pageSize: this.managerDetailList.pagination.pageSize
          }
        })
        if (res.code === 200 && res.data) {
          this.managerDetailList.data = res.data.list || []
          this.managerDetailList.pagination.total = (res.data.pagination && res.data.pagination.total) || 0
        }
      } catch (error) {
        console.error('加载经理明细列表失败:', error)
      } finally {
        this.managerDetailList.loading = false
      }
    },
    // 加载店长明细列表
    async loadStoreManagerDetailList(params) {
      this.storeManagerDetailList.loading = true
      try {
        const res = await request({
          url: '/api/Extend/LqBusinessUnitDashboard/GetStoreManagerDetailList',
          method: 'POST',
          data: {
            ...params,
            currentPage: this.storeManagerDetailList.pagination.currentPage,
            pageSize: this.storeManagerDetailList.pagination.pageSize
          }
        })
        if (res.code === 200 && res.data) {
          this.storeManagerDetailList.data = res.data.list || []
          this.storeManagerDetailList.pagination.total = (res.data.pagination && res.data.pagination.total) || 0
        }
      } catch (error) {
        console.error('加载店长明细列表失败:', error)
      } finally {
        this.storeManagerDetailList.loading = false
      }
    },
    // 加载健康师明细列表
    async loadHealthCoachDetailList(params) {
      this.healthCoachDetailList.loading = true
      try {
        const res = await request({
          url: '/api/Extend/LqBusinessUnitDashboard/GetHealthCoachDetailList',
          method: 'POST',
          data: {
            ...params,
            currentPage: this.healthCoachDetailList.pagination.currentPage,
            pageSize: this.healthCoachDetailList.pagination.pageSize
          }
        })
        if (res.code === 200 && res.data) {
          this.healthCoachDetailList.data = res.data.list || []
          this.healthCoachDetailList.pagination.total = (res.data.pagination && res.data.pagination.total) || 0
        }
      } catch (error) {
        console.error('加载健康师明细列表失败:', error)
      } finally {
        this.healthCoachDetailList.loading = false
      }
    },
    // 加载经理分布
    async loadManagerDistribution(params) {
      try {
        const res = await request({
          url: '/api/Extend/LqBusinessUnitDashboard/GetManagerDistribution',
          method: 'POST',
          data: params
        })
        if (res.code === 200) {
          this.managerDistribution = res.data || { DistributionData: [] }
          this.$nextTick(() => {
            if (this.managerDistribution.DistributionData && this.managerDistribution.DistributionData.length > 0) {
              this.renderManagerDistributionChart()
            }
          })
        }
      } catch (error) {
        console.error('加载经理分布失败:', error)
      }
    },
    // 加载经理趋势
    async loadManagerTrend() {
      if (!this.query.month || !this.query.businessUnitId) return
      // 从经理排行中获取经理ID列表（取前5名）
      if (!this.managerRanking || this.managerRanking.length === 0) {
        // 如果还没有加载经理排行，先不加载趋势
        return
      }
      const managerIds = this.managerRanking.slice(0, 5).map(item => item.ManagerId).filter(id => id)
      if (managerIds.length === 0) return
      
      try {
        const statisticsMonth = this.query.month.replace('-', '')
        const res = await request({
          url: '/api/Extend/LqBusinessUnitDashboard/GetManagerTrend',
          method: 'POST',
          data: {
            statisticsMonth,
            businessUnitId: this.query.businessUnitId,
            storeIds: [],
            monthCount: this.trendMonthCount,
            ManagerIds: managerIds
          }
        })
        if (res.code === 200) {
          this.managerTrend = res.data || { ManagerTrendData: [] }
          this.$nextTick(() => {
            if (this.managerTrend.ManagerTrendData && this.managerTrend.ManagerTrendData.length > 0) {
              this.renderManagerTrendChart()
            }
          })
        }
      } catch (error) {
        console.error('加载经理趋势失败:', error)
      }
    },
    // 加载店长排行
    async loadStoreManagerRanking(params) {
      try {
        const res = await request({
          url: '/api/Extend/LqBusinessUnitDashboard/GetStoreManagerRanking',
          method: 'POST',
          data: params
        })
        if (res.code === 200) {
          this.storeManagerRanking = (res.data && res.data.RankingData) || []
        }
      } catch (error) {
        console.error('加载店长排行失败:', error)
      }
    },
    // 加载健康师排行
    async loadHealthCoachRanking(params) {
      try {
        const res = await request({
          url: '/api/Extend/LqBusinessUnitDashboard/GetHealthCoachRanking',
          method: 'POST',
          data: params
        })
        if (res.code === 200) {
          this.healthCoachRanking = (res.data && res.data.RankingData) || []
        }
      } catch (error) {
        console.error('加载健康师排行失败:', error)
      }
    },
    // 初始化所有图表
    initAllCharts() {
      this.renderPerformanceTrendChart()
      this.renderStoreDistributionChart()
      this.renderManagerDistributionChart()
      this.renderManagerTrendChart()
    },
    // 渲染业绩趋势图表
    renderPerformanceTrendChart() {
      const chart = this.getChart('performanceTrendChart')
      if (!this.performanceTrend.TrendData || this.performanceTrend.TrendData.length === 0) {
        chart.setOption({
          title: { text: '暂无数据', left: 'center', top: 'middle', textStyle: { color: '#909399' } }
        })
        return
      }
      const dates = this.performanceTrend.TrendData.map(item => {
        const month = item.Month
        if (month && month.length === 6) {
          return month.substring(0, 4) + '-' + month.substring(4, 6)
        }
        return month
      })
      chart.setOption({
        tooltip: {
          trigger: 'axis',
          backgroundColor: 'rgba(255,255,255,0.95)',
          borderWidth: 1,
          borderColor: '#E4E7ED',
          textStyle: { color: '#303133' }
        },
        legend: { top: 0, textStyle: { color: '#303133', fontSize: 12 } },
        grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: dates,
          axisLine: { lineStyle: { color: '#E4E7ED' } },
          axisLabel: { color: '#303133', fontSize: 12 }
        },
        yAxis: {
          type: 'value',
          splitLine: { lineStyle: { type: 'dashed', color: '#E4E7ED' } },
          axisLine: { lineStyle: { color: '#E4E7ED' } },
          axisLabel: {
            color: '#303133',
            fontSize: 12,
            formatter: function (value) {
              if (value >= 10000) {
                return (value / 10000).toFixed(1) + '万'
              }
              return value
            }
          }
        },
        series: [
          {
            name: '开单业绩',
            type: 'line',
            smooth: true,
            data: this.performanceTrend.TrendData.map(item => item.BillingPerformance || 0),
            color: '#409EFF',
            lineStyle: { width: 2 }
          },
          {
            name: '消耗业绩',
            type: 'line',
            smooth: true,
            data: this.performanceTrend.TrendData.map(item => item.ConsumePerformance || 0),
            color: '#67C23A',
            lineStyle: { width: 2 }
          },
          {
            name: '净业绩',
            type: 'line',
            smooth: true,
            data: this.performanceTrend.TrendData.map(item => item.NetPerformance || 0),
            color: '#E6A23C',
            lineStyle: { width: 2 }
          }
        ]
      })
    },
    // 渲染门店分布图表
    renderStoreDistributionChart() {
      const chart = this.getChart('storeDistributionChart')
      if (!this.storeDistribution.DistributionData || this.storeDistribution.DistributionData.length === 0) {
        chart.setOption({
          title: { text: '暂无数据', left: 'center', top: 'middle', textStyle: { color: '#909399' } }
        })
        return
      }
      // 浅色系颜色配置
      const lightColors = [
        '#A8D5E2', // 浅蓝色
        '#B8E6B8', // 浅绿色
        '#FFD4A3', // 浅橙色
        '#E8C5E8', // 浅紫色
        '#FFE5B4', // 浅黄色
        '#C4E1F6', // 浅天蓝色
        '#D4EDDA', // 浅薄荷绿
        '#F8D7DA', // 浅粉色
        '#D1ECF1', // 浅青色
        '#FFF3CD'  // 浅米色
      ]
      
      // 计算总值，用于计算百分比
      const total = this.storeDistribution.DistributionData.reduce((sum, item) => sum + (item.Performance || 0), 0)
      
      // 处理数据，只给占比大于1%的显示标签
      const data = this.storeDistribution.DistributionData.map((item, index) => {
        const value = item.Performance || 0
        const percent = total > 0 ? (value / total * 100) : 0
        return {
          value: value,
          name: item.StoreName || '未知门店',
          itemStyle: {
            color: lightColors[index % lightColors.length]
          },
          // 只有占比大于1%的才显示标签和标签线
          label: {
            show: percent >= 1,
            formatter: percent >= 1 ? '{b}\n{d}%' : '',
            fontSize: 11,
            position: 'outside',
            color: '#606266',
            distanceToLabelLine: 5
          },
          labelLine: {
            show: percent >= 1,
            length: 10,
            length2: 8,
            lineStyle: {
              color: '#C0C4CC',
              width: 1
            }
          }
        }
      })
      
      // 门店数量判断：超过10个就隐藏图例
      const storeCount = this.storeDistribution.DistributionData.length
      const showLegend = storeCount <= 10
      
      chart.setOption({
        tooltip: {
          trigger: 'item',
          formatter: function(params) {
            const value = params.value || 0
            const percent = params.percent || 0
            const formattedValue = value >= 10000 
              ? '￥' + (value / 10000).toFixed(2) + '万' 
              : '￥' + value.toFixed(2)
            return params.seriesName + '<br/>' + params.name + ': ' + formattedValue + ' (' + percent.toFixed(2) + '%)'
          }
        },
        legend: showLegend ? {
          show: true,
          orient: 'vertical',
          right: '5%',
          top: 'middle',
          textStyle: { 
            fontSize: 11, 
            color: '#606266'
          },
          formatter: function(name) {
            const item = data.find(d => d.name === name)
            if (item && item.value > 0) {
              const formattedValue = item.value >= 10000 
                ? (item.value / 10000).toFixed(2) + '万' 
                : item.value.toFixed(2)
              return name + '  ￥' + formattedValue
            }
            return name
          },
          itemWidth: 12,
          itemHeight: 12,
          itemGap: 6
        } : {
          show: false
        },
        series: [
          {
            name: '门店业绩',
            type: 'pie',
            radius: showLegend ? ['35%', '65%'] : ['45%', '75%'],
            center: showLegend ? ['35%', '50%'] : ['50%', '50%'],
            avoidLabelOverlap: true,
            itemStyle: {
              borderRadius: 8,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: true,
              formatter: function(params) {
                return params.percent >= 1 ? params.name + '\n' + params.percent.toFixed(1) + '%' : ''
              },
              fontSize: 11,
              position: 'outside',
              distanceToLabelLine: 5,
              color: '#606266',
              lineHeight: 14
            },
            labelLine: {
              show: true,
              length: 10,
              length2: 8,
              lineStyle: {
                color: '#C0C4CC',
                width: 1
              }
            },
            emphasis: {
              label: {
                show: true,
                fontSize: 12,
                fontWeight: 'bold'
              },
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.3)'
              }
            },
            data: data
          }
        ]
      })
    },
    // 渲染经理分布图表
    renderManagerDistributionChart() {
      const chart = this.getChart('managerDistributionChart')
      if (!this.managerDistribution.DistributionData || this.managerDistribution.DistributionData.length === 0) {
        chart.setOption({
          title: { text: '暂无数据', left: 'center', top: 'middle', textStyle: { color: '#909399' } }
        })
        return
      }
      // 浅色系颜色配置
      const lightColors = [
        '#A8D5E2', '#B8E6B8', '#FFD4A3', '#E8C5E8', '#FFE5B4',
        '#C4E1F6', '#D4EDDA', '#F8D7DA', '#D1ECF1', '#FFF3CD'
      ]
      
      const total = this.managerDistribution.DistributionData.reduce((sum, item) => sum + (item.TotalBillingPerformance || 0), 0)
      
      const data = this.managerDistribution.DistributionData.map((item, index) => {
        const value = item.TotalBillingPerformance || 0
        const percent = total > 0 ? (value / total * 100) : 0
        return {
          value: value,
          name: item.ManagerName || '未知经理',
          itemStyle: {
            color: lightColors[index % lightColors.length]
          },
          label: {
            show: percent >= 1,
            formatter: percent >= 1 ? '{b}\n{d}%' : '',
            fontSize: 11,
            position: 'outside',
            color: '#606266',
            distanceToLabelLine: 5
          },
          labelLine: {
            show: percent >= 1,
            length: 10,
            length2: 8,
            lineStyle: {
              color: '#C0C4CC',
              width: 1
            }
          }
        }
      })
      
      const managerCount = this.managerDistribution.DistributionData.length
      const showLegend = managerCount <= 10
      
      chart.setOption({
        tooltip: {
          trigger: 'item',
          formatter: function(params) {
            const value = params.value || 0
            const percent = params.percent || 0
            const formattedValue = value >= 10000 
              ? '￥' + (value / 10000).toFixed(2) + '万' 
              : '￥' + value.toFixed(2)
            return params.seriesName + '<br/>' + params.name + ': ' + formattedValue + ' (' + percent.toFixed(2) + '%)'
          }
        },
        legend: showLegend ? {
          show: true,
          orient: 'vertical',
          right: '5%',
          top: 'middle',
          textStyle: { 
            fontSize: 11, 
            color: '#606266'
          },
          formatter: function(name) {
            const item = data.find(d => d.name === name)
            if (item && item.value > 0) {
              const formattedValue = item.value >= 10000 
                ? (item.value / 10000).toFixed(2) + '万' 
                : item.value.toFixed(2)
              return name + '  ￥' + formattedValue
            }
            return name
          },
          itemWidth: 12,
          itemHeight: 12,
          itemGap: 6
        } : {
          show: false
        },
        series: [{
          name: '经理业绩',
          type: 'pie',
          radius: showLegend ? ['35%', '65%'] : ['45%', '75%'],
          center: showLegend ? ['35%', '50%'] : ['50%', '50%'],
          avoidLabelOverlap: true,
          itemStyle: {
            borderRadius: 8,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: true,
            formatter: function(params) {
              return params.percent >= 1 ? params.name + '\n' + params.percent.toFixed(1) + '%' : ''
            },
            fontSize: 11,
            position: 'outside',
            distanceToLabelLine: 5,
            color: '#606266',
            lineHeight: 14
          },
          labelLine: {
            show: true,
            length: 10,
            length2: 8,
            lineStyle: {
              color: '#C0C4CC',
              width: 1
            }
          },
          data: data
        }]
      })
    },
    // 渲染经理趋势图表
    renderManagerTrendChart() {
      const chart = this.getChart('managerTrendChart')
      if (!this.managerTrend.ManagerTrendData || this.managerTrend.ManagerTrendData.length === 0) {
        chart.setOption({
          title: { text: '暂无数据', left: 'center', top: 'middle', textStyle: { color: '#909399' } }
        })
        return
      }
      
      // 获取所有月份（从第一个经理的趋势点中获取）
      const firstManager = this.managerTrend.ManagerTrendData[0]
      if (!firstManager || !firstManager.TrendPoints || firstManager.TrendPoints.length === 0) {
        chart.setOption({
          title: { text: '暂无数据', left: 'center', top: 'middle', textStyle: { color: '#909399' } }
        })
        return
      }
      
      const dates = firstManager.TrendPoints.map(point => {
        const month = point.Month
        if (month && month.length === 6) {
          return month.substring(0, 4) + '-' + month.substring(4, 6)
        }
        return month
      })
      
      // 为每个经理创建一条线
      const colors = ['#409EFF', '#67C23A', '#E6A23C', '#F56C6C', '#909399', '#9C27B0', '#FF9800', '#00BCD4']
      const series = this.managerTrend.ManagerTrendData.map((manager, index) => {
        return {
          name: manager.ManagerName || '未知经理',
          type: 'line',
          smooth: true,
          data: manager.TrendPoints.map(point => point.TotalPerformance || 0),
          color: colors[index % colors.length],
          lineStyle: { width: 2 }
        }
      })
      
      const managerNames = this.managerTrend.ManagerTrendData.map(m => m.ManagerName || '未知经理')
      
      chart.setOption({
        tooltip: {
          trigger: 'axis',
          axisPointer: { type: 'cross' }
        },
        legend: {
          data: managerNames,
          bottom: 0,
          textStyle: { fontSize: 11 }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '15%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: dates,
          axisLine: { lineStyle: { color: '#E4E7ED' } },
          axisLabel: { color: '#303133', fontSize: 12 }
        },
        yAxis: {
          type: 'value',
          splitLine: { lineStyle: { type: 'dashed', color: '#E4E7ED' } },
          axisLine: { lineStyle: { color: '#E4E7ED' } },
          axisLabel: {
            color: '#303133',
            fontSize: 12,
            formatter: function (value) {
              if (value >= 10000) {
                return (value / 10000).toFixed(1) + '万'
              }
              return value
            }
          }
        },
        series: series
      })
    },
    getChart(id) {
      const dom = document.getElementById(id)
      if (!dom) return { setOption: () => {} }
      if (this.charts[id]) this.charts[id].dispose()
      this.charts[id] = echarts.init(dom)
      return this.charts[id]
    },
    handleResize() {
      Object.values(this.charts).forEach(c => c && c.resize())
    },
    // KPI点击滚动到对应明细列表
    scrollToDetailList(kpi) {
      let targetId = ''
      switch (kpi.key) {
        case 'billing':
        case 'consume':
        case 'net':
        case 'managed':
        case 'active':
          targetId = 'store-detail-list'
          break
        default:
          return
      }
      if (targetId) {
        this.$nextTick(() => {
          const element = document.getElementById(targetId)
          if (element) {
            element.scrollIntoView({ behavior: 'smooth', block: 'start' })
          }
        })
      }
    },
    // 门店明细列表分页大小变化
    handleStoreDetailPageSizeChange(val) {
      this.storeDetailList.pagination.pageSize = val
      this.storeDetailList.pagination.currentPage = 1
      const statisticsMonth = this.query.month.replace('-', '')
      const params = {
        statisticsMonth,
        businessUnitId: this.query.businessUnitId,
        storeIds: []
      }
      this.loadStoreDetailList(params)
    },
    // 门店明细列表页码变化
    handleStoreDetailPageChange(val) {
      this.storeDetailList.pagination.currentPage = val
      const statisticsMonth = this.query.month.replace('-', '')
      const params = {
        statisticsMonth,
        businessUnitId: this.query.businessUnitId,
        storeIds: []
      }
      this.loadStoreDetailList(params)
    },
    // 经理明细列表分页大小变化
    handleManagerDetailPageSizeChange(val) {
      this.managerDetailList.pagination.pageSize = val
      this.managerDetailList.pagination.currentPage = 1
      const statisticsMonth = this.query.month.replace('-', '')
      const params = {
        statisticsMonth,
        businessUnitId: this.query.businessUnitId,
        storeIds: []
      }
      this.loadManagerDetailList(params)
    },
    // 经理明细列表页码变化
    handleManagerDetailPageChange(val) {
      this.managerDetailList.pagination.currentPage = val
      const statisticsMonth = this.query.month.replace('-', '')
      const params = {
        statisticsMonth,
        businessUnitId: this.query.businessUnitId,
        storeIds: []
      }
      this.loadManagerDetailList(params)
    },
    // 店长明细列表分页大小变化
    handleStoreManagerDetailPageSizeChange(val) {
      this.storeManagerDetailList.pagination.pageSize = val
      this.storeManagerDetailList.pagination.currentPage = 1
      const statisticsMonth = this.query.month.replace('-', '')
      const params = {
        statisticsMonth,
        businessUnitId: this.query.businessUnitId,
        storeIds: []
      }
      this.loadStoreManagerDetailList(params)
    },
    // 店长明细列表页码变化
    handleStoreManagerDetailPageChange(val) {
      this.storeManagerDetailList.pagination.currentPage = val
      const statisticsMonth = this.query.month.replace('-', '')
      const params = {
        statisticsMonth,
        businessUnitId: this.query.businessUnitId,
        storeIds: []
      }
      this.loadStoreManagerDetailList(params)
    },
    // 健康师明细列表分页大小变化
    handleHealthCoachDetailPageSizeChange(val) {
      this.healthCoachDetailList.pagination.pageSize = val
      this.healthCoachDetailList.pagination.currentPage = 1
      const statisticsMonth = this.query.month.replace('-', '')
      const params = {
        statisticsMonth,
        businessUnitId: this.query.businessUnitId,
        storeIds: []
      }
      this.loadHealthCoachDetailList(params)
    },
    // 健康师明细列表页码变化
    handleHealthCoachDetailPageChange(val) {
      this.healthCoachDetailList.pagination.currentPage = val
      const statisticsMonth = this.query.month.replace('-', '')
      const params = {
        statisticsMonth,
        businessUnitId: this.query.businessUnitId,
        storeIds: []
      }
      this.loadHealthCoachDetailList(params)
    },
    getComparisonClass(value) {
      if (value > 0) return 'positive'
      if (value < 0) return 'negative'
      return ''
    },
    formatMoney(v) {
      return Number(v || 0).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })
    },
    formatNumber(v) {
      const num = Number(v || 0)
      return num.toLocaleString()
    },
    formatPercent(v) {
      if (v === null || v === undefined || isNaN(v)) {
        return '0.00'
      }
      const num = Number(v)
      if (isNaN(num)) {
        return '0.00'
      }
      return num.toFixed(2)
    }
  }
}
</script>

<style lang="scss" scoped>
.business-unit-dashboard {
  padding: 16px;
  padding-bottom: 32px;
  background-color: #f5f7fa;
  min-height: 100vh;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
  box-sizing: border-box;
  .cockpit-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    background: #fff;
    padding: 12px 20px;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);

    .page-title {
      margin: 0;
      font-size: 20px;
      color: #303133;
      font-weight: 600;

      .subtitle {
        font-size: 13px;
        color: #909399;
        font-weight: normal;
        margin-left: 12px;
      }
    }

    .search-form-compact {
      .el-form-item {
        margin-bottom: 0;
        margin-right: 15px;
      }
    }
  }

  .kpi-row {
    margin-bottom: 16px;
    
    .el-col:nth-child(n+5) {
      margin-top: 16px;
    }
  }

  .kpi-card {
    background: #fff;
    padding: 20px 10px;
    border-radius: 8px;
    display: flex;
    align-items: center;
    position: relative;
    overflow: hidden;
    height: 100px;
    box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.04);
    transition: transform 0.3s;
    cursor: pointer;

    &:hover {
      transform: translateY(-4px);
    }

    &.primary {
      border-left: 4px solid #409EFF;
      .kpi-icon {
        color: #409EFF;
        background: rgba(64, 158, 255, 0.1);
      }
    }

    &.success {
      border-left: 4px solid #67C23A;
      .kpi-icon {
        color: #67C23A;
        background: rgba(103, 194, 58, 0.1);
      }
    }

    &.warning {
      border-left: 4px solid #E6A23C;
      .kpi-icon {
        color: #E6A23C;
        background: rgba(230, 162, 60, 0.1);
      }
    }

    &.info {
      border-left: 4px solid #909399;
      .kpi-icon {
        color: #909399;
        background: rgba(144, 147, 153, 0.1);
      }
    }

    &.danger {
      border-left: 4px solid #F56C6C;
      .kpi-icon {
        color: #F56C6C;
        background: rgba(245, 108, 108, 0.1);
      }
    }

    .kpi-icon {
      width: 48px;
      height: 48px;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 24px;
      margin-right: 15px;
    }

    .kpi-label {
      font-size: 13px;
      color: #909399;
      margin-bottom: 6px;
    }

    .kpi-value {
      font-size: 20px;
      font-weight: bold;
      color: #303133;
      .unit {
        font-size: 13px;
      }
    }
  }

  .dashboard-card {
    border: none;
    border-radius: 8px;
    margin-bottom: 16px;

    &::v-deep .el-card__header {
      padding: 12px 20px;
      border-bottom: 1px solid #f0f2f5;
    }

    .card-title {
      font-size: 15px;
      font-weight: 600;
      color: #303133;
      i {
        color: #409EFF;
        margin-right: 8px;
      }
    }
  }

  .chart-box {
    height: 320px;
    width: 100%;
  }

  .analysis-row {
    .dashboard-card {
      height: 400px;
      display: flex;
      flex-direction: column;

      &::v-deep .el-card__body {
        flex: 1;
        display: flex;
        flex-direction: column;
        overflow: hidden;
      }

      .chart-box {
        flex: 1;
        min-height: 0;
      }
    }
  }

  .ranking-row {
    .dashboard-card {
      height: 540px;
      display: flex;
      flex-direction: column;

      &::v-deep .el-card__body {
        flex: 1;
        display: flex;
        flex-direction: column;
        overflow: hidden;
        padding: 20px;
      }

      &::v-deep .el-table {
        flex: 1;
        overflow: hidden;
      }

      &::v-deep .el-table__body-wrapper {
        max-height: calc(100% - 40px);
        overflow-y: auto;
      }
    }
  }

  .insight-row {
    .dashboard-card {
      min-height: 300px;
      display: flex;
      flex-direction: column;

      &::v-deep .el-card__body {
        flex: 1;
        padding: 20px;
      }
    }
  }

  .operation-stats {
    display: flex;
    flex-direction: column;
    gap: 20px;

    .stat-item {
      display: flex;
      flex-direction: column;
      align-items: flex-start;
      padding: 12px 0;

      .stat-label {
        font-size: 14px;
        color: #606266;
        margin-bottom: 8px;
      }

      .stat-value {
        font-size: 18px;
        font-weight: bold;
        color: #303133;
      }
    }
  }

  .comparison-content {
    .comparison-section {
      margin-bottom: 30px;

      &:last-child {
        margin-bottom: 0;
      }

      h4 {
        margin: 0 0 16px 0;
        font-size: 16px;
        color: #303133;
        font-weight: 600;
      }

      .comparison-item {
        padding: 16px;
        background: #f5f7fa;
        border-radius: 8px;
        text-align: center;

        .comparison-label {
          font-size: 13px;
          color: #909399;
          margin-bottom: 8px;
        }

        .comparison-value {
          font-size: 24px;
          font-weight: bold;
          color: #303133;

          &.positive {
            color: #67C23A;
          }

          &.negative {
            color: #F56C6C;
          }
        }
      }
    }
  }

  // 明细列表样式
  .detail-list-row {
    margin-top: 16px;
    margin-bottom: 16px;

    .dashboard-card {
      height: 600px;
      display: flex;
      flex-direction: column;

      &::v-deep .el-card__body {
        flex: 1;
        display: flex;
        flex-direction: column;
        overflow: hidden;
        padding: 20px;
      }

      .el-table {
        flex: 1;
      }
    }

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .card-title {
        font-size: 16px;
        font-weight: 600;
        color: #303133;
      }
    }

    .detail-pagination {
      margin-top: 16px;
      text-align: right;
    }
  }
}
</style>

