<template>
  <div class="app-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h2>科技部总经理工资</h2>
        <p class="page-desc">管理科技部总经理工资数据，包括溯源金额、Cell金额、提成、补贴、扣款等信息</p>
      </div>
      <div class="header-right">
        <el-button 
          type="warning" 
          icon="el-icon-upload2"
          @click="showImportDialog"
          :loading="importLoading"
        >
          导入
        </el-button>
        <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="50px">
        <el-form-item label="月份" prop="month">
          <el-date-picker
            v-model="queryParams.month"
            type="month"
            placeholder="选择月份"
            format="yyyyMM"
            value-format="yyyyMM"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="岗位" prop="position">
          <el-select 
            v-model="queryParams.position" 
            placeholder="请选择岗位"
            clearable
            filterable
            style="width: 200px"
          >
            <el-option label="全部" :value="''" />
            <el-option label="科技一部" value="科技一部" />
            <el-option label="科技二部" value="科技二部" />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="关键词" prop="keyword">
          <el-input
            v-model="queryParams.keyword"
            placeholder="员工姓名/账号"
            clearable
            style="width: 200px"
          />
        </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 class="batch-action-container" v-if="selectedRows.length > 0">
        <span class="selected-count">已选择 {{ selectedRows.length }} 条记录</span>
        <el-button 
          type="warning" 
          icon="el-icon-lock"
          size="small"
          @click="handleBatchLock"
          :loading="lockLoading"
        >
          批量锁定
        </el-button>
        <el-button 
          type="success" 
          icon="el-icon-unlock"
          size="small"
          @click="handleBatchUnlock"
          :loading="lockLoading"
        >
          批量解锁
        </el-button>
        <el-button 
          type="info" 
          icon="el-icon-close"
          size="small"
          @click="handleClearSelection"
        >
          取消选择
        </el-button>
      </div>
    </div>

    <!-- 数据表格 -->
    <div class="table-container">
      <NCC-table 
        ref="table"
        v-loading="loading" 
        :data="list" 
        border 
        stripe
        height="calc(100vh - 420px)"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
        @selection-change="handleSelectionChange"
      >
        <!-- 多选列 -->
        <el-table-column type="selection" width="55" align="center" fixed="left" />
        <!-- 基本信息 -->
        <el-table-column prop="EmployeeName" label="员工姓名" width="120" align="center" fixed="left">
          <template slot-scope="scope">
            <div class="employee-name">
              <i class="el-icon-user employee-icon"></i>
              <span>{{ scope.row.EmployeeName || '无' }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="Position" label="岗位" width="120" align="center" fixed="left">
          <template slot-scope="scope">
            <span>{{ scope.row.Position || '无' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="EmployeeAccount" label="员工账号" width="120" align="center" fixed="left">
          <template slot-scope="scope">
            <span>{{ scope.row.EmployeeAccount || '无' }}</span>
          </template>
        </el-table-column>

        <!-- 业绩信息 -->
        <el-table-column label="业绩信息" align="center">
          <el-table-column prop="TraceabilityAmount" label="溯源金额" width="120" align="center">
            <template slot-scope="scope">
              <span>{{ formatMoney(scope.row.TraceabilityAmount) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="CellAmount" label="Cell金额" width="120" align="center">
            <template slot-scope="scope">
              <span>{{ formatMoney(scope.row.CellAmount) }}</span>
            </template>
          </el-table-column>
        </el-table-column>

        <!-- 提成信息 -->
        <el-table-column label="提成信息" align="center">
          <el-table-column prop="TraceabilityCommissionRate" label="溯源金额提成比例" width="160" align="center">
            <template slot-scope="scope">
              <span>{{ formatPercent(scope.row.TraceabilityCommissionRate) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="TraceabilityCommissionAmount" label="溯源金额提成金额" width="160" align="center">
            <template slot-scope="scope">
              <span>{{ formatMoney(scope.row.TraceabilityCommissionAmount) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="CellCommissionRate" label="Cell金额提成比例" width="160" align="center">
            <template slot-scope="scope">
              <span>{{ formatPercent(scope.row.CellCommissionRate) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="CellCommissionAmount" label="Cell金额提成金额" width="160" align="center">
            <template slot-scope="scope">
              <span>{{ formatMoney(scope.row.CellCommissionAmount) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="TotalCommission" label="提成合计" width="120" align="center">
            <template slot-scope="scope">
              <span>{{ formatMoney(scope.row.TotalCommission) }}</span>
            </template>
          </el-table-column>
        </el-table-column>

        <!-- 工资信息 -->
        <el-table-column label="工资信息" align="center">
          <el-table-column prop="BaseSalary" label="底薪" width="120" align="center">
            <template slot-scope="scope">
              <span>{{ formatMoney(scope.row.BaseSalary) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="WorkingDays" label="在店天数" width="100" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.WorkingDays || '0' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="LeaveDays" label="请假天数" width="100" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.LeaveDays || '0' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="CalculatedGrossSalary" label="核算应发工资" width="140" align="center">
            <template slot-scope="scope">
              <span>{{ formatMoney(scope.row.CalculatedGrossSalary) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="FinalGrossSalary" label="最终应发工资" width="140" align="center">
            <template slot-scope="scope">
              <span>{{ formatMoney(scope.row.FinalGrossSalary) }}</span>
            </template>
          </el-table-column>
        </el-table-column>

        <!-- 补贴信息 -->
        <el-table-column label="补贴信息" align="center">
          <el-table-column prop="MonthlyTrainingSubsidy" label="当月培训补贴" width="140" align="center">
            <template slot-scope="scope">
              <span>{{ formatMoney(scope.row.MonthlyTrainingSubsidy) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="MonthlyTransportSubsidy" label="当月交通补贴" width="140" align="center">
            <template slot-scope="scope">
              <span>{{ formatMoney(scope.row.MonthlyTransportSubsidy) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="LastMonthTrainingSubsidy" label="上月培训补贴" width="140" align="center">
            <template slot-scope="scope">
              <span>{{ formatMoney(scope.row.LastMonthTrainingSubsidy) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="LastMonthTransportSubsidy" label="上月交通补贴" width="140" align="center">
            <template slot-scope="scope">
              <span>{{ formatMoney(scope.row.LastMonthTransportSubsidy) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="TotalSubsidy" label="补贴合计" width="120" align="center">
            <template slot-scope="scope">
              <span>{{ formatMoney(scope.row.TotalSubsidy) }}</span>
            </template>
          </el-table-column>
        </el-table-column>

        <!-- 扣款信息 -->
        <el-table-column label="扣款信息" align="center">
          <el-table-column prop="MissingCard" label="缺卡扣款" width="120" align="center">
            <template slot-scope="scope">
              <span>{{ formatMoney(scope.row.MissingCard) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="LateArrival" label="迟到扣款" width="120" align="center">
            <template slot-scope="scope">
              <span>{{ formatMoney(scope.row.LateArrival) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="LeaveDeduction" label="请假扣款" width="120" align="center">
            <template slot-scope="scope">
              <span>{{ formatMoney(scope.row.LeaveDeduction) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="SocialInsuranceDeduction" label="扣社保" width="120" align="center">
            <template slot-scope="scope">
              <span>{{ formatMoney(scope.row.SocialInsuranceDeduction) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="RewardDeduction" label="扣除奖励" width="120" align="center">
            <template slot-scope="scope">
              <span>{{ formatMoney(scope.row.RewardDeduction) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="AccommodationDeduction" label="扣住宿费" width="120" align="center">
            <template slot-scope="scope">
              <span>{{ formatMoney(scope.row.AccommodationDeduction) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="StudyPeriodDeduction" label="扣学习期费用" width="140" align="center">
            <template slot-scope="scope">
              <span>{{ formatMoney(scope.row.StudyPeriodDeduction) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="WorkClothesDeduction" label="扣工作服费用" width="140" align="center">
            <template slot-scope="scope">
              <span>{{ formatMoney(scope.row.WorkClothesDeduction) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="TotalDeduction" label="扣款合计" width="120" align="center">
            <template slot-scope="scope">
              <span>{{ formatMoney(scope.row.TotalDeduction) }}</span>
            </template>
          </el-table-column>
        </el-table-column>

        <!-- 其他信息 -->
        <el-table-column label="其他信息" align="center">
          <el-table-column prop="Bonus" label="发奖金" width="100" align="center">
            <template slot-scope="scope">
              <span>{{ formatMoney(scope.row.Bonus) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="ReturnPhoneDeposit" label="退手机押金" width="120" align="center">
            <template slot-scope="scope">
              <span>{{ formatMoney(scope.row.ReturnPhoneDeposit) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="ReturnAccommodationDeposit" label="退住宿押金" width="120" align="center">
            <template slot-scope="scope">
              <span>{{ formatMoney(scope.row.ReturnAccommodationDeposit) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="LastMonthSupplement" label="补发上月" width="120" align="center">
            <template slot-scope="scope">
              <span>{{ formatMoney(scope.row.LastMonthSupplement) }}</span>
            </template>
          </el-table-column>
        </el-table-column>

        <!-- 支付信息 -->
        <el-table-column label="支付信息" align="center">
          <el-table-column prop="ActualSalary" label="实发工资" width="120" align="center">
            <template slot-scope="scope">
              <span>{{ formatMoney(scope.row.ActualSalary) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="MonthlyPaymentStatus" label="当月是否发放" width="140" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.MonthlyPaymentStatus || '无' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="PaidAmount" label="支付金额" width="120" align="center">
            <template slot-scope="scope">
              <span>{{ formatMoney(scope.row.PaidAmount) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="PendingAmount" label="待支付金额" width="120" align="center">
            <template slot-scope="scope">
              <span>{{ formatMoney(scope.row.PendingAmount) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="MonthlyTotalPayment" label="当月支付总额" width="140" align="center">
            <template slot-scope="scope">
              <span>{{ formatMoney(scope.row.MonthlyTotalPayment) }}</span>
            </template>
          </el-table-column>
        </el-table-column>

        <!-- 锁定状态列 -->
        <el-table-column prop="IsLocked" label="锁定状态" width="100" align="center" fixed="right">
          <template slot-scope="scope">
            <el-tag :type="scope.row.IsLocked === 1 ? 'danger' : 'success'" size="mini">
              {{ scope.row.IsLocked === 1 ? '已锁定' : '未锁定' }}
            </el-tag>
          </template>
        </el-table-column>
        <!-- 操作列 -->
        <el-table-column label="操作" width="350" align="center" fixed="right">
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-view"
              @click="showDetail(scope.row)"
            >
              详情
            </el-button>
            <el-button
              type="info"
              size="mini"
              icon="el-icon-document"
              @click="showStoreDetail(scope.row)"
              v-if="scope.row.StoreDetail"
            >
              门店明细
            </el-button>
            <el-button
              v-if="scope.row.IsLocked === 1"
              type="success"
              size="mini"
              icon="el-icon-unlock"
              @click="handleUnlock(scope.row)"
              :loading="lockLoading"
            >
              解锁
            </el-button>
            <el-button
              v-else
              type="warning"
              size="mini"
              icon="el-icon-lock"
              @click="handleLock(scope.row)"
              :loading="lockLoading"
            >
              锁定
            </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>
      <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-general-manager-detail-dialog
      :visible="detailVisible"
      :detail-data="currentDetailData"
      @close="handleDetailClose"
    />

    <!-- 门店明细弹窗 -->
    <el-dialog
      title="门店明细"
      :visible="storeDetailVisible"
      width="1400px"
      @close="handleStoreDetailClose"
    >
      <el-table :data="storeDetailList" border stripe max-height="500">
        <el-table-column prop="StoreName" label="门店名称" width="150" align="center" fixed="left" />
        <el-table-column label="溯源金额信息" align="center">
            <el-table-column prop="TraceabilityBillingAmount" label="溯源开单金额"  align="center">
                <template slot-scope="scope">
                    <span>{{ formatMoney(scope.row.TraceabilityBillingAmount) }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="TraceabilityRefundAmount" label="溯源退卡金额" align="center">
                <template slot-scope="scope">
                    <span>{{ formatMoney(scope.row.TraceabilityRefundAmount) }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="TraceabilityAmount" label="溯源金额"  align="center">
                <template slot-scope="scope">
                <span>{{ formatMoney(scope.row.TraceabilityAmount) }}</span>
                </template>
            </el-table-column>
        </el-table-column>
        <el-table-column label="Cell金额信息" align="center">
          <el-table-column prop="CellBillingAmount" label="Cell开单金额"  align="center">
            <template slot-scope="scope">
              <span>{{ formatMoney(scope.row.CellBillingAmount) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="CellRefundAmount" label="Cell退卡金额" align="center">
            <template slot-scope="scope">
              <span>{{ formatMoney(scope.row.CellRefundAmount) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="CellAmount" label="Cell金额" align="center">
            <template slot-scope="scope">
              <span>{{ formatMoney(scope.row.CellAmount) }}</span>
            </template>
          </el-table-column>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleStoreDetailClose">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 导入弹窗 -->
    <el-dialog
      title="导入科技部总经理工资数据"
      :visible="importDialogVisible"
      width="500px"
      :close-on-click-modal="false"
      @close="handleImportDialogClose"
    >
      <el-upload
        ref="upload"
        action=""
        :auto-upload="false"
        :on-change="handleFileChange"
        :file-list="fileList"
        :limit="1"
        accept=".xlsx,.xls"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">只能上传.xlsx/.xls文件，且不超过10MB</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleImportDialogClose">取消</el-button>
        <el-button 
          type="primary" 
          @click="handleImportConfirm"
          :loading="importLoading"
          :disabled="!importFile"
        >
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getTechGeneralManagerSalaryList, calculateTechGeneralManagerSalary, lockTechGeneralManagerSalary, importTechGeneralManagerSalaryFromExcel } from '@/api/extend/techGeneralManagerSalary'
import TechGeneralManagerDetailDialog from './tech-general-manager-detail-dialog.vue'

export default {
  name: 'TechGeneralManagerSalary',
  components: {
    TechGeneralManagerDetailDialog
  },
  data() {
    // 获取当前年月
    const getCurrentYear = () => {
      return new Date().getFullYear().toString()
    }
    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,
      importLoading: false,
      lockLoading: false,
      list: [],
      total: 0,
      calculateDialogVisible: false,
      calculateMonth: getCurrentMonth(),
      detailVisible: false,
      currentDetailData: null,
      storeDetailVisible: false,
      storeDetailList: [],
      importDialogVisible: false,
      importFile: null,
      fileList: [],
      selectedRows: [],
      queryParams: {
        currentPage: 1,
        pageSize: 300, // 写死为300
        year: getCurrentYear(),
        month: getCurrentMonth(), // yyyyMM 格式
        position: '',
        keyword: ''
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 获取列表数据
    async getList() {
      this.loading = true
      try {
        // 处理年月：从month选择器中提取年份和月份
        let year = ''
        let month = ''
        
        if (this.queryParams.month && this.queryParams.month.length === 6) {
          // yyyyMM 格式，如 202512
          year = this.queryParams.month.substring(0, 4)
          month = this.queryParams.month.substring(4, 6)
        } else if (this.queryParams.year && this.queryParams.month) {
          // 分别选择年份和月份
          year = this.queryParams.year
          month = this.queryParams.month.length === 6 
            ? this.queryParams.month.substring(4, 6) 
            : this.queryParams.month
        } else {
          // 使用默认值（当前年月）
          const now = new Date()
          year = now.getFullYear().toString()
          month = String(now.getMonth() + 1).padStart(2, '0')
        }

        const params = {
          currentPage: this.queryParams.currentPage,
          pageSize: this.queryParams.pageSize,
          Year: parseInt(year),
          Month: parseInt(month),
          Position: this.queryParams.position || undefined,
          Keyword: this.queryParams.keyword || ''
        }

        const response = await getTechGeneralManagerSalaryList(params)

        if (response.code === 200) {
          this.list = response.data.list || []
          this.total = (response.data.pagination && response.data.pagination.total) || 0
          // 刷新后清除选择
          this.handleClearSelection()
        } else {
          this.$message.error(response.msg || '获取数据失败')
        }
      } catch (error) {
        console.error('获取科技部总经理工资列表失败:', error)
        this.$message.error('获取数据失败' + error)
      } finally {
        this.loading = false
      }
    },

    // 搜索
    handleQuery() {
      this.queryParams.currentPage = 1
      this.getList()
    },

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

      this.queryParams = {
        currentPage: 1,
        pageSize: 300, // 写死为300
        year: getCurrentYear(),
        month: getCurrentMonth(),
        position: '',
        keyword: ''
      }
      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.calculateDialogVisible = true
    },

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

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

      // 从calculateMonth中提取年份和月份（yyyyMM格式，如202512）
      let year = 0
      let month = 0
      if (this.calculateMonth && this.calculateMonth.length === 6) {
        year = parseInt(this.calculateMonth.substring(0, 4))
        month = parseInt(this.calculateMonth.substring(4, 6))
      } else {
        this.$message.warning('月份格式不正确')
        return
      }

      this.calculateLoading = true
      try {
        const response = await calculateTechGeneralManagerSalary(year, month)
        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
      }
    },

    // 显示门店明细
    showStoreDetail(row) {
      try {
        if (row.StoreDetail) {
          const detail = JSON.parse(row.StoreDetail)
          // 确保是数组格式
          this.storeDetailList = Array.isArray(detail) ? detail : []
          this.storeDetailVisible = true
        } else {
          this.$message.info('暂无门店明细')
        }
      } catch (error) {
        console.error('解析门店明细失败:', error)
        this.$message.error('门店明细格式错误')
      }
    },

    // 关闭门店明细弹窗
    handleStoreDetailClose() {
      this.storeDetailVisible = false
      this.storeDetailList = []
    },

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

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

    // 显示导入弹窗
    showImportDialog() {
      this.importDialogVisible = true
      this.importFile = null
      this.fileList = []
    },

    // 关闭导入弹窗
    handleImportDialogClose() {
      this.importDialogVisible = false
      this.importFile = null
      this.fileList = []
      if (this.$refs.upload) {
        this.$refs.upload.clearFiles()
      }
    },

    // 文件选择变化
    handleFileChange(file, fileList) {
      this.importFile = file.raw
      this.fileList = fileList
    },

    // 确认导入
    async handleImportConfirm() {
      if (!this.importFile) {
        this.$message.warning('请选择要导入的Excel文件')
        return
      }

      // 检查文件大小（10MB）
      const maxSize = 10 * 1024 * 1024
      if (this.importFile.size > maxSize) {
        this.$message.warning('文件大小不能超过10MB')
        return
      }

      // 检查文件格式
      const allowedExtensions = ['.xlsx', '.xls']
      const fileName = this.importFile.name.toLowerCase()
      const isValidFormat = allowedExtensions.some(ext => fileName.endsWith(ext))
      if (!isValidFormat) {
        this.$message.warning('只支持.xlsx和.xls格式的Excel文件')
        return
      }

      this.importLoading = true
      try {
        const response = await importTechGeneralManagerSalaryFromExcel(this.importFile)
        if (response.code === 200) {
          const result = response.data || response
          let message = '导入成功'
          if (result.successCount !== undefined) {
            message = `导入成功：新增${result.insertCount || 0}条，更新${result.updateCount || 0}条，跳过${result.skippedCount || 0}条`
          }
          this.$message.success(message)
          this.handleImportDialogClose()
          this.getList()
        } else {
          this.$message.error(response.msg || '导入失败')
        }
      } catch (error) {
        console.error('导入失败:', error)
        this.$message.error(error.message || '导入失败，请重试')
      } finally {
        this.importLoading = false
      }
    },

    // 锁定工资
    async handleLock(row) {
      await this.$confirm('确定要锁定该工资记录吗？锁定后将无法修改。', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        this.lockLoading = true
        try {
          const response = await lockTechGeneralManagerSalary([row.Id], true)
          if (response.code === 200) {
            this.$message.success('锁定成功')
            this.getList()
          } else {
            this.$message.error(response.msg || '锁定失败')
          }
        } catch (error) {
          console.error('锁定失败:', error)
          this.$message.error(error.message || '锁定失败，请重试')
        } finally {
          this.lockLoading = false
        }
      }).catch(() => {
        // 用户取消
      })
    },

    // 解锁工资
    async handleUnlock(row) {
      await this.$confirm('确定要解锁该工资记录吗？解锁后可以修改。', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        this.lockLoading = true
        try {
          const response = await lockTechGeneralManagerSalary([row.Id], false)
          if (response.code === 200) {
            this.$message.success('解锁成功')
            this.getList()
          } else {
            this.$message.error(response.msg || '解锁失败')
          }
        } catch (error) {
          console.error('解锁失败:', error)
          this.$message.error(error.message || '解锁失败，请重试')
        } finally {
          this.lockLoading = false
        }
      }).catch(() => {
        // 用户取消
      })
    },

    // 选择变化
    handleSelectionChange(selection) {
      this.selectedRows = selection
    },

    // 清除选择
    handleClearSelection() {
      // NCC-table 组件内部 el-table 的 ref 是 NCCTable
      if (this.$refs.table && this.$refs.table.$refs && this.$refs.table.$refs.NCCTable) {
        this.$refs.table.$refs.NCCTable.clearSelection()
      }
      this.selectedRows = []
    },

    // 批量锁定
    async handleBatchLock() {
      if (!this.selectedRows || this.selectedRows.length === 0) {
        this.$message.warning('请先选择要锁定的记录')
        return
      }

      // 过滤出未锁定的记录
      const unlockedRows = this.selectedRows.filter(row => row.IsLocked !== 1)
      if (unlockedRows.length === 0) {
        this.$message.warning('所选记录已全部锁定')
        return
      }

      await this.$confirm(`确定要锁定选中的 ${unlockedRows.length} 条记录吗？锁定后将无法修改。`, '批量锁定', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        this.lockLoading = true
        try {
          const ids = unlockedRows.map(row => row.Id)
          const response = await lockTechGeneralManagerSalary(ids, true)
          if (response.code === 200) {
            this.$message.success(`锁定成功：${unlockedRows.length}条`)
            this.handleClearSelection()
            this.getList()
          } else {
            this.$message.error(response.msg || '批量锁定失败')
          }
        } catch (error) {
          console.error('批量锁定失败:', error)
          this.$message.error(error.message || '批量锁定失败，请重试')
        } finally {
          this.lockLoading = false
        }
      }).catch(() => {
        // 用户取消
      })
    },

    // 批量解锁
    async handleBatchUnlock() {
      if (!this.selectedRows || this.selectedRows.length === 0) {
        this.$message.warning('请先选择要解锁的记录')
        return
      }

      // 过滤出已锁定的记录
      const lockedRows = this.selectedRows.filter(row => row.IsLocked === 1)
      if (lockedRows.length === 0) {
        this.$message.warning('所选记录已全部解锁')
        return
      }

      await this.$confirm(`确定要解锁选中的 ${lockedRows.length} 条记录吗？解锁后可以修改。`, '批量解锁', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        this.lockLoading = true
        try {
          const ids = lockedRows.map(row => row.Id)
          const response = await lockTechGeneralManagerSalary(ids, false)
          if (response.code === 200) {
            this.$message.success(`解锁成功：${lockedRows.length}条`)
            this.handleClearSelection()
            this.getList()
          } else {
            this.$message.error(response.msg || '批量解锁失败')
          }
        } catch (error) {
          console.error('批量解锁失败:', error)
          this.$message.error(error.message || '批量解锁失败，请重试')
        } finally {
          this.lockLoading = false
        }
      }).catch(() => {
        // 用户取消
      })
    },

    // 导出功能
    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 = [
          'ID',
          '员工姓名',
          '员工账号',
          '核算岗位',
          '统计月份',
          '是否离职',
          '溯源金额',
          'Cell金额',
          '底薪',
          '溯源金额提成比例',
          '溯源金额提成金额',
          'Cell金额提成比例',
          'Cell金额提成金额',
          '提成合计',
          '在店天数',
          '请假天数',
          '核算应发工资',
          '最终应发工资',
          '当月培训补贴',
          '当月交通补贴',
          '上月培训补贴',
          '上月交通补贴',
          '补贴合计',
          '缺卡扣款',
          '迟到扣款',
          '请假扣款',
          '扣社保',
          '扣除奖励',
          '扣住宿费',
          '扣学习期费用',
          '扣工作服费用',
          '扣款合计',
          '发奖金',
          '退手机押金',
          '退住宿押金',
          '补发上月',
          '实发工资',
          '当月是否发放',
          '支付金额',
          '待支付金额',
          '当月支付总额',
          '是否锁定'
        ]

        // 构建数据行
        const dataRows = this.list.map(item => [
          item.Id || '无',
          item.EmployeeName || '无',
          item.EmployeeAccount || '无',
          item.Position || '无',
          item.StatisticsMonth || '无',
          item.IsTerminated === 1 ? '已离职' : '在职',
          this.formatMoney(item.TraceabilityAmount),
          this.formatMoney(item.CellAmount),
          this.formatMoney(item.BaseSalary),
          this.formatPercent(item.TraceabilityCommissionRate),
          this.formatMoney(item.TraceabilityCommissionAmount),
          this.formatPercent(item.CellCommissionRate),
          this.formatMoney(item.CellCommissionAmount),
          this.formatMoney(item.TotalCommission),
          item.WorkingDays || '0',
          item.LeaveDays || '0',
          this.formatMoney(item.CalculatedGrossSalary),
          this.formatMoney(item.FinalGrossSalary),
          this.formatMoney(item.MonthlyTrainingSubsidy),
          this.formatMoney(item.MonthlyTransportSubsidy),
          this.formatMoney(item.LastMonthTrainingSubsidy),
          this.formatMoney(item.LastMonthTransportSubsidy),
          this.formatMoney(item.TotalSubsidy),
          this.formatMoney(item.MissingCard),
          this.formatMoney(item.LateArrival),
          this.formatMoney(item.LeaveDeduction),
          this.formatMoney(item.SocialInsuranceDeduction),
          this.formatMoney(item.RewardDeduction),
          this.formatMoney(item.AccommodationDeduction),
          this.formatMoney(item.StudyPeriodDeduction),
          this.formatMoney(item.WorkClothesDeduction),
          this.formatMoney(item.TotalDeduction),
          this.formatMoney(item.Bonus),
          this.formatMoney(item.ReturnPhoneDeposit),
          this.formatMoney(item.ReturnAccommodationDeposit),
          this.formatMoney(item.LastMonthSupplement),
          this.formatMoney(item.ActualSalary),
          item.MonthlyPaymentStatus || '无',
          this.formatMoney(item.PaidAmount),
          this.formatMoney(item.PendingAmount),
          this.formatMoney(item.MonthlyTotalPayment),
          item.IsLocked === 1 ? '已锁定' : '未锁定'
        ])

        // 合并表头和数据
        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)
    },

    // 格式化百分比
    formatPercent(value) {
      if (value === null || value === undefined || value === '') {
        return '0.00%'
      }
      return (Number(value) * 100).toFixed(2) + '%'
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 16px;
  background: linear-gradient(135deg, #f5f7fa 0%, #e8ecf1 50%, #f0f4f8 100%);
  min-height: 100vh;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
  padding: 18px 24px;
  background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08), 0 2px 8px rgba(0, 0, 0, 0.04);
  border: 1px solid rgba(144, 147, 153, 0.2);
  position: relative;
  overflow: hidden;

  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 3px;
    background: linear-gradient(90deg, #606266 0%, #909399 50%, #606266 100%);
  }

  .header-left {
    h2 {
      margin: 0 0 8px 0;
      color: #303133;
      font-size: 22px;
      font-weight: 600;
      background: linear-gradient(135deg, #303133 0%, #606266 100%);
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
      background-clip: text;
    }

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

  .header-right {
    display: flex;
    gap: 10px;
    flex-wrap: wrap;

    .el-button {
      border-radius: 8px;
      padding: 10px 18px;
      font-weight: 500;
      transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
      }

      &.el-button--primary {
        background: linear-gradient(135deg, #606266 0%, #909399 100%);
        border: none;

        &:hover {
          background: linear-gradient(135deg, #909399 0%, #606266 100%);
        }
      }

      &.el-button--success {
        background: linear-gradient(135deg, #67C23A 0%, #85ce61 100%);
        border: none;

        &:hover {
          background: linear-gradient(135deg, #85ce61 0%, #67C23A 100%);
        }
      }

      &.el-button--warning {
        background: linear-gradient(135deg, #E6A23C 0%, #f0b45a 100%);
        border: none;

        &:hover {
          background: linear-gradient(135deg, #f0b45a 0%, #E6A23C 100%);
        }
      }

      &.el-button--info {
        background: linear-gradient(135deg, #909399 0%, #a6a9ad 100%);
        border: none;

        &:hover {
          background: linear-gradient(135deg, #a6a9ad 0%, #909399 100%);
        }
      }
    }
  }
}

.search-container {
  margin-bottom: 16px;
  padding: 18px 24px;
  background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08), 0 2px 8px rgba(0, 0, 0, 0.04);
  border: 1px solid rgba(144, 147, 153, 0.2);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);

  &:hover {
    box-shadow: 0 6px 20px rgba(0, 0, 0, 0.1), 0 4px 12px rgba(0, 0, 0, 0.06);
  }

  &::v-deep .el-form {
    .el-form-item {
      margin-bottom: 16px;
    }

    .el-button {
      border-radius: 8px;
      padding: 10px 20px;
      font-weight: 500;
      transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
      }

      &.el-button--primary {
        background: linear-gradient(135deg, #606266 0%, #909399 100%);
        border: none;

        &:hover {
          background: linear-gradient(135deg, #909399 0%, #606266 100%);
        }
      }
    }

    .el-input__inner,
    .el-select .el-input__inner {
      border-radius: 8px;
      border: 1px solid rgba(144, 147, 153, 0.3);
      transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);

      &:focus {
        border-color: #909399;
        box-shadow: 0 0 0 2px rgba(144, 147, 153, 0.15);
      }
    }
  }
}

.batch-action-container {
  margin-top: 16px;
  padding: 14px 18px;
  background: linear-gradient(135deg, rgba(144, 147, 153, 0.08) 0%, rgba(144, 147, 153, 0.05) 100%);
  border-radius: 10px;
  border: 1px solid rgba(144, 147, 153, 0.3);
  display: flex;
  align-items: center;
  gap: 12px;
  box-shadow: 0 2px 8px rgba(144, 147, 153, 0.1);

  .selected-count {
    color: #606266;
    font-weight: 600;
    margin-right: 8px;
    font-size: 14px;
  }

  .el-button {
    border-radius: 8px;
    font-weight: 500;
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.08);

    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 10px rgba(0, 0, 0, 0.12);
    }
  }
}

.table-container {
  margin-bottom: 20px;
  padding: 18px 24px;
  background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08), 0 2px 8px rgba(0, 0, 0, 0.04);
  border: 1px solid rgba(144, 147, 153, 0.2);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  overflow: hidden;
  z-index: 1;

  &:hover {
    box-shadow: 0 6px 20px rgba(0, 0, 0, 0.1), 0 4px 12px rgba(0, 0, 0, 0.06);
  }

  &::v-deep .el-table {
    background-color: #ffffff;

    .el-table__body-wrapper {
      background-color: #ffffff;
    }
  }
}

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

  .employee-icon {
    color: #606266;
    font-size: 16px;
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  }

  &:hover .employee-icon {
    transform: scale(1.1) rotate(5deg);
  }
}

// 表格样式优化
::v-deep .el-table {
  border-radius: 8px;
  overflow: hidden;
  border: 1px solid rgba(144, 147, 153, 0.2);

  // 确保多选框列可以点击 - 全局设置，最高优先级
  .el-table__column--selection {
    z-index: 1000 !important;
    pointer-events: auto !important;
    position: relative;
  }

  .el-checkbox {
    z-index: 1001 !important;
    pointer-events: auto !important;
    position: relative;
    cursor: pointer;
  }

  .el-checkbox__input {
    z-index: 1001 !important;
    pointer-events: auto !important;
    cursor: pointer;
  }

  .el-checkbox__inner {
    z-index: 1001 !important;
    pointer-events: auto !important;
    cursor: pointer;
  }

  td.el-table__cell--selection,
  th.el-table__cell--selection {
    z-index: 1000 !important;
    pointer-events: auto !important;
    position: relative;
    background-color: #ffffff !important;
    cursor: pointer;

    .cell {
      pointer-events: auto !important;
      z-index: 1001 !important;
      position: relative;
    }
  }

  .el-table__header-wrapper {
    th {
      background: linear-gradient(135deg, rgba(144, 147, 153, 0.08) 0%, rgba(144, 147, 153, 0.05) 100%);
      color: #303133;
      font-weight: 600;
      border-bottom: 2px solid rgba(144, 147, 153, 0.2);
      padding: 14px 0 !important;
      height: auto !important;
      line-height: normal !important;
      box-sizing: border-box;
    }
  }

  .el-table__body-wrapper {
    background-color: #ffffff;
    z-index: 1;

    .el-table__row {
      transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
      background-color: #ffffff;

      &:hover {
        background: linear-gradient(90deg, rgba(144, 147, 153, 0.05) 0%, rgba(144, 147, 153, 0.02) 100%) !important;
        transform: translateX(2px);
      }

      td {
        border-bottom: 1px solid rgba(144, 147, 153, 0.15);
        background-color: #ffffff !important;
        padding: 12px 0 !important;
        height: auto !important;
        line-height: normal !important;
        box-sizing: border-box;
      }

      &.el-table__row--striped {
        td {
          background-color: #fafafa !important;
        }

        &:hover td {
          background: linear-gradient(90deg, rgba(144, 147, 153, 0.05) 0%, rgba(144, 147, 153, 0.02) 100%) !important;
        }
      }
    }
  }

  .el-table__header-wrapper {
    background-color: #ffffff;
    z-index: 2;
  }

  // 固定列样式修复
  .el-table__fixed,
  .el-table__fixed-right {
    z-index: 5 !important;
    background-color: #ffffff;
    height: 100% !important;

    // 确保多选框可以点击 - 选择列需要最高的z-index
    .el-table__column--selection {
      z-index: 1000 !important;
      pointer-events: auto !important;
      position: relative;
    }

    // 确保选择列单元格可以点击
    td.el-table__cell--selection,
    th.el-table__cell--selection {
      z-index: 1000 !important;
      pointer-events: auto !important;
      position: relative;
      background-color: #ffffff !important;
      cursor: pointer;

      .cell {
        pointer-events: auto !important;
        z-index: 1001 !important;
        position: relative;
      }
    }

    // 确保多选框本身可以点击
    .el-checkbox {
      z-index: 1001 !important;
      position: relative;
      pointer-events: auto !important;
      cursor: pointer;
    }

    .el-checkbox__input {
      z-index: 1001 !important;
      pointer-events: auto !important;
      cursor: pointer;
    }

    .el-checkbox__inner {
      z-index: 1001 !important;
      pointer-events: auto !important;
      cursor: pointer;
    }

    &::before {
      background: linear-gradient(135deg, rgba(144, 147, 153, 0.08) 0%, rgba(144, 147, 153, 0.05) 100%);
      z-index: 4 !important;
      height: 100% !important;
      pointer-events: none !important;
    }

    .el-table__fixed-header-wrapper {
      height: auto !important;
      background-color: #ffffff;

      th {
        background: linear-gradient(135deg, rgba(144, 147, 153, 0.08) 0%, rgba(144, 147, 153, 0.05) 100%) !important;
        z-index: 6 !important;
        padding: 14px 0 !important;
        height: auto !important;
        line-height: normal !important;

        // 选择列header需要最高z-index
        &.el-table__cell--selection {
          z-index: 1000 !important;
          pointer-events: auto !important;
        }
      }
    }

    .el-table__fixed-body-wrapper {
      background-color: #ffffff;
      height: auto !important;
      max-height: 100% !important;
      overflow-y: auto !important;

      td {
        background-color: #ffffff !important;
        z-index: 6 !important;
        padding: 12px 0 !important;
        height: auto !important;
        line-height: normal !important;

        // 选择列cell需要最高z-index
        &.el-table__cell--selection {
          z-index: 1000 !important;
          pointer-events: auto !important;
        }
      }

      .el-table__row {
        height: auto !important;

        &.el-table__row--striped {
          td {
            background-color: #fafafa !important;
          }
        }
      }
    }

    th {
      background: linear-gradient(135deg, rgba(144, 147, 153, 0.08) 0%, rgba(144, 147, 153, 0.05) 100%) !important;
      z-index: 6 !important;
      padding: 14px 0 !important;
      height: auto !important;
      line-height: normal !important;

      // 选择列header需要最高z-index
      &.el-table__cell--selection {
        z-index: 1000 !important;
        pointer-events: auto !important;
      }
    }

    td {
      background-color: #ffffff !important;
      z-index: 6 !important;
      padding: 12px 0 !important;
      height: auto !important;
      line-height: normal !important;

      // 选择列cell需要最高z-index
      &.el-table__cell--selection {
        z-index: 1000 !important;
        pointer-events: auto !important;
      }
    }
  }

  // 固定列补丁
  .el-table__fixed-right-patch {
    background-color: #ffffff;
    z-index: 4 !important;
    height: 100% !important;
    pointer-events: none !important;
  }

  // 确保固定列和主表格的header高度一致
  .el-table__header-wrapper th,
  .el-table__fixed-header-wrapper th,
  .el-table__fixed-right-header-wrapper th {
    padding: 14px 0 !important;
    height: auto !important;
    line-height: normal !important;
  }

  // 确保固定列和主表格的body行高一致
  .el-table__body-wrapper td,
  .el-table__fixed-body-wrapper td,
  .el-table__fixed-right-body-wrapper td {
    padding: 12px 0 !important;
    height: auto !important;
    line-height: normal !important;
  }
}
</style>

