<template>
  <div class="app-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h2>科技部股份</h2>
        <p class="page-desc">管理科技部股份相关数据</p>
      </div>
      <div class="header-right">
        <el-button 
          type="success" 
          icon="el-icon-download"
          @click="handleExport"
          :loading="exportLoading"
        >
          导出
        </el-button>
        <el-button 
          type="primary" 
          icon="el-icon-cpu"
          @click="showCalculateDialog"
          :loading="calculateLoading"
        >
          计算股份
        </el-button>
        <el-button 
          icon="el-icon-refresh" 
          @click="getList"
          :loading="loading"
        >
          刷新
        </el-button>
      </div>
    </div>

    <!-- 搜索区域 -->
    <div class="search-container">
      <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="80px">
        <el-form-item label="统计月份" prop="statisticsMonth">
          <el-date-picker
            v-model="queryParams.statisticsMonth"
            type="month"
            placeholder="选择月份"
            format="yyyyMM"
            value-format="yyyyMM"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="部门" prop="departmentName">
          <el-select 
            v-model="queryParams.departmentName" 
            placeholder="请选择部门"
            clearable
            filterable
            style="width: 200px"
          >
            <el-option label="科技一部" value="科技一部" />
            <el-option label="科技二部" value="科技二部" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 数据表格 -->
    <div class="table-container">
      <NCC-table 
        v-loading="loading" 
        :data="list" 
        border 
        stripe
        height="calc(100vh - 420px)"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
      >
        <!-- 基本信息 -->
        <el-table-column prop="DepartmentName" label="部门名称" width="150" align="center" fixed="left">
          <template slot-scope="scope">
            <div class="department-name">
              <i class="el-icon-office-building department-icon"></i>
              <span>{{ scope.row.DepartmentName || '无' }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="StatisticsMonth" label="统计月份" width="120" align="center" fixed="left">
          <template slot-scope="scope">
            <span>{{ formatMonth(scope.row.StatisticsMonth) || '无' }}</span>
          </template>
        </el-table-column>

        <!-- 收入信息 -->
        <el-table-column label="收入信息" align="center">
          <el-table-column prop="Income" label="收入" width="120" align="center">
            <template slot-scope="scope">
              <span class="highlight">{{ formatMoney(scope.row.Income) }}</span>
            </template>
          </el-table-column>
        </el-table-column>

        <!-- 成本信息 -->
        <el-table-column label="成本信息" align="center">
          <el-table-column prop="CostReimbursement" label="成本-报销" width="120" align="center">
            <template slot-scope="scope">
              <span>{{ formatMoney(scope.row.CostReimbursement) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="CostTeacherBase" label="成本-人工-老师底薪" width="160" align="center">
            <template slot-scope="scope">
              <span>{{ formatMoney(scope.row.CostTeacherBase) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="CostTeacherManual" label="成本-人工-手工费" width="160" align="center">
            <template slot-scope="scope">
              <span>{{ formatMoney(scope.row.CostTeacherManual) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="CostTeacherBillingComm" label="成本-人工-开单提成" width="160" align="center">
            <template slot-scope="scope">
              <span>{{ formatMoney(scope.row.CostTeacherBillingComm) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="CostTeacherConsumeComm" label="成本-人工-消耗提成" width="160" align="center">
            <template slot-scope="scope">
              <span>{{ formatMoney(scope.row.CostTeacherConsumeComm) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="CostTeacherExpertComm" label="成本-人工-专家提成" width="160" align="center">
            <template slot-scope="scope">
              <span>{{ formatMoney(scope.row.CostTeacherExpertComm) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="CostTeacherOvertime" label="成本-人工-加班" width="140" align="center">
            <template slot-scope="scope">
              <span>{{ formatMoney(scope.row.CostTeacherOvertime) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="CostGMBase" label="成本-人工-总经理底薪" width="170" align="center">
            <template slot-scope="scope">
              <span>{{ formatMoney(scope.row.CostGMBase) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="CostGMComm" label="成本-人工-总经理提成" width="170" align="center">
            <template slot-scope="scope">
              <span>{{ formatMoney(scope.row.CostGMComm) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="CostOther1" label="成本-其他1" width="120" align="center">
            <template slot-scope="scope">
              <span>{{ formatMoney(scope.row.CostOther1) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="CostOther2" label="成本-其他2" width="120" align="center">
            <template slot-scope="scope">
              <span>{{ formatMoney(scope.row.CostOther2) }}</span>
            </template>
          </el-table-column>
        </el-table-column>

        <!-- 奖励 -->
        <el-table-column label="奖励" align="center">
          <el-table-column prop="RewardTechDept" label="奖励-科技部" width="140" align="center">
            <template slot-scope="scope">
              <span>{{ formatMoney(scope.row.RewardTechDept) }}</span>
            </template>
          </el-table-column>
        </el-table-column>

        <!-- 利润结果 -->
        <el-table-column label="利润结果" align="center">
          <el-table-column prop="Profit" label="利润" width="120" align="center">
            <template slot-scope="scope">
              <span class="highlight">{{ formatMoney(scope.row.Profit) }}</span>
            </template>
          </el-table-column>
        </el-table-column>

        <!-- 操作列 -->
        <el-table-column label="操作" width="120" align="center" fixed="right">
          <template slot-scope="scope">
            <el-button 
              type="text" 
              size="mini"
              icon="el-icon-view"
              @click="showDetail(scope.row)"
            >
              查看详情
            </el-button>
          </template>
        </el-table-column>
      </NCC-table>
    </div>

    <!-- 计算股份弹窗 -->
    <el-dialog
      title="计算科技部股份"
      :visible="calculateDialogVisible"
      width="500px"
      :close-on-click-modal="false"
      @close="handleCalculateDialogClose"
    >
      <el-form label-width="100px" label-position="right">
        <el-form-item label="统计月份" required>
          <el-date-picker
            v-model="calculateMonth"
            type="month"
            placeholder="请选择月份"
            format="yyyyMM"
            value-format="yyyyMM"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="部门">
          <el-select 
            v-model="calculateDepartmentName" 
            placeholder="请选择部门（不选则计算所有部门）"
            clearable
            filterable
            style="width: 100%"
          >
            <el-option label="科技一部" value="科技一部" />
            <el-option label="科技二部" value="科技二部" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleCalculateDialogClose">取消</el-button>
        <el-button 
          type="primary" 
          @click="handleCalculateConfirm"
          :loading="calculateLoading"
        >
          确定
        </el-button>
      </div>
    </el-dialog>

    <!-- 详情弹窗 -->
    <tech-stock-detail-dialog
      :visible="detailVisible"
      :detail-data="currentDetailData"
      @close="handleDetailClose"
    />
  </div>
</template>

<script>
import { getTechStockList, generateTechStock } from '@/api/extend/techStock'
import TechStockDetailDialog from './tech-stock-detail-dialog.vue'

export default {
  name: 'TechStock',
  components: {
    TechStockDetailDialog
  },
  data() {
    // 获取当前月份
    const getCurrentMonth = () => {
      const now = new Date()
      const year = now.getFullYear()
      const month = String(now.getMonth() + 1).padStart(2, '0')
      return `${year}${month}`
    }

    return {
      loading: false,
      calculateLoading: false,
      exportLoading: false,
      list: [],
      calculateDialogVisible: false,
      calculateMonth: getCurrentMonth(),
      calculateDepartmentName: '',
      detailVisible: false,
      currentDetailData: null,
      queryParams: {
        statisticsMonth: getCurrentMonth(), // yyyyMM 格式
        departmentName: ''
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 获取列表数据
    async getList() {
      this.loading = true
      try {
        const params = {
          StatisticsMonth: this.queryParams.statisticsMonth || undefined,
          DepartmentName: this.queryParams.departmentName || undefined
        }

        const response = await getTechStockList(params)

        if (response.code === 200) {
          this.list = response.data.data || []
        } else {
          this.$message.error(response.msg || '获取数据失败')
        }
      } catch (error) {
        console.error('获取科技部股份列表失败:', error)
        this.$message.error('获取数据失败')
      } finally {
        this.loading = false
      }
    },

    // 搜索
    handleQuery() {
      this.getList()
    },

    // 重置搜索
    resetQuery() {
      const getCurrentMonth = () => {
        const now = new Date()
        const year = now.getFullYear()
        const month = String(now.getMonth() + 1).padStart(2, '0')
        return `${year}${month}`
      }

      this.queryParams = {
        statisticsMonth: getCurrentMonth(),
        departmentName: ''
      }
      this.getList()
    },

    // 显示计算股份弹窗
    showCalculateDialog() {
      const getCurrentMonth = () => {
        const now = new Date()
        const year = now.getFullYear()
        const month = String(now.getMonth() + 1).padStart(2, '0')
        return `${year}${month}`
      }
      this.calculateMonth = getCurrentMonth()
      this.calculateDepartmentName = ''
      this.calculateDialogVisible = true
    },

    // 关闭计算股份弹窗
    handleCalculateDialogClose() {
      this.calculateDialogVisible = false
    },

    // 确认计算股份
    async handleCalculateConfirm() {
      if (!this.calculateMonth) {
        this.$message.warning('请选择统计月份')
        return
      }

      this.calculateLoading = true
      try {
        const data = {
          statisticsMonth: this.calculateMonth,
          departmentName: this.calculateDepartmentName || undefined
        }

        const response = await generateTechStock(data)
        if (response.code === 200) {
          this.$message.success('计算股份成功')
          this.calculateDialogVisible = false
          this.getList()
        } else {
          this.$message.error(response.msg || '计算股份失败')
        }
      } catch (error) {
        console.error('计算股份失败:', error)
        this.$message.error(error.message || '计算股份失败')
      } finally {
        this.calculateLoading = false
      }
    },

    // 显示详情
    showDetail(row) {
      this.currentDetailData = row
      this.detailVisible = true
    },

    // 关闭详情弹窗
    handleDetailClose() {
      this.detailVisible = false
      this.currentDetailData = null
    },

    // 导出功能
    async handleExport() {
      if (!this.list || this.list.length === 0) {
        this.$message.warning('暂无数据可导出')
        return
      }

      this.exportLoading = true
      try {
        // 动态导入 xlsx 库
        const XLSX = await import('xlsx')

        // 构建表头（根据后端DTO字段的中文映射）
        const headers = [
          '部门名称',
          '统计月份',
          '收入',
          '成本-报销',
          '成本-人工-老师底薪',
          '成本-人工-手工费',
          '成本-人工-开单提成',
          '成本-人工-消耗提成',
          '成本-人工-专家提成',
          '成本-人工-加班',
          '成本-人工-总经理底薪',
          '成本-人工-总经理提成',
          '奖励-科技部',
          '成本-其他1',
          '成本-其他2',
          '利润'
        ]

        // 构建数据行
        const dataRows = this.list.map(item => [
          item.DepartmentName || '无',
          this.formatMonth(item.StatisticsMonth) || '无',
          this.formatMoney(item.Income),
          this.formatMoney(item.CostReimbursement),
          this.formatMoney(item.CostTeacherBase),
          this.formatMoney(item.CostTeacherManual),
          this.formatMoney(item.CostTeacherBillingComm),
          this.formatMoney(item.CostTeacherConsumeComm),
          this.formatMoney(item.CostTeacherExpertComm),
          this.formatMoney(item.CostTeacherOvertime),
          this.formatMoney(item.CostGMBase),
          this.formatMoney(item.CostGMComm),
          this.formatMoney(item.RewardTechDept),
          this.formatMoney(item.CostOther1),
          this.formatMoney(item.CostOther2),
          this.formatMoney(item.Profit)
        ])

        // 合并表头和数据
        const excelData = [headers, ...dataRows]

        // 创建工作表
        const ws = XLSX.utils.aoa_to_sheet(excelData)

        // 设置列宽
        const colWidths = headers.map(() => ({ wch: 15 }))
        ws['!cols'] = colWidths

        // 创建工作簿
        const wb = XLSX.utils.book_new()
        XLSX.utils.book_append_sheet(wb, ws, '科技部股份')

        // 生成文件名
        const now = new Date()
        const timestamp = now.getFullYear() + 
          String(now.getMonth() + 1).padStart(2, '0') + 
          String(now.getDate()).padStart(2, '0') + 
          String(now.getHours()).padStart(2, '0') + 
          String(now.getMinutes()).padStart(2, '0') + 
          String(now.getSeconds()).padStart(2, '0')
        const fileName = `科技部股份_${timestamp}.xlsx`

        // 导出文件
        XLSX.writeFile(wb, fileName)

        this.$message.success('导出成功')
      } catch (error) {
        console.error('导出失败:', error)
        this.$message.error('导出失败，请重试')
      } finally {
        this.exportLoading = false
      }
    },

    // 格式化金额
    formatMoney(value) {
      if (value === null || value === undefined || value === '') {
        return '0.00'
      }
      return Number(value).toFixed(2)
    },

    // 格式化月份
    formatMonth(value) {
      if (!value || value.length !== 6) {
        return value || '无'
      }
      const year = value.substring(0, 4)
      const month = value.substring(4, 6)
      return `${year}-${month}`
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
  background: #f5f5f5;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);

  .header-left {
    h2 {
      margin: 0 0 8px 0;
      color: #303133;
      font-size: 20px;
      font-weight: 600;
    }

    .page-desc {
      margin: 0;
      color: #909399;
      font-size: 14px;
    }
  }

  .header-right {
    display: flex;
    gap: 12px;
  }
}

.search-container {
  margin-bottom: 20px;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.table-container {
  margin-bottom: 20px;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.department-name {
  display: flex;
  align-items: center;
  gap: 6px;

  .department-icon {
    color: #409EFF;
    font-size: 16px;
  }
}

.highlight {
  color: #409EFF;
  font-weight: 600;
}

// 表格样式优化
::v-deep .el-table {
  .el-table__header-wrapper {
    th {
      background-color: #f5f7fa;
      color: #606266;
      font-weight: 600;
    }
  }

  .el-table__body-wrapper {
    .el-table__row {
      &:hover {
        background-color: #f5f7fa;
      }
    }
  }
}
</style>
