<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 label-width="80px">
          <el-col :span="6">
            <el-form-item label="选择月份">
              <el-date-picker 
                v-model="query.month" 
                type="month" 
                value-format="yyyy-MM" 
                format="yyyy-MM" 
                placeholder="选择月份"
                style="width: 100%;"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label-width="0">
              <el-button type="primary" icon="el-icon-search" @click="search()">查询</el-button>
              <el-button icon="el-icon-refresh-right" @click="reset()">重置</el-button>
              <el-button icon="el-icon-download" @click="exportExcel()">导出Excel</el-button>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>

      <!-- 统计卡片 -->
      <el-row :gutter="16" class="statistics-cards" v-if="summaryData">
        <el-col :span="4">
          <div class="stat-card">
            <div class="stat-content">
              <div class="stat-label">
                开单业绩
              </div>
              <div class="stat-value">¥{{ formatMoney(summaryData.totalOrderAchievement) }}</div>
            </div>
          </div>
        </el-col>
        <el-col :span="4">
          <div class="stat-card">
            <div class="stat-content">
              <div class="stat-label">
                消耗业绩
              </div>
              <div class="stat-value">¥{{ formatMoney(summaryData.totalConsumeAchievement) }}</div>
            </div>
          </div>
        </el-col>
        <el-col :span="4">
          <div class="stat-card">
            <div class="stat-content">
              <div class="stat-label">
                退卡业绩
              </div>
              <div class="stat-value">¥{{ formatMoney(summaryData.totalRefundAchievement) }}</div>
            </div>
          </div>
        </el-col>
        <el-col :span="4">
          <div class="stat-card">
            <div class="stat-content">
              <div class="stat-label">
                总人头
              </div>
              <div class="stat-value">{{ summaryData.totalPersonCount || 0 }}</div>
            </div>
          </div>
        </el-col>
        <el-col :span="4">
          <div class="stat-card">
            <div class="stat-content">
              <div class="stat-label">
                手工费
              </div>
              <div class="stat-value">¥{{ formatMoney(summaryData.totalLaborCost) }}</div>
            </div>
          </div>
        </el-col>
      </el-row>

      <!-- 数据表格 -->
      <div class="NCC-common-layout-main NCC-flex-main table-wrapper">
        <el-table 
          v-loading="listLoading" 
          :data="list" 
          border 
          stripe
          :max-height="tableHeight"
          @sort-change="handleSortChange">
          <el-table-column prop="EmployeeId" label="员工ID" width="180" sortable="custom">
            <template slot-scope="scope">
              <span>{{ scope.row.EmployeeId || '无' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="EmployeeName" label="员工姓名" min-width="120" sortable="custom">
            <template slot-scope="scope">
              <span>{{ scope.row.EmployeeName || '无' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="OrderAchievement" label="开单业绩" min-width="130" sortable="custom">
            <template slot-scope="scope">
              <span class="amount-value">¥{{ formatMoney(scope.row.OrderAchievement) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="ConsumeAchievement" label="消耗业绩" min-width="130" sortable="custom">
            <template slot-scope="scope">
              <span class="amount-value">¥{{ formatMoney(scope.row.ConsumeAchievement) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="RefundAchievement" label="退卡业绩" min-width="130" sortable="custom">
            <template slot-scope="scope">
              <span class="amount-value">¥{{ formatMoney(scope.row.RefundAchievement) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="PersonCount" label="人头" width="100" sortable="custom">
            <template slot-scope="scope">
              <span>{{ scope.row.PersonCount !== null && scope.row.PersonCount !== undefined ? scope.row.PersonCount : 0 }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="LaborCost" label="手工费" min-width="130" sortable="custom">
            <template slot-scope="scope">
              <span class="amount-value">¥{{ formatMoney(scope.row.LaborCost) }}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </div>
</template>

<script>
import request from '@/utils/request'
import { saveAs } from 'file-saver'

export default {
  name: 'TechTeacherConsumeStatistics',
  data() {
    return {
      query: {
        month: ''
      },
      list: [],
      originalList: [], // 保存原始数据，用于取消排序时恢复
      listLoading: false,
      summaryData: null,
      sortProp: '',
      sortOrder: ''
    }
  },
  computed: {
    // 计算表格高度
    tableHeight() {
      // 减去头部、筛选条件、统计卡片、分页等高度
      return window.innerHeight - 350
    }
  },
  created() {
    this.setDefaultMonth()
    this.search()
  },
  methods: {
    // 设置默认月份（当前月份）
    setDefaultMonth() {
      const now = new Date()
      const year = now.getFullYear()
      const month = String(now.getMonth() + 1).padStart(2, '0')
      this.query.month = `${year}-${month}`
    },

    // 查询数据
    search() {
      if (!this.query.month) {
        this.$message({
          type: 'warning',
          message: '请选择月份',
          duration: 1500
        })
        return
      }

      this.listLoading = true

      // 解析年月
      const [year, month] = this.query.month.split('-')

      const params = {
        Year: parseInt(year),
        Month: parseInt(month)
      }

      request({
        url: '/api/Extend/lqtechteachersalary/statistics',
        method: 'GET',
        data: params
      }).then(res => {
        if (res.data && Array.isArray(res.data)) {
          this.list = res.data
          this.originalList = JSON.parse(JSON.stringify(res.data)) // 保存原始数据
          // 计算汇总数据
          this.calculateSummary(res.data)
        } else {
          this.list = []
          this.originalList = []
          this.summaryData = null
        }
        this.listLoading = false
      }).catch(err => {
        console.error('查询失败:', err)
        this.$message({
          type: 'error',
          message: '查询失败，请重试',
          duration: 1500
        })
        this.listLoading = false
        this.list = []
        this.originalList = []
        this.summaryData = null
      })
    },

    // 处理排序变化
    handleSortChange({ column, prop, order }) {
      if (!order) {
        // 取消排序，恢复原始顺序
        this.sortProp = ''
        this.sortOrder = ''
        if (this.originalList.length > 0) {
          this.list = JSON.parse(JSON.stringify(this.originalList))
        }
        return
      }
      
      this.sortProp = prop
      this.sortOrder = order === 'ascending' ? 'asc' : 'desc'
      
      this.sortList()
    },

    // 对列表进行排序
    sortList() {
      if (!this.sortProp || !this.sortOrder) {
        return
      }

      // 从原始数据开始排序，确保每次排序都是基于原始数据
      const sourceList = this.originalList.length > 0 ? JSON.parse(JSON.stringify(this.originalList)) : JSON.parse(JSON.stringify(this.list))
      
      // 创建新数组并排序
      const sortedList = sourceList.sort((a, b) => {
        let aVal = a[this.sortProp]
        let bVal = b[this.sortProp]

        // 处理空值
        if (aVal === null || aVal === undefined) aVal = 0
        if (bVal === null || bVal === undefined) bVal = 0

        // 数值类型直接比较
        if (typeof aVal === 'number' && typeof bVal === 'number') {
          return this.sortOrder === 'asc' ? aVal - bVal : bVal - aVal
        }

        // 字符串类型
        aVal = String(aVal || '')
        bVal = String(bVal || '')
        
        if (this.sortOrder === 'asc') {
          return aVal.localeCompare(bVal)
        } else {
          return bVal.localeCompare(aVal)
        }
      })
      
      // 重新赋值整个数组以触发响应式更新
      this.list = sortedList
      this.$nextTick(() => {
        this.$forceUpdate()
      })
    },

    // 计算汇总数据
    calculateSummary(data) {
      if (!data || data.length === 0) {
        this.summaryData = {
          totalOrderAchievement: 0,
          totalConsumeAchievement: 0,
          totalRefundAchievement: 0,
          totalPersonCount: 0,
          totalPersonTimes: 0,
          totalLaborCost: 0
        }
        return
      }

      this.summaryData = {
        totalOrderAchievement: data.reduce((sum, item) => sum + (parseFloat(item.OrderAchievement) || 0), 0),
        totalConsumeAchievement: data.reduce((sum, item) => sum + (parseFloat(item.ConsumeAchievement) || 0), 0),
        totalRefundAchievement: data.reduce((sum, item) => sum + (parseFloat(item.RefundAchievement) || 0), 0),
        totalPersonCount: data.reduce((sum, item) => sum + (parseInt(item.PersonCount) || 0), 0),
        totalPersonTimes: data.reduce((sum, item) => sum + (parseInt(item.PersonTimes) || 0), 0),
        totalLaborCost: data.reduce((sum, item) => sum + (parseFloat(item.LaborCost) || 0), 0)
      }
    },

    // 重置查询条件
    reset() {
      this.setDefaultMonth()
      this.list = []
      this.originalList = []
      this.summaryData = null
      this.sortProp = ''
      this.sortOrder = ''
      this.search()
    },

    // 格式化金额
    formatMoney(amount) {
      if (amount === null || amount === undefined || amount === '') {
        return '0.00'
      }
      const num = parseFloat(amount)
      if (isNaN(num)) {
        return '0.00'
      }
      return num.toFixed(2)
    },

    // 导出Excel
    async exportExcel() {
      if (!this.list || this.list.length === 0) {
        this.$message({
          type: 'warning',
          message: '暂无数据可导出',
          duration: 1500
        })
        return
      }

      try {
        // 动态导入 xlsx 库
        const XLSX = await import('xlsx')
        
        // 构建表头
        const headers = [
          '员工ID',
          '员工姓名',
          '开单业绩',
          '消耗业绩',
          '退卡业绩',
          '人头',
          '手工费'
        ]
        
        // 构建数据行
        const dataRows = this.list.map(row => [
          row.EmployeeId || '无',
          row.EmployeeName || '无',
          this.formatMoney(row.OrderAchievement),
          this.formatMoney(row.ConsumeAchievement),
          this.formatMoney(row.RefundAchievement),
          row.PersonCount !== null && row.PersonCount !== undefined ? row.PersonCount : 0,
          this.formatMoney(row.LaborCost)
        ])
        
        // 合并表头和数据
        const excelData = [headers, ...dataRows]
        
        // 创建工作簿
        const ws = XLSX.utils.aoa_to_sheet(excelData)
        
        // 设置列宽
        ws['!cols'] = [
          { wch: 18 }, // 员工ID
          { wch: 12 }, // 员工姓名
          { wch: 15 }, // 订单业绩
          { wch: 15 }, // 耗卡业绩
          { wch: 15 }, // 退款业绩
          { wch: 10 }, // 人数
          { wch: 15 }  // 人工成本
        ]
        
        // 创建工作簿
        const wb = XLSX.utils.book_new()
        XLSX.utils.book_append_sheet(wb, ws, '科技部老师耗卡业绩')
        
        // 生成文件名
        const [year, month] = this.query.month.split('-')
        const fileName = `科技部老师耗卡业绩_${year}年${month}月_${new Date().getTime()}.xlsx`
        
        // 导出文件
        const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'array' })
        saveAs(new Blob([wbout], { type: 'application/octet-stream' }), fileName)
        
        this.$message({
          type: 'success',
          message: '导出成功',
          duration: 1500
        })
      } catch (error) {
        console.error('导出失败:', error)
        if (error.message && error.message.includes('xlsx')) {
          this.$message({
            type: 'error',
            message: '导出失败：请先安装 xlsx 库，运行命令: npm install xlsx --save',
            duration: 3000
          })
        } else {
          this.$message({
            type: 'error',
            message: '导出失败：' + (error.message || '未知错误'),
            duration: 2000
          })
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.statistics-cards {
  margin-bottom: 16px;
  
  .stat-card {
    height: 100px;
    padding: 12px;
    background: #fff;
    border-radius: 12px;
    border: 1px solid #e4e7ed;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
    
    .stat-content {
      height: 100%;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: flex-start;
      
      .stat-label {
        font-size: 13px;
        color: #606266;
        margin-bottom: 8px;
      }
      
      .stat-value {
        font-size: 20px;
        font-weight: 600;
        color: #303133;
      }
    }
  }
}

.table-wrapper {
  height: 100%;
  
  ::v-deep .el-table__body-wrapper {
    overflow-y: scroll !important;
  }
}

.amount-value {
  color: #409EFF;
  font-weight: 500;
}
</style>

