<template>
  <div class="NCC-common-layout">
    <div class="NCC-common-layout-center">
      <!-- 筛选条件 -->
      <el-row class="NCC-common-search-box" :gutter="16">
        <el-form @submit.native.prevent>
          <el-col :span="6">
            <el-form-item label="开始时间">
              <el-date-picker 
                v-model="query.startTime" 
                type="datetime" 
                value-format="yyyy-MM-dd HH:mm:ss" 
                format="yyyy-MM-dd HH:mm:ss" 
                placeholder="开始时间"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="结束时间">
              <el-date-picker 
                v-model="query.endTime" 
                type="datetime" 
                value-format="yyyy-MM-dd HH:mm:ss" 
                format="yyyy-MM-dd HH:mm:ss" 
                placeholder="结束时间"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="组织类型">
              <el-select
                v-model="query.organizationType"
                placeholder="请选择组织类型"
                filterable
                clearable
                @change="handleOrganizationTypeChange"
                :style='{"width":"100%"}'>
                <el-option label="事业部" value="事业部"></el-option>
                <el-option label="科技部" value="科技部"></el-option>
                <el-option label="教育部" value="教育部"></el-option>
                <el-option label="大项目部" value="大项目部"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="部门">
              <el-select
                v-model="query.departmentId"
                placeholder="请选择部门"
                filterable
                clearable
                @change="handleDepartmentChange"
                :style='{"width":"100%"}'>
                <el-option
                  v-for="dept in departmentOptions"
                  :key="dept.Id || dept.id"
                  :label="dept.FullName || dept.fullName"
                  :value="dept.Id || dept.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="门店">
              <el-select
                v-model="query.storeIds"
                placeholder="请选择门店"
                multiple
                filterable
                clearable
                :style='{"width":"100%"}'>
                <el-option
                  v-for="store in storeOptions"
                  :key="store.id"
                  :label="store.dm"
                  :value="store.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" @click="search()">查询</el-button>
              <el-button icon="el-icon-refresh-right" @click="reset()">重置</el-button>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>

      <!-- 统计卡片 -->
      <div class="statistics-cards" v-if="summaryData">
        <el-row :gutter="12">
          <el-col :span="4">
            <div class="statistics-card invite-card">
              <div class="card-icon">
                <i class="el-icon-user-solid"></i>
              </div>
              <div class="card-content">
                <div class="card-title">总邀请数</div>
                <div class="card-value">{{ summaryData.totalInviteCount || 0 }}</div>
              </div>
            </div>
          </el-col>
          <el-col :span="4">
            <div class="statistics-card appointment-card">
              <div class="card-icon">
                <i class="el-icon-date"></i>
              </div>
              <div class="card-content">
                <div class="card-title">总预约数</div>
                <div class="card-value">{{ summaryData.totalAppointmentCount || 0 }}</div>
              </div>
            </div>
          </el-col>
          <el-col :span="4">
            <div class="statistics-card visit-card">
              <div class="card-icon">
                <i class="el-icon-location"></i>
              </div>
              <div class="card-content">
                <div class="card-title">总到店人数</div>
                <div class="card-value">{{ summaryData.totalVisitCount || 0 }}</div>
              </div>
            </div>
          </el-col>
          <el-col :span="4">
            <div class="statistics-card billing-card">
              <div class="card-icon">
                <i class="el-icon-document"></i>
              </div>
              <div class="card-content">
                <div class="card-title">总开单数</div>
                <div class="card-value">{{ summaryData.totalBillingCount || 0 }}</div>
              </div>
            </div>
          </el-col>
          <el-col :span="4">
            <div class="statistics-card billing-amount-card">
              <div class="card-icon">
                <i class="el-icon-money"></i>
              </div>
              <div class="card-content">
                <div class="card-title">总开单金额</div>
                <div class="card-value">¥{{ formatMoney(summaryData.totalBillingAmount) }}</div>
              </div>
            </div>
          </el-col>
          <el-col :span="4">
            <div class="statistics-card consume-card">
              <div class="card-icon">
                <i class="el-icon-success"></i>
              </div>
              <div class="card-content">
                <div class="card-title">总消耗金额</div>
                <div class="card-value">¥{{ formatMoney(summaryData.totalConsumeAmount) }}</div>
              </div>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="12" style="margin-top: 12px;">
          <el-col :span="4">
            <div class="statistics-card refund-card">
              <div class="card-icon">
                <i class="el-icon-warning"></i>
              </div>
              <div class="card-content">
                <div class="card-title">总退款金额</div>
                <div class="card-value">¥{{ formatMoney(summaryData.totalRefundAmount) }}</div>
              </div>
            </div>
          </el-col>
          <el-col :span="4">
            <div class="statistics-card performance-card">
              <div class="card-icon">
                <i class="el-icon-star-on"></i>
              </div>
              <div class="card-content">
                <div class="card-title">总个人业绩</div>
                <div class="card-value">¥{{ formatMoney(summaryData.totalPersonalPerformance) }}</div>
              </div>
            </div>
          </el-col>
          <el-col :span="4">
            <div class="statistics-card headcount-card">
              <div class="card-icon">
                <i class="el-icon-user"></i>
              </div>
              <div class="card-content">
                <div class="card-title">总人头数</div>
                <div class="card-value">{{ formatNumber(summaryData.totalHeadCount) }}</div>
              </div>
            </div>
          </el-col>
          <el-col :span="4">
            <div class="statistics-card personcount-card">
              <div class="card-icon">
                <i class="el-icon-s-custom"></i>
              </div>
              <div class="card-content">
                <div class="card-title">总人次</div>
                <div class="card-value">{{ formatNumber(summaryData.totalPersonCount) }}</div>
              </div>
            </div>
          </el-col>
          <el-col :span="4">
            <div class="statistics-card project-card">
              <div class="card-icon">
                <i class="el-icon-goods"></i>
              </div>
              <div class="card-content">
                <div class="card-title">总项目数</div>
                <div class="card-value">{{ summaryData.totalProjectCount || 0 }}</div>
              </div>
            </div>
          </el-col>
          <el-col :span="4">
            <div class="statistics-card labor-card">
              <div class="card-icon">
                <i class="el-icon-coin"></i>
              </div>
              <div class="card-content">
                <div class="card-title">总手工费</div>
                <div class="card-value">{{ summaryData.totalLaborCost || 0 }}</div>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>

      <!-- 数据表格 -->
      <div class="NCC-common-layout-main NCC-flex-main">
        <NCC-table 
          v-loading="listLoading" 
          :data="list" 
          has-c
        >
          <el-table-column prop="employeeName" label="员工姓名"  />
          <el-table-column prop="storeName" label="门店名称"  />
          <el-table-column prop="departmentName" label="部门名称"  />
          <el-table-column prop="goldTriangleName" label="金三角名称"  >
            <template slot-scope="scope">
              {{ scope.row.goldTriangleName || '无' }}
            </template>
          </el-table-column>
          <el-table-column prop="teamPerformanceRatio" label="业绩占比">
            <template slot-scope="scope">
              {{ formatPercentage(scope.row.teamPerformanceRatio) }}
            </template>
          </el-table-column>
          <el-table-column prop="inviteCount" label="邀请数"  >
            <template slot-scope="scope">
              <span class="clickable-cell" @click="handleInviteClick(scope.row)">
                {{ scope.row.inviteCount || 0 }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="appointmentCount" label="预约数"  >
            <template slot-scope="scope">
              <span class="clickable-cell" @click="handleAppointmentClick(scope.row)">
                {{ scope.row.appointmentCount || 0 }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="到店人数" label="到店人数"  >
            <template slot-scope="scope">
              <span class="clickable-cell" @click="handleVisitClick(scope.row)">
                {{ scope.row.visitCount || 0 }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="billingCount" label="开单数"  >
            <template slot-scope="scope">
              <span class="clickable-cell" @click="handleBillingClick(scope.row)">
                {{ scope.row.billingCount || 0 }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="billingAmount" label="开单金额"  >
            <template slot-scope="scope">
              <span class="clickable-cell amount-value" @click="handleBillingAmountClick(scope.row)">
                ¥{{ formatMoney(scope.row.billingAmount) }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="consumeAmount" label="消耗金额"  >
            <template slot-scope="scope">
              <span class="clickable-cell amount-paid" @click="handleConsumeAmountClick(scope.row)">
                ¥{{ formatMoney(scope.row.consumeAmount) }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="refundAmount" label="退款金额"  >
            <template slot-scope="scope">
              <span class="clickable-cell amount-paid" @click="handleRefundAmountClick(scope.row)">
                ¥{{ formatMoney(scope.row.refundAmount) }}
              </span>
            </template>
          </el-table-column>
          <el-table-column  label="个人业绩"  >
            <template slot-scope="scope">
              <span class="amount-paid">¥{{ formatMoney(scope.row.billingAmount - scope.row.refundAmount) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="headCount" label="人头数"  >
            <template slot-scope="scope">
              {{ scope.row.headCount || 0 }}
            </template>
          </el-table-column>
          <el-table-column prop="personCount" label="人次"  >
            <template slot-scope="scope">
              {{ scope.row.personCount || 0 }}
            </template>
          </el-table-column>
          <el-table-column prop="projectCount" label="项目数"  >
            <template slot-scope="scope">
              {{ scope.row.projectCount || 0 }}
            </template>
          </el-table-column>
          <el-table-column prop="laborCost" label="手工费"  >
            <template slot-scope="scope">
              {{ scope.row.laborCost || 0 }}
            </template>
          </el-table-column>
        </NCC-table>

        <!-- 分页组件 -->
        <pagination 
          v-show="total > 0" 
          :total="total" 
          :page.sync="query.currentPage"
          :limit.sync="query.pageSize" 
          @pagination="search" 
        />
      </div>
    </div>
  </div>
</template>

<script>
import request from '@/utils/request'
import Pagination from '@/components/Pagination'

export default {
  name: 'StoreOverallStatistics',
  components: {
    Pagination
  },
  data() {
    return {
      query: {
        organizationType: undefined,
        departmentId: undefined,
        storeIds: [],
        startTime: undefined,
        endTime: undefined,
        currentPage: 1,
        pageSize: 20
      },
      storeOptions: [],
      departmentOptions: [],
      list: [],
      total: 0,
      listLoading: false,
      summaryData: null
    }
  },
  created() {

    if (sessionStorage.getItem('isshaixuan') === 'false') {
      this.setDefaultTimeRange()
    } else{
      this.restoreQueryParams()
    }
    this.loadAllStores()
    this.search()
  },
  watch: {
    // 监听开始时间变化，重新加载门店列表
    'query.startTime'() {
      this.$nextTick(() => {
        this.initStoreOptions()
      })
    }
  },
  methods: {
    // 保存筛选条件到 sessionStorage
    saveQueryParams() {
      try {
        const paramsToSave = {
          organizationType: this.query.organizationType,
          departmentId: this.query.departmentId,
          storeIds: this.query.storeIds,
          startTime: this.query.startTime,
          endTime: this.query.endTime,
          currentPage: this.query.currentPage,
          pageSize: this.query.pageSize
        }
        sessionStorage.setItem('form7_query_params', JSON.stringify(paramsToSave))
        sessionStorage.setItem('isshaixuan', true)
      } catch (err) {
        console.error('保存筛选条件失败:', err)
      }
    },

    // 从 sessionStorage 恢复筛选条件
    restoreQueryParams() {
      try {
        const savedParams = sessionStorage.getItem('form7_query_params')
        if (savedParams) {
          const params = JSON.parse(savedParams)
          // 恢复筛选条件
          this.query.organizationType = params.organizationType || undefined
          this.query.departmentId = params.departmentId || undefined
          this.query.storeIds = params.storeIds || []
          this.query.startTime = params.startTime || undefined
          this.query.endTime = params.endTime || undefined
          this.query.currentPage = params.currentPage || 1
          this.query.pageSize = params.pageSize || 20
          
          // 如果没有时间范围，设置默认值
          if (!this.query.startTime || !this.query.endTime) {
            this.setDefaultTimeRange()
          }
          
          // 恢复部门选项和门店列表
          if (this.query.organizationType) {
            this.loadDepartmentOptions()
          }
          if (this.query.departmentId && this.query.organizationType && this.query.startTime) {
            this.$nextTick(() => {
              this.initStoreOptions()
            })
          } else {
            this.loadAllStores()
          }
          
          sessionStorage.setItem('isshaixuan', false)
        } else {
          // 没有保存的条件，设置默认时间范围
          this.setDefaultTimeRange()
        }
      } catch (err) {
        console.error('恢复筛选条件失败:', err)
        // 出错时设置默认时间范围
        this.setDefaultTimeRange()
      }
    },

    // 设置默认时间范围（本月1号到现在）
    setDefaultTimeRange() {
      const now = new Date()
      const firstDayOfMonth = new Date(now.getFullYear(), now.getMonth(), 1)
      
      this.query.startTime = this.formatDateTime(firstDayOfMonth.getTime())
      this.query.endTime = this.formatDateTime(now.getTime())
      
      // 时间设置后，如果有组织类型和部门，重新加载门店列表
      if (this.query.organizationType && this.query.departmentId) {
        this.$nextTick(() => {
          this.initStoreOptions()
        })
      }
    },

    // 加载全部门店（当没有选择部门时）
    loadAllStores() {
      request({
        url: '/api/Extend/LqMdxx',
        method: 'GET',
        data: {
          currentPage: 1,
          pageSize: 1000
        }
      }).then(res => {
        this.storeOptions = res.data.list || []
      }).catch(err => {
        console.error('获取门店列表失败:', err)
        this.storeOptions = []
      })
    },

    // 获取部门选项（根据组织类型）
    loadDepartmentOptions() {
      if (!this.query.organizationType) {
        this.departmentOptions = []
        return
      }
      
      request({
        url: '/api/Extend/Organize/GetByName',
        method: 'GET',
        data: {
          organizeName: this.query.organizationType
        }
      }).then(res => {
        this.departmentOptions = res.data || []
        // 如果部门ID不在新列表中，清空部门ID
        if (this.query.departmentId) {
          const exists = this.departmentOptions.some(
            dept => (dept.Id || dept.id) === this.query.departmentId
          )
          if (!exists) {
            this.query.departmentId = undefined
            this.query.storeIds = []
            this.storeOptions = []
          }
        }
      }).catch(() => {
        this.departmentOptions = []
      })
    },

    // 初始化门店选项（根据组织类型、部门、年月）
    initStoreOptions() {
      // 如果没有选择部门，加载全部门店
      if (!this.query.departmentId) {
        this.loadAllStores()
        return
      }

      // 如果缺少必要参数，不加载门店列表
      if (!this.query.organizationType || !this.query.startTime) {
        this.storeOptions = []
        return
      }

      // 从开始时间提取年月（格式：YYYYMM）
      // startTime 格式为 yyyy-MM-dd HH:mm:ss
      const dateStr = this.query.startTime
      if (!dateStr) {
        this.storeOptions = []
        return
      }
      
      // 提取年月，格式：YYYYMM
      const monthStr = dateStr.substring(0, 4) + dateStr.substring(5, 7)

      request({
        url: '/api/Extend/lqmdtarget/GetManagedStores',
        method: 'POST',
        data: {
          month: monthStr,
          organizationType: this.query.organizationType,
          departmentId: this.query.departmentId
        }
      }).then(res => {
        if (res.data && Array.isArray(res.data)) {
          // 将返回的数据格式转换为 storeOptions 需要的格式
          // 返回格式: [{ StoreId: "...", StoreName: "..." }]
          // 需要格式: [{ id: "...", dm: "..." }]
          this.storeOptions = res.data.map(store => ({
            id: store.StoreId,
            dm: store.StoreName
          }))
          // 默认选中所有获取到的门店
          this.query.storeIds = this.storeOptions.map(store => store.id)
        } else {
          this.storeOptions = []
          this.query.storeIds = []
        }
      }).catch(err => {
        console.error('获取门店列表失败:', err)
        this.$message({
          type: 'error',
          message: '获取门店列表失败',
          duration: 1500
        })
        this.storeOptions = []
        this.query.storeIds = []
      })
    },

    // 处理组织类型变化
    handleOrganizationTypeChange() {
      // 清空部门和门店
      this.query.departmentId = undefined
      this.query.storeIds = []
      // 重新加载部门选项
      this.loadDepartmentOptions()
      // 加载全部门店（因为部门已清空）
      this.loadAllStores()
    },

    // 处理部门变化
    handleDepartmentChange() {
      // 清空门店选择
      this.query.storeIds = []
      // 重新加载门店列表（如果有部门则加载部门管理的门店，否则加载全部门店）
      this.initStoreOptions()
    },



    // 查询数据
    search() {
      this.listLoading = true
      // 保存当前筛选条件
      // this.saveQueryParams()

      const params = {
        currentPage: this.query.currentPage,
        pageSize: this.query.pageSize
      }

      if (this.query.storeIds && this.query.storeIds.length > 0) {
        params.StoreIds = this.query.storeIds.join(',')
      }

      if (this.query.departmentId) {
        params.DepartmentId = this.query.departmentId
      }

      if (this.query.startTime) {
        params.StartTime = this.query.startTime
      }

      if (this.query.endTime) {
        params.EndTime = this.query.endTime
      }

      request({
        url: '/api/Extend/lqkdkdjlb/get-health-coach-statistics',
        method: 'GET',
        data: params
      }).then(res => {
        if (res.data && res.data.list) {
          this.list = res.data.list
          this.total = (res.data.pagination && res.data.pagination.totalCount) || 0
          // 计算汇总数据
          this.calculateSummary(res.data.list)
        } else {
          this.list = []
          this.total = 0
          this.summaryData = null
        }
        this.listLoading = false
      }).catch(err => {
        console.error('查询失败:', err)
        this.$message({
          type: 'error',
          message: '查询失败，请重试',
          duration: 1500
        })
        this.listLoading = false
        this.summaryData = null
      })
    },

    // 计算汇总数据
    calculateSummary(dataList) {
      if (!dataList || dataList.length === 0) {
        this.summaryData = null
        return
      }

      const summary = {
        totalInviteCount: 0,
        totalAppointmentCount: 0,
        totalVisitCount: 0,
        totalBillingCount: 0,
        totalBillingAmount: 0,
        totalConsumeAmount: 0,
        totalRefundAmount: 0,
        totalPersonalPerformance: 0,
        totalHeadCount: 0,
        totalPersonCount: 0,
        totalProjectCount: 0,
        totalLaborCost: 0
      }

      dataList.forEach(item => {
        summary.totalInviteCount += Number(item.inviteCount) || 0
        summary.totalAppointmentCount += Number(item.appointmentCount) || 0
        summary.totalVisitCount += Number(item.visitCount) || 0
        summary.totalBillingCount += Number(item.billingCount) || 0
        summary.totalBillingAmount += Number(item.billingAmount) || 0
        summary.totalConsumeAmount += Number(item.consumeAmount) || 0
        summary.totalRefundAmount += Number(item.refundAmount) || 0
        summary.totalHeadCount += Number(item.headCount) || 0
        summary.totalPersonCount += Number(item.personCount) || 0
        summary.totalProjectCount += Number(item.projectCount) || 0
        summary.totalLaborCost += Number(item.laborCost) || 0
      })

      // 计算总个人业绩（开单金额 - 退款金额）
      summary.totalPersonalPerformance = summary.totalBillingAmount - summary.totalRefundAmount

      this.summaryData = summary
    },

    // 重置查询条件
    reset() {
      this.query = {
        organizationType: undefined,
        departmentId: undefined,
        storeIds: [],
        startTime: undefined,
        endTime: undefined,
        currentPage: 1,
        pageSize: 20
      }
      this.setDefaultTimeRange()
      this.departmentOptions = []
      // 重置后加载全部门店
      this.loadAllStores()
      // 清除保存的筛选条件
      try {
        sessionStorage.removeItem('form7_query_params')
      } catch (err) {
        console.error('清除保存的筛选条件失败:', err)
      }
      this.list = []
      this.total = 0
      this.summaryData = null
      this.search()
    },

    // 格式化金额
    formatMoney(amount) {
      if (!amount && amount !== 0) return '0.00'
      return Number(amount).toFixed(2)
    },

    // 格式化数字，保留两位小数
    formatNumber(num) {
      if (num === null || num === undefined || num === '') return '0.00'
      const value = Number(num)
      if (isNaN(value)) return '0.00'
      return value.toFixed(2)
    },

    // 格式化百分比
    formatPercentage(ratio) {
      if (ratio === null || ratio === undefined) return '0.00%'
      return `${Number(ratio).toFixed(2)}%`
    },

    // 格式化日期时间（用于API传参）
    formatDateTime(timestamp) {
      if (!timestamp) return ''
      const date = new Date(timestamp)
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      const seconds = String(date.getSeconds()).padStart(2, '0')
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    },

    // 将时间字符串转换为时间戳（毫秒）
    getTimestamp(timeStr) {
      if (!timeStr) return ''
      // 手动解析 yyyy-MM-dd HH:mm:ss 格式，避免时区问题
      const parts = timeStr.match(/(\d{4})-(\d{2})-(\d{2})\s+(\d{2}):(\d{2}):(\d{2})/)
      if (!parts) {
        // 如果格式不匹配，尝试使用 Date 解析
        return new Date(timeStr).getTime()
      }
      // 创建本地时间的 Date 对象
      const year = parseInt(parts[1], 10)
      const month = parseInt(parts[2], 10) - 1 // 月份从0开始
      const day = parseInt(parts[3], 10)
      const hours = parseInt(parts[4], 10)
      const minutes = parseInt(parts[5], 10)
      const seconds = parseInt(parts[6], 10)
      return new Date(year, month, day, hours, minutes, seconds).getTime()
    },

    // 处理邀请数点击事件
    handleInviteClick(row) {
      if (row && row.employeeId) {
        this.saveQueryParams()
        this.$router.push({
          path: '/lqYaoyjl',
          query: {
            employeeId: row.employeeId,
            storeId: row.storeId || '',
            startTime: this.getTimestamp(this.query.startTime),
            endTime: this.getTimestamp(this.query.endTime),
          }
        })
      } else {
        this.$message({
          type: 'warning',
          message: '无法获取健康师ID',
          duration: 1500
        })
      }
    },

    // 处理预约数点击事件
    handleAppointmentClick(row) {
      if (row && row.employeeId) {
        this.saveQueryParams()
        this.$router.push({
          path: '/lqYyjl',
          query: {
            employeeId: row.employeeId,
            storeId: row.storeId || '',
            startTime: this.getTimestamp(this.query.startTime),
            endTime: this.getTimestamp(this.query.endTime),
          }
        })
      } else {
        this.$message({
          type: 'warning',
          message: '无法获取健康师ID',
          duration: 1500
        })
      }
    },

    // 处理到店人数点击事件
    handleVisitClick(row) {
      if (row && row.employeeId) {
        this.saveQueryParams()
        this.$router.push({
          path: '/lqYyjl',
          query: {
            employeeId: row.employeeId,
            storeId: row.storeId || '',
            startTime: this.getTimestamp(this.query.startTime),
            endTime: this.getTimestamp(this.query.endTime),
            type:'已确认'
          }
        })
      } else {
        this.$message({
          type: 'warning',
          message: '无法获取健康师ID',
          duration: 1500
        })
      }
    },

    // 处理开单数点击事件
    handleBillingClick(row) {
      if (row && row.employeeId) {
        this.saveQueryParams()
        this.$router.push({
          path: '/lqKdKdjlb',
          query: {
            jksId: row.employeeId,
            storeId: row.storeId || '',
            startTime: this.getTimestamp(this.query.startTime),
            endTime: this.getTimestamp(this.query.endTime),
          }
        })
      } else {
        this.$message({
          type: 'warning',
          message: '无法获取健康师ID',
          duration: 1500
        })
      }
    },

    // 处理开单金额点击事件
    handleBillingAmountClick(row) {
      if (row && row.employeeId) {
        this.saveQueryParams()
        this.$router.push({
          path: '/lqKdKdjlb',
          query: {
            jksId: row.employeeId,
            storeId: row.storeId || '',
            startTime: this.getTimestamp(this.query.startTime),
            endTime: this.getTimestamp(this.query.endTime),
          }
        })
      } else {
        this.$message({
          type: 'warning',
          message: '无法获取健康师ID',
          duration: 1500
        })
      }
    },

    // 处理消耗金额点击事件
    handleConsumeAmountClick(row) {
      if (row && row.employeeId) {
        this.saveQueryParams()
        this.$router.push({
          path: '/lqXhHyhk',
          query: {
            jksId: row.employeeId,
            storeId: row.storeId || '',
            startTime: this.getTimestamp(this.query.startTime),
            endTime: this.getTimestamp(this.query.endTime),
          }
        })
      } else {
        this.$message({
          type: 'warning',
          message: '无法获取健康师ID',
          duration: 1500
        })
      }
    },

    // 处理退款金额点击事件
    handleRefundAmountClick(row) {
      if (row && row.employeeId) {
        this.saveQueryParams()
        this.$router.push({
          path: '/lqHytkHytk',
          query: {
            jksId: row.employeeId,
            storeId: row.storeId || '',
            startTime: this.getTimestamp(this.query.startTime),
            endTime: this.getTimestamp(this.query.endTime),
          }
        })
      } else {
        this.$message({
          type: 'warning',
          message: '无法获取健康师ID',
          duration: 1500
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.statistics-cards {
  margin-bottom: 16px;
}

.statistics-card {
  height: 72px;
  padding: 10px;
  border-radius: 8px;
  background: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  display: flex;
  align-items: center;
  transition: all 0.2s ease;
  cursor: default;
  
  &:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
  }
  
  .card-icon {
    width: 44px;
    height: 44px;
    border-radius: 6px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 10px;
    flex-shrink: 0;
    
    i {
      font-size: 20px;
      color: #fff;
    }
  }
  
  // 不同卡片的图标颜色
  &.invite-card .card-icon {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  }
  
  &.appointment-card .card-icon {
    background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
  }
  
  &.visit-card .card-icon {
    background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  }
  
  &.billing-card .card-icon {
    background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
  }
  
  &.billing-amount-card .card-icon {
    background: linear-gradient(135deg, #409EFF 0%, #66B1FF 100%);
  }
  
  &.consume-card .card-icon {
    background: linear-gradient(135deg, #67C23A 0%, #85ce61 100%);
  }
  
  &.refund-card .card-icon {
    background: linear-gradient(135deg, #F56C6C 0%, #f78989 100%);
  }
  
  &.performance-card .card-icon {
    background: linear-gradient(135deg, #E6A23C 0%, #ebb563 100%);
  }
  
  &.headcount-card .card-icon {
    background: linear-gradient(135deg, #909399 0%, #a6a9ad 100%);
  }
  
  &.personcount-card .card-icon {
    background: linear-gradient(135deg, #606266 0%, #787c82 100%);
  }
  
  &.project-card .card-icon {
    background: linear-gradient(135deg, #409EFF 0%, #66B1FF 100%);
  }
  
  &.labor-card .card-icon {
    background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
  }
  
  .card-content {
    flex: 1;
    min-width: 0;
    
    .card-title {
      font-size: 12px;
      color: #909399;
      margin-bottom: 4px;
      line-height: 1.2;
    }
    
    .card-value {
      font-size: 18px;
      font-weight: bold;
      color: #303133;
      line-height: 1.2;
      word-break: break-all;
    }
  }
}

// 表格区域样式
.NCC-common-layout-main {
  ::v-deep .el-table {
    .el-table__header {
      th {
        background-color: #f5f7fa;
        color: #606266;
        font-weight: 600;
      }
    }
    
    .el-table__body {
      tr:hover > td {
        background-color: #f5f7fa;
      }
    }
  }
}

.amount-value {
  color: #409EFF;
  font-weight: 500;
}

.amount-paid {
  color: #67C23A;
  font-weight: 500;
}

.clickable-cell {
  color: #409EFF;
  cursor: pointer;
  text-decoration: none;
  transition: color 0.2s ease;

  &:hover {
    color: #66b1ff;
    text-decoration: underline;
  }

  &:active {
    color: #3a8ee6;
  }
}

// 搜索框区域样式
.NCC-common-search-box {
  .el-form-item {
    margin-bottom: 18px;
    
    .el-form-item__label {
      font-weight: 500;
      color: #606266;
    }
  }
  
  .el-button {
    transition: all 0.2s ease;
    
    &:hover {
      transform: translateY(-1px);
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .statistics-cards {
    .el-col {
      margin-bottom: 16px;
    }
  }
  
  .statistics-card {
    height: 80px;
    padding: 8px;
    
    .card-icon {
      width: 50px;
      height: 50px;
      margin-right: 12px;
      
      i {
        font-size: 20px;
      }
    }
    
    .card-content {
      .card-title {
        font-size: 12px;
      }
      
      .card-value {
        font-size: 18px;
      }
    }
  }
}
</style>

