<template>
  <div class="tech-department-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.techDepartmentId" placeholder="请选择科技部" filterable clearable
              @change="handleTechDepartmentChange" size="mini" style="width: 150px;">
              <el-option v-for="dept in techDepartmentOptions" :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">
      <el-col :span="24">
        <el-card class="dashboard-card" shadow="hover">
          <div slot="header" class="card-title">
            <span><i class="el-icon-s-marketing"></i> 股份趋势</span>
            <el-radio-group v-model="shareTrendMonthCount" size="mini" style="float: right" @change="handleShareTrendMonthCountChange">
              <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="shareTrendChart" 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="TotalKemeiIncome" label="科美总收入" align="right">
              <template slot-scope="scope">￥{{ formatMoney(scope.row.TotalKemeiIncome) }}</template>
            </el-table-column>
            <el-table-column prop="Percentage" label="占比" width="100" align="right">
              <template slot-scope="scope">{{ formatPercent(scope.row.Percentage) }}%</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="teacherRanking" size="mini" style="width: 100%">
            <el-table-column type="index" label="排名" width="60"></el-table-column>
            <el-table-column prop="EmployeeName" 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="8">
                  <div class="comparison-item">
                    <div class="comparison-label">溯源金额变化率</div>
                    <div class="comparison-value" :class="getComparisonClass(monthOverMonthComparison.TraceabilityAmountChangeRate)">
                      {{ formatPercent(monthOverMonthComparison.TraceabilityAmountChangeRate) }}%
                    </div>
                  </div>
                </el-col>
                <el-col :span="8">
                  <div class="comparison-item">
                    <div class="comparison-label">Cell金额变化率</div>
                    <div class="comparison-value" :class="getComparisonClass(monthOverMonthComparison.CellAmountChangeRate)">
                      {{ formatPercent(monthOverMonthComparison.CellAmountChangeRate) }}%
                    </div>
                  </div>
                </el-col>
                <el-col :span="8">
                  <div class="comparison-item">
                    <div class="comparison-label">科美总收入变化率</div>
                    <div class="comparison-value" :class="getComparisonClass(monthOverMonthComparison.TotalKemeiIncomeChangeRate)">
                      {{ formatPercent(monthOverMonthComparison.TotalKemeiIncomeChangeRate) }}%
                    </div>
                  </div>
                </el-col>
              </el-row>
            </div>
            <div class="comparison-section">
              <h4>同比对比（与去年同月对比）</h4>
              <el-row :gutter="16">
                <el-col :span="8">
                  <div class="comparison-item">
                    <div class="comparison-label">溯源金额变化率</div>
                    <div class="comparison-value" :class="getComparisonClass(yearOverYearComparison.TraceabilityAmountChangeRate)">
                      {{ formatPercent(yearOverYearComparison.TraceabilityAmountChangeRate) }}%
                    </div>
                  </div>
                </el-col>
                <el-col :span="8">
                  <div class="comparison-item">
                    <div class="comparison-label">Cell金额变化率</div>
                    <div class="comparison-value" :class="getComparisonClass(yearOverYearComparison.CellAmountChangeRate)">
                      {{ formatPercent(yearOverYearComparison.CellAmountChangeRate) }}%
                    </div>
                  </div>
                </el-col>
                <el-col :span="8">
                  <div class="comparison-item">
                    <div class="comparison-label">科美总收入变化率</div>
                    <div class="comparison-value" :class="getComparisonClass(yearOverYearComparison.TotalKemeiIncomeChangeRate)">
                      {{ formatPercent(yearOverYearComparison.TotalKemeiIncomeChangeRate) }}%
                    </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="门店名称" ></el-table-column>
            <el-table-column prop="TraceabilityAmount" label="溯源金额">
              <template slot-scope="scope">￥{{ formatMoney(scope.row.TraceabilityAmount) }}</template>
            </el-table-column>
            <el-table-column prop="CellAmount" label="Cell金额" >
              <template slot-scope="scope">￥{{ formatMoney(scope.row.CellAmount) }}</template>
            </el-table-column>
            <el-table-column prop="TotalKemeiIncome" label="科美总收入">
              <template slot-scope="scope">￥{{ formatMoney(scope.row.TotalKemeiIncome) }}</template>
            </el-table-column>
            <el-table-column prop="Percentage" label="占比">
              <template slot-scope="scope">{{ formatPercent(scope.row.Percentage) }}%</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="teacher-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="teacherDetailList.data"
            v-loading="teacherDetailList.loading"
            size="mini"
            border
            style="width: 100%"
            :max-height="500">
            <el-table-column prop="EmployeeName" label="老师姓名" ></el-table-column>
            <el-table-column prop="StoreName" label="门店" ></el-table-column>
            <el-table-column prop="OrderAchievement" label="开单业绩" >
              <template slot-scope="scope">￥{{ formatMoney(scope.row.OrderAchievement) }}</template>
            </el-table-column>
            <el-table-column prop="ConsumeAchievement" label="消耗业绩" >
              <template slot-scope="scope">￥{{ formatMoney(scope.row.ConsumeAchievement) }}</template>
            </el-table-column>
            <el-table-column prop="TotalPerformance" label="总业绩" >
              <template slot-scope="scope">￥{{ formatMoney(scope.row.TotalPerformance) }}</template>
            </el-table-column>
          </el-table>
          <div class="detail-pagination" v-if="teacherDetailList.pagination.total > 0">
            <el-pagination
              @size-change="handleTeacherDetailPageSizeChange"
              @current-change="handleTeacherDetailPageChange"
              :current-page="teacherDetailList.pagination.currentPage"
              :page-sizes="[10, 20, 50, 100]"
              :page-size="teacherDetailList.pagination.pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="teacherDetailList.pagination.total">
            </el-pagination>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 明细列表 - 第二行 -->
    <el-row class="detail-list-row" :gutter="16">
      <!-- 开单明细列表 -->
      <el-col id="billing-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="billingDetailList.data"
            v-loading="billingDetailList.loading"
            size="mini"
            border
            style="width: 100%"
            :max-height="500">
            <el-table-column prop="BillingDate" label="开单日期" ></el-table-column>
            <el-table-column prop="StoreName" label="门店" ></el-table-column>
            <el-table-column prop="MemberName" label="会员" ></el-table-column>
            <el-table-column prop="BeautyType" label="美业类型" ></el-table-column>
            <el-table-column prop="Amount" label="金额" >
              <template slot-scope="scope">￥{{ formatMoney(scope.row.Amount) }}</template>
            </el-table-column>
          </el-table>
          <div class="detail-pagination" v-if="billingDetailList.pagination.total > 0">
            <el-pagination
              @size-change="handleBillingDetailPageSizeChange"
              @current-change="handleBillingDetailPageChange"
              :current-page="billingDetailList.pagination.currentPage"
              :page-sizes="[10, 20, 50, 100]"
              :page-size="billingDetailList.pagination.pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="billingDetailList.pagination.total">
            </el-pagination>
          </div>
        </el-card>
      </el-col>
      <!-- 消耗明细列表 -->
      <el-col id="consume-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="consumeDetailList.data"
            v-loading="consumeDetailList.loading"
            size="mini"
            border
            style="width: 100%"
            :max-height="500">
            <el-table-column prop="ConsumeDate" label="消耗日期" ></el-table-column>
            <el-table-column prop="StoreName" label="门店" ></el-table-column>
            <el-table-column prop="MemberName" label="会员" ></el-table-column>
            <el-table-column prop="Amount" label="金额" >
              <template slot-scope="scope">￥{{ formatMoney(scope.row.Amount) }}</template>
            </el-table-column>
          </el-table>
          <div class="detail-pagination" v-if="consumeDetailList.pagination.total > 0">
            <el-pagination
              @size-change="handleConsumeDetailPageSizeChange"
              @current-change="handleConsumeDetailPageChange"
              :current-page="consumeDetailList.pagination.currentPage"
              :page-sizes="[10, 20, 50, 100]"
              :page-size="consumeDetailList.pagination.pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="consumeDetailList.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: 'TechDepartmentDashboard',
  data() {
    return {
      query: {
        month: dayjs().format('YYYY-MM'),
        techDepartmentId: undefined
      },
      techDepartmentOptions: [],
      trendMonthCount: 12,
      shareTrendMonthCount: 12,
      loading: false,
      charts: {},
      // 统计数据
      statistics: {},
      shareStatistics: {},
      performanceTrend: { TrendData: [] },
      shareTrend: { TrendData: [] },
      storeRanking: [],
      storeDistribution: { DistributionData: [] },
      teacherRanking: [],
      operationStatistics: {
        BillingAnalysis: {},
        ConsumeAnalysis: {},
        RefundAnalysis: {}
      },
      comparisonAnalysis: {
        TimeComparison: {
          MonthOverMonth: {},
          YearOverYear: {}
        }
      },
      // 明细列表数据
      storeDetailList: {
        loading: false,
        data: [],
        pagination: {
          currentPage: 1,
          pageSize: 20,
          total: 0
        }
      },
      teacherDetailList: {
        loading: false,
        data: [],
        pagination: {
          currentPage: 1,
          pageSize: 20,
          total: 0
        }
      },
      billingDetailList: {
        loading: false,
        data: [],
        pagination: {
          currentPage: 1,
          pageSize: 20,
          total: 0
        }
      },
      consumeDetailList: {
        loading: false,
        data: [],
        pagination: {
          currentPage: 1,
          pageSize: 20,
          total: 0
        }
      }
    }
  },
  computed: {
    // 合并所有 KPI 为一个数组，一行显示4个
    allKpiList() {
      return [...this.kpiList, ...this.shareKpiList]
    },
    kpiList() {
      const d = this.statistics || {}
      return [
        {
          tooltip: '开单溯源金额 - 退卡溯源金额',
          key: 'traceability',
          label: '溯源金额',
          value: this.formatMoney(d.TraceabilityAmount),
          raw: d.TraceabilityAmount || 0,
          icon: 'el-icon-wallet',
          type: 'primary',
          isMoney: true,
          clickable: true
        },
        {
          tooltip: '开单Cell金额 - 退卡Cell金额',
          key: 'cell',
          label: 'Cell金额',
          value: this.formatMoney(d.CellAmount),
          raw: d.CellAmount || 0,
          icon: 'el-icon-coin',
          type: 'success',
          isMoney: true,
          clickable: true
        },
        {
          tooltip: '溯源金额 + Cell金额',
          key: 'total',
          label: '科美总收入',
          value: this.formatMoney(d.TotalKemeiIncome),
          raw: d.TotalKemeiIncome || 0,
          icon: 'el-icon-trophy',
          type: 'warning',
          isMoney: 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: 'danger',
          isMoney: false,
          clickable: true
        }
      ]
    },
    shareKpiList() {
      const d = this.shareStatistics || {}
      return [
        {
          key: 'income',
          label: '收入',
          value: this.formatMoney(d.Income),
          raw: d.Income || 0,
          icon: 'el-icon-money',
          type: 'primary',
          isMoney: true,
          clickable: false
        },
        {
          key: 'cost',
          label: '总成本',
          value: this.formatMoney((d.CostReimbursement || 0) + (d.CostTeacherBase || 0) + (d.CostTeacherManual || 0) + (d.CostTeacherBillingComm || 0) + (d.CostTeacherConsumeComm || 0) + (d.CostGMBase || 0) + (d.CostGMComm || 0)),
          raw: (d.CostReimbursement || 0) + (d.CostTeacherBase || 0) + (d.CostTeacherManual || 0) + (d.CostTeacherBillingComm || 0) + (d.CostTeacherConsumeComm || 0) + (d.CostGMBase || 0) + (d.CostGMComm || 0),
          icon: 'el-icon-s-finance',
          type: 'warning',
          isMoney: true,
          clickable: false
        },
        {
          key: 'profit',
          label: '利润',
          value: this.formatMoney(d.Profit),
          raw: d.Profit || 0,
          icon: 'el-icon-trophy',
          type: d.Profit >= 0 ? 'success' : 'danger',
          isMoney: true,
          clickable: false
        }
      ]
    },
    // 对比分析数据简化
    monthOverMonthComparison() {
      if (!this.comparisonAnalysis || !this.comparisonAnalysis.TimeComparison || !this.comparisonAnalysis.TimeComparison.MonthOverMonth) {
        return {
          TraceabilityAmountChangeRate: 0,
          CellAmountChangeRate: 0,
          TotalKemeiIncomeChangeRate: 0
        }
      }
      return this.comparisonAnalysis.TimeComparison.MonthOverMonth
    },
    yearOverYearComparison() {
      if (!this.comparisonAnalysis || !this.comparisonAnalysis.TimeComparison || !this.comparisonAnalysis.TimeComparison.YearOverYear) {
        return {
          TraceabilityAmountChangeRate: 0,
          CellAmountChangeRate: 0,
          TotalKemeiIncomeChangeRate: 0
        }
      }
      return this.comparisonAnalysis.TimeComparison.YearOverYear
    }
  },
  watch: {
    trendMonthCount() {
      this.loadPerformanceTrend()
    },
    shareTrendMonthCount() {
      this.loadShareTrend()
    }
  },
  async mounted() {
    await this.loadTechDepartmentOptions()
    // 如果列表有数据且未选择科技部，默认选择第一个
    if (this.techDepartmentOptions.length > 0 && !this.query.techDepartmentId) {
      const firstDept = this.techDepartmentOptions[0]
      this.query.techDepartmentId = firstDept.Id || firstDept.id
    }
    if (this.query.techDepartmentId) {
      this.search()
    }
    window.addEventListener('resize', this.handleResize)
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize)
    Object.values(this.charts).forEach(c => c && c.dispose())
  },
  methods: {
    // 年月选择器变化处理
    handleMonthChange() {
    },
    // 科技部变化处理
    handleTechDepartmentChange() {
      // 科技部变化时自动刷新数据
      if (this.query.techDepartmentId) {
        this.search()
      }
    },
    // 趋势月份数量变化
    handleTrendMonthCountChange() {
      // watch中已处理
    },
    // 股份趋势月份数量变化
    handleShareTrendMonthCountChange() {
      // watch中已处理
    },
    // 加载科技部选项
    async loadTechDepartmentOptions() {
      try {
        const res = await request({
          url: '/api/Extend/Organize/GetByName',
          method: 'GET',
          data: {
            organizeName: '科技部'
          }
        })
        this.techDepartmentOptions = res.data || []
      } catch (error) {
        console.error('加载科技部列表失败:', error)
        this.techDepartmentOptions = []
      }
    },
    // 主搜索方法
    async search() {
      if (!this.query.month) {
        this.$message.warning('请选择月份')
        return
      }
      if (!this.query.techDepartmentId) {
        this.$message.warning('请选择科技部')
        return
      }
      try {
        this.loading = true
        const statisticsMonth = this.query.month.replace('-', '')
        const params = {
          statisticsMonth,
          techDepartmentId: this.query.techDepartmentId,
          storeIds: []
        }
        await Promise.all([
          this.loadStatistics(params),
          this.loadShareStatistics(params),
          this.loadPerformanceTrend(),
          this.loadShareTrend(),
          this.loadStoreRanking(params),
          this.loadStoreDistribution(params),
          this.loadTeacherRanking(params),
          this.loadOperationStatistics(params),
          this.loadComparisonAnalysis(params),
          this.loadStoreDetailList(params),
          this.loadTeacherDetailList(params),
          this.loadBillingDetailList(params),
          this.loadConsumeDetailList(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/LqTechDepartmentDashboard/GetStatistics',
          method: 'POST',
          data: params
        })
        if (res.code === 200) {
          this.statistics = res.data || {}
        }
      } catch (error) {
        console.error('加载统计数据失败:', error)
      }
    },
    // 加载股份统计数据
    async loadShareStatistics(params) {
      try {
        const res = await request({
          url: '/api/Extend/LqTechDepartmentDashboard/GetShareStatistics',
          method: 'POST',
          data: params
        })
        if (res.code === 200) {
          this.shareStatistics = 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/LqTechDepartmentDashboard/GetPerformanceTrend',
          method: 'POST',
          data: {
            statisticsMonth,
            techDepartmentId: this.query.techDepartmentId,
            storeIds: [],
            monthCount: this.trendMonthCount
          }
        })
        if (res.code === 200) {
          this.performanceTrend = res.data || { TrendData: [] }
          this.$nextTick(() => {
            this.renderPerformanceTrendChart()
          })
        }
      } catch (error) {
        console.error('加载业绩趋势失败:', error)
      }
    },
    // 加载股份趋势
    async loadShareTrend() {
      if (!this.query.month) return
      try {
        const statisticsMonth = this.query.month.replace('-', '')
        const res = await request({
          url: '/api/Extend/LqTechDepartmentDashboard/GetShareTrend',
          method: 'POST',
          data: {
            statisticsMonth,
            techDepartmentId: this.query.techDepartmentId,
            storeIds: [],
            monthCount: this.shareTrendMonthCount
          }
        })
        if (res.code === 200) {
          this.shareTrend = res.data || { TrendData: [] }
          this.$nextTick(() => {
            this.renderShareTrendChart()
          })
        }
      } catch (error) {
        console.error('加载股份趋势失败:', error)
      }
    },
    // 加载门店排行
    async loadStoreRanking(params) {
      try {
        const res = await request({
          url: '/api/Extend/LqTechDepartmentDashboard/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/LqTechDepartmentDashboard/GetStoreDistribution',
          method: 'POST',
          data: params
        })
        if (res.code === 200) {
          this.storeDistribution = res.data || { DistributionData: [] }
          this.$nextTick(() => {
            this.renderStoreDistributionChart()
          })
        }
      } catch (error) {
        console.error('加载门店分布失败:', error)
      }
    },
    // 加载老师排行
    async loadTeacherRanking(params) {
      try {
        const res = await request({
          url: '/api/Extend/LqTechDepartmentDashboard/GetTeacherRanking',
          method: 'POST',
          data: params
        })
        if (res.code === 200) {
          this.teacherRanking = (res.data && res.data.RankingData) || []
        }
      } catch (error) {
        console.error('加载老师排行失败:', error)
      }
    },
    // 加载运营统计
    async loadOperationStatistics(params) {
      try {
        const res = await request({
          url: '/api/Extend/LqTechDepartmentDashboard/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/LqTechDepartmentDashboard/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/LqTechDepartmentDashboard/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 loadTeacherDetailList(params) {
      this.teacherDetailList.loading = true
      try {
        const res = await request({
          url: '/api/Extend/LqTechDepartmentDashboard/GetTeacherDetailList',
          method: 'POST',
          data: {
            ...params,
            currentPage: this.teacherDetailList.pagination.currentPage,
            pageSize: this.teacherDetailList.pagination.pageSize
          }
        })
        if (res.code === 200 && res.data) {
          this.teacherDetailList.data = res.data.list || []
          this.teacherDetailList.pagination.total = (res.data.pagination && res.data.pagination.total) || 0
        }
      } catch (error) {
        console.error('加载老师明细列表失败:', error)
      } finally {
        this.teacherDetailList.loading = false
      }
    },
    // 加载开单明细列表
    async loadBillingDetailList(params) {
      this.billingDetailList.loading = true
      try {
        const res = await request({
          url: '/api/Extend/LqTechDepartmentDashboard/GetBillingDetailList',
          method: 'POST',
          data: {
            ...params,
            currentPage: this.billingDetailList.pagination.currentPage,
            pageSize: this.billingDetailList.pagination.pageSize
          }
        })
        if (res.code === 200 && res.data) {
          this.billingDetailList.data = res.data.list || []
          this.billingDetailList.pagination.total = (res.data.pagination && res.data.pagination.total) || 0
        }
      } catch (error) {
        console.error('加载开单明细列表失败:', error)
      } finally {
        this.billingDetailList.loading = false
      }
    },
    // 加载消耗明细列表
    async loadConsumeDetailList(params) {
      this.consumeDetailList.loading = true
      try {
        const res = await request({
          url: '/api/Extend/LqTechDepartmentDashboard/GetConsumeDetailList',
          method: 'POST',
          data: {
            ...params,
            currentPage: this.consumeDetailList.pagination.currentPage,
            pageSize: this.consumeDetailList.pagination.pageSize
          }
        })
        if (res.code === 200 && res.data) {
          this.consumeDetailList.data = res.data.list || []
          this.consumeDetailList.pagination.total = (res.data.pagination && res.data.pagination.total) || 0
        }
      } catch (error) {
        console.error('加载消耗明细列表失败:', error)
      } finally {
        this.consumeDetailList.loading = false
      }
    },
    // 初始化所有图表
    initAllCharts() {
      this.renderPerformanceTrendChart()
      this.renderStoreDistributionChart()
      this.renderShareTrendChart()
    },
    // 渲染业绩趋势图表
    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.TraceabilityAmount || 0),
            color: '#409EFF',
            lineStyle: { width: 2 }
          },
          {
            name: 'Cell金额',
            type: 'line',
            smooth: true,
            data: this.performanceTrend.TrendData.map(item => item.CellAmount || 0),
            color: '#67C23A',
            lineStyle: { width: 2 }
          },
          {
            name: '科美总收入',
            type: 'line',
            smooth: true,
            data: this.performanceTrend.TrendData.map(item => item.TotalKemeiIncome || 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.TotalKemeiIncome || 0), 0)
      
      // 处理数据，只给占比大于1%的显示标签
      const data = this.storeDistribution.DistributionData.map((item, index) => {
        const value = item.TotalKemeiIncome || 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'
          }
        }
      })
      
      // 门店数量判断：超过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) {
                // 只显示占比大于1%的标签
                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
          }
        ]
      })
    },
    // 渲染股份趋势图表
    renderShareTrendChart() {
      const chart = this.getChart('shareTrendChart')
      if (!this.shareTrend.TrendData || this.shareTrend.TrendData.length === 0) {
        chart.setOption({
          title: { text: '暂无数据', left: 'center', top: 'middle', textStyle: { color: '#909399' } }
        })
        return
      }
      const dates = this.shareTrend.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.shareTrend.TrendData.map(item => item.Income || 0),
            color: '#409EFF',
            lineStyle: { width: 2 }
          },
          {
            name: '总成本',
            type: 'line',
            smooth: true,
            data: this.shareTrend.TrendData.map(item => {
              return (item.CostReimbursement || 0) + (item.CostTeacherBase || 0) + (item.CostTeacherManual || 0) +
                (item.CostTeacherBillingComm || 0) + (item.CostTeacherConsumeComm || 0) + (item.CostGMBase || 0) + (item.CostGMComm || 0)
            }),
            color: '#F56C6C',
            lineStyle: { width: 2 }
          },
          {
            name: '利润',
            type: 'line',
            smooth: true,
            data: this.shareTrend.TrendData.map(item => item.Profit || 0),
            color: '#67C23A',
            lineStyle: { width: 2 }
          }
        ]
      })
    },
    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 'traceability':
        case 'cell':
        case 'total':
          targetId = 'billing-detail-list'
          break
        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,
        techDepartmentId: this.query.techDepartmentId,
        storeIds: []
      }
      this.loadStoreDetailList(params)
    },
    // 门店明细列表页码变化
    handleStoreDetailPageChange(val) {
      this.storeDetailList.pagination.currentPage = val
      const statisticsMonth = this.query.month.replace('-', '')
      const params = {
        statisticsMonth,
        techDepartmentId: this.query.techDepartmentId,
        storeIds: []
      }
      this.loadStoreDetailList(params)
    },
    // 老师明细列表分页大小变化
    handleTeacherDetailPageSizeChange(val) {
      this.teacherDetailList.pagination.pageSize = val
      this.teacherDetailList.pagination.currentPage = 1
      const statisticsMonth = this.query.month.replace('-', '')
      const params = {
        statisticsMonth,
        techDepartmentId: this.query.techDepartmentId,
        storeIds: []
      }
      this.loadTeacherDetailList(params)
    },
    // 老师明细列表页码变化
    handleTeacherDetailPageChange(val) {
      this.teacherDetailList.pagination.currentPage = val
      const statisticsMonth = this.query.month.replace('-', '')
      const params = {
        statisticsMonth,
        techDepartmentId: this.query.techDepartmentId,
        storeIds: []
      }
      this.loadTeacherDetailList(params)
    },
    // 开单明细列表分页大小变化
    handleBillingDetailPageSizeChange(val) {
      this.billingDetailList.pagination.pageSize = val
      this.billingDetailList.pagination.currentPage = 1
      const statisticsMonth = this.query.month.replace('-', '')
      const params = {
        statisticsMonth,
        techDepartmentId: this.query.techDepartmentId,
        storeIds: []
      }
      this.loadBillingDetailList(params)
    },
    // 开单明细列表页码变化
    handleBillingDetailPageChange(val) {
      this.billingDetailList.pagination.currentPage = val
      const statisticsMonth = this.query.month.replace('-', '')
      const params = {
        statisticsMonth,
        techDepartmentId: this.query.techDepartmentId,
        storeIds: []
      }
      this.loadBillingDetailList(params)
    },
    // 消耗明细列表分页大小变化
    handleConsumeDetailPageSizeChange(val) {
      this.consumeDetailList.pagination.pageSize = val
      this.consumeDetailList.pagination.currentPage = 1
      const statisticsMonth = this.query.month.replace('-', '')
      const params = {
        statisticsMonth,
        techDepartmentId: this.query.techDepartmentId,
        storeIds: []
      }
      this.loadConsumeDetailList(params)
    },
    // 消耗明细列表页码变化
    handleConsumeDetailPageChange(val) {
      this.consumeDetailList.pagination.currentPage = val
      const statisticsMonth = this.query.month.replace('-', '')
      const params = {
        statisticsMonth,
        techDepartmentId: this.query.techDepartmentId,
        storeIds: []
      }
      this.loadConsumeDetailList(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>
.tech-department-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;
      justify-content: space-between;
      align-items: center;
      padding: 12px 0;
      border-bottom: 1px solid #f0f2f5;

      &:last-child {
        border-bottom: none;
      }

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

      .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>

