<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"
          :disabled="!list || list.length === 0"
        >
          导出
        </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="storeId">
          <el-select 
            v-model="queryParams.storeId" 
            placeholder="请选择门店"
            clearable
            filterable
            style="width: 200px"
          >
            <el-option
              v-for="store in storeList"
              :key="store.id"
              :label="store.fullName"
              :value="store.id"
            />
          </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 - 480px)"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
      >
        <!-- 基本信息 -->
        <el-table-column prop="StoreName" label="门店名称" width="140" align="center" fixed="left">
          <template slot-scope="scope">
            <div class="store-name">
              <i class="el-icon-shop store-icon"></i>
              <span>{{ scope.row.StoreName || '无' }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="EmployeeName" label="员工姓名" width="130" 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="100" align="center" fixed="left">
          <template slot-scope="scope">
            <span>{{ scope.row.Position || '无' }}</span>
          </template>
        </el-table-column>

        <!-- 业绩信息 -->
        <el-table-column label="业绩信息" align="center">
          <el-table-column prop="StoreBillingPerformance" label="门店开单业绩" width="140" align="center">
            <template slot-scope="scope">
              <span>{{ formatMoney(scope.row.StoreBillingPerformance) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="StoreRefundPerformance" label="门店退卡业绩" width="140" align="center">
            <template slot-scope="scope">
              <span>{{ formatMoney(scope.row.StoreRefundPerformance) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="StoreTotalPerformance" label="门店总业绩" width="140" align="center">
            <template slot-scope="scope">
              <span>{{ formatMoney(scope.row.StoreTotalPerformance) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="StoreLifeline" label="门店生命线" width="120" align="center">
            <template slot-scope="scope">
              <span>{{ formatMoney(scope.row.StoreLifeline) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="PerformanceCompletionRate" label="业绩完成率" width="120" align="center">
            <template slot-scope="scope">
              <span>{{ formatPercent(scope.row.PerformanceCompletionRate) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="PerformanceReached" label="业绩是否达标" width="120" align="center">
            <template slot-scope="scope">
              <el-tag :type="scope.row.PerformanceReached === '是' ? 'success' : 'danger'" size="mini">
                {{ scope.row.PerformanceReached || '否' }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table-column>

        <!-- 考核信息 -->
        <el-table-column label="考核信息" align="center">
          <el-table-column prop="HeadCount" label="进店消耗人数" width="140" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.HeadCount || '0' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="TargetHeadCount" label="目标人头数" width="120" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.TargetHeadCount || '0' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="HeadCountReached" label="人头是否达标" width="120" align="center">
            <template slot-scope="scope">
              <el-tag :type="scope.row.HeadCountReached === '是' ? 'success' : 'danger'" size="mini">
                {{ scope.row.HeadCountReached || '否' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="StoreConsume" label="门店消耗" width="120" align="center">
            <template slot-scope="scope">
              <span>{{ formatMoney(scope.row.StoreConsume) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="TargetConsume" label="目标消耗" width="120" align="center">
            <template slot-scope="scope">
              <span>{{ formatMoney(scope.row.TargetConsume) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="ConsumeReached" label="消耗是否达标" width="120" align="center">
            <template slot-scope="scope">
              <el-tag :type="scope.row.ConsumeReached === '是' ? 'success' : 'danger'" size="mini">
                {{ scope.row.ConsumeReached || '否' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="UnreachedIndicatorCount" label="未达标指标数" width="140" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.UnreachedIndicatorCount || '0' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="AssessmentDeduction" label="考核扣款" width="120" align="center">
            <template slot-scope="scope">
              <span>{{ formatMoney(scope.row.AssessmentDeduction) }}</span>
            </template>
          </el-table-column>
        </el-table-column>

        <!-- 提成信息 -->
        <el-table-column label="提成信息" align="center">
          <el-table-column prop="GrossProfit" label="毛利" width="120" align="center">
            <template slot-scope="scope">
              <span>{{ formatMoney(scope.row.GrossProfit) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="CommissionRate" label="提成比例" width="120" align="center">
            <template slot-scope="scope">
              <span>{{ formatPercent(scope.row.CommissionRate) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="CommissionAmount" label="提成金额" width="120" align="center">
            <template slot-scope="scope">
              <span>{{ formatMoney(scope.row.CommissionAmount) }}</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="ActualBaseSalary" label="实际底薪" width="120" align="center">
            <template slot-scope="scope">
              <span>{{ formatMoney(scope.row.ActualBaseSalary) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="GrossSalary" label="应发工资" width="120" align="center">
            <template slot-scope="scope">
              <span>{{ formatMoney(scope.row.GrossSalary) }}</span>
            </template>
          </el-table-column>
        </el-table-column>

        <!-- 考勤信息 -->
        <el-table-column label="考勤信息" align="center">
          <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>

        <!-- 补贴信息 -->
        <el-table-column label="补贴信息" align="center">
          <el-table-column prop="TransportationAllowance" label="车补" width="100" align="center">
            <template slot-scope="scope">
              <span>{{ formatMoney(scope.row.TransportationAllowance) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="LessRest" label="少休费" width="100" align="center">
            <template slot-scope="scope">
              <span>{{ formatMoney(scope.row.LessRest) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="FullAttendance" label="全勤奖" width="100" align="center">
            <template slot-scope="scope">
              <span>{{ formatMoney(scope.row.FullAttendance) }}</span>
            </template>
          </el-table-column>
          <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="StoreCategory" label="门店分类" width="100" align="center">
          <template slot-scope="scope">
            <span>{{ getStoreCategoryName(scope.row.StoreCategory) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="IsNewStore" label="是否新店" width="100" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.IsNewStore || '无' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="NewStoreProtectionStage" label="新店保护阶段" width="120" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.NewStoreProtectionStage || '0' }}</span>
          </template>
        </el-table-column>
        <!-- 操作列 -->
        <el-table-column label="操作" width="120" align="left" fixed="right">
          <template slot-scope="scope">
            <el-button 
              type="primary" 
              size="mini" 
              icon="el-icon-view"
              @click="handleViewDetail(scope.row)"
            >
              查看详情
            </el-button>
          </template>
        </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> -->
      </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="calculateYear"
            type="year"
            placeholder="请选择年份"
            format="yyyy"
            value-format="yyyy"
            style="width: 100%"
          />
        </el-form-item>
        <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>

    <!-- 详情弹窗 -->
    <shop-detail-dialog
      :visible.sync="detailDialogVisible"
      :detail-data="currentDetailData"
      @close="handleDetailDialogClose"
    />
  </div>
</template>

<script>
import { getStoreManagerSalaryList, calculateStoreManagerSalary } from '@/api/extend/storeManagerSalary'
import { getStoreSelector } from '@/api/extend/store'
import ShopDetailDialog from './shop-detail-dialog.vue'

export default {
  name: 'StoreManagerSalary',
  components: {
    ShopDetailDialog
  },
  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,
      list: [],
      total: 0,
      storeList: [],
      calculateDialogVisible: false,
      calculateYear: getCurrentYear(),
      calculateMonth: getCurrentMonth(),
      detailDialogVisible: false,
      currentDetailData: null,
      queryParams: {
        currentPage: 1,
        pageSize: 300, // 写死为300
        year: getCurrentYear(),
        month: getCurrentMonth(), // yyyyMM 格式
        storeId: ''
      }
    }
  },
  created() {
    this.getStoreList()
    this.getList()
  },
  methods: {
    // 获取门店列表
    async getStoreList() {
      try {
        const response = await getStoreSelector()
        this.storeList = response.data.list || []
      } catch (error) {
        console.error('获取门店列表失败:', error)
        this.storeList = []
      }
    },

    // 获取列表数据
    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: year,
          Month: month,
          StoreId: this.queryParams.storeId || ''
        }

        const response = await getStoreManagerSalaryList(params)

        if (response.code === 200) {
          this.list = response.data.list || []
          this.total = (response.data.pagination && response.data.pagination.total) || 0
        } 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(),
        storeId: ''
      }
      this.getList()
    },

    // 显示计算工资弹窗
    showCalculateDialog() {
      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.calculateYear = getCurrentYear()
      this.calculateMonth = getCurrentMonth()
      this.calculateDialogVisible = true
    },

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

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

      // 从calculateMonth中提取月份（yyyyMM格式，如202512）
      const year = this.calculateYear
      const month = this.calculateMonth.length === 6 
        ? this.calculateMonth.substring(4, 6) 
        : this.calculateMonth

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

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

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

        // 构建表头
        const headers = [
          '门店名称',
          '员工姓名',
          '岗位',
          '门店开单业绩',
          '门店退卡业绩',
          '门店总业绩',
          '门店生命线',
          '业绩完成率',
          '业绩是否达标',
          '进店消耗人数',
          '目标人头数',
          '人头是否达标',
          '门店消耗',
          '目标消耗',
          '消耗是否达标',
          '未达标指标数',
          '考核扣款',
          '毛利',
          '提成比例',
          '提成金额',
          '底薪',
          '实际底薪',
          '应发工资',
          '在店天数',
          '请假天数',
          '车补',
          '少休费',
          '全勤奖',
          '当月培训补贴',
          '当月交通补贴',
          '上月培训补贴',
          '上月交通补贴',
          '补贴合计',
          '缺卡扣款',
          '迟到扣款',
          '请假扣款',
          '扣社保',
          '扣除奖励',
          '扣住宿费',
          '扣学习期费用',
          '扣工作服费用',
          '扣款合计',
          '发奖金',
          '退手机押金',
          '退住宿押金',
          '补发上月',
          '实发工资',
          '当月是否发放',
          '支付金额',
          '待支付金额',
          '当月支付总额',
          '门店分类',
          '是否新店',
          '新店保护阶段',
          '锁定状态'
        ]

        // 构建数据行
        const dataRows = this.list.map(item => [
          item.StoreName || '无',
          item.EmployeeName || '无',
          item.Position || '无',
          this.formatMoney(item.StoreBillingPerformance),
          this.formatMoney(item.StoreRefundPerformance),
          this.formatMoney(item.StoreTotalPerformance),
          this.formatMoney(item.StoreLifeline),
          this.formatPercent(item.PerformanceCompletionRate),
          item.PerformanceReached || '否',
          item.HeadCount || '0',
          item.TargetHeadCount || '0',
          item.HeadCountReached || '否',
          this.formatMoney(item.StoreConsume),
          this.formatMoney(item.TargetConsume),
          item.ConsumeReached || '否',
          item.UnreachedIndicatorCount || '0',
          this.formatMoney(item.AssessmentDeduction),
          this.formatMoney(item.GrossProfit),
          this.formatPercent(item.CommissionRate),
          this.formatMoney(item.CommissionAmount),
          this.formatMoney(item.BaseSalary),
          this.formatMoney(item.ActualBaseSalary),
          this.formatMoney(item.GrossSalary),
          item.WorkingDays || '0',
          item.LeaveDays || '0',
          this.formatMoney(item.TransportationAllowance),
          this.formatMoney(item.LessRest),
          this.formatMoney(item.FullAttendance),
          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),
          this.getStoreCategoryName(item.StoreCategory),
          item.IsNewStore || '无',
          item.NewStoreProtectionStage || '0',
          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) + '%'
    },

    // 获取门店分类名称
    getStoreCategoryName(category) {
      const categoryMap = {
        1: 'A类',
        2: 'B类',
        3: 'C类'
      }
      return categoryMap[category] || '无'
    },

    // 查看详情
    handleViewDetail(row) {
      this.currentDetailData = row
      this.detailDialogVisible = true
    },

    // 关闭详情弹窗
    handleDetailDialogClose() {
      this.detailDialogVisible = false
      this.currentDetailData = null
    }
  }
}
</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);
}

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

  .store-icon,
  .employee-icon {
    color: #409EFF;
    font-size: 16px;
  }
}

// 表格样式优化
::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>

