<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="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>

    <!-- 数据表格 -->
    <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="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="BillingAmount" label="开单金额" width="120" align="center">
            <template slot-scope="scope">
              <span>{{ formatMoney(scope.row.BillingAmount) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="RefundAmount" label="退卡金额" width="120" align="center">
            <template slot-scope="scope">
              <span>{{ formatMoney(scope.row.RefundAmount) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="TotalPerformance" label="总业绩" width="120" align="center">
            <template slot-scope="scope">
              <span>{{ formatMoney(scope.row.TotalPerformance) }}</span>
            </template>
          </el-table-column>
        </el-table-column>

        <!-- 提成信息 -->
        <el-table-column label="提成信息" align="center">
          <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="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="StoreDetail" label="门店明细" width="200" align="center" fixed="right">
          <template slot-scope="scope">
            <el-button 
              type="text" 
              size="mini"
              @click="showStoreDetail(scope.row)"
              v-if="scope.row.StoreDetail"
            >
              查看明细
            </el-button>
            <span v-else>无</span>
          </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>

    <!-- 门店明细弹窗 -->
    <el-dialog
      title="门店明细"
      :visible="storeDetailVisible"
      width="1000px"
      @close="handleStoreDetailClose"
    >
      <el-table :data="storeDetailList" border stripe max-height="500">
        <el-table-column prop="StoreName" label="门店名称" width="200" align="center" fixed="left" />
        <el-table-column prop="BillingAmount" label="开单金额"  align="center">
          <template slot-scope="scope">
            <span>{{ formatMoney(scope.row.BillingAmount) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="RefundAmount" label="退卡金额"  align="center">
          <template slot-scope="scope">
            <span>{{ formatMoney(scope.row.RefundAmount) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="TotalPerformance" label="总业绩"  align="center">
          <template slot-scope="scope">
            <span>{{ formatMoney(scope.row.TotalPerformance) }}</span>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleStoreDetailClose">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getMajorProjectDirectorSalaryList, calculateMajorProjectDirectorSalary } from '@/api/extend/majorProjectDirectorSalary'

export default {
  name: 'MajorProjectDirectorSalary',
  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,
      list: [],
      total: 0,
      calculateDialogVisible: false,
      calculateYear: getCurrentYear(),
      calculateMonth: getCurrentMonth(),
      storeDetailVisible: false,
      storeDetailList: [],
      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 getMajorProjectDirectorSalaryList(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(),
        position: '',
        keyword: ''
      }
      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 = parseInt(this.calculateYear)
      const month = this.calculateMonth.length === 6 
        ? parseInt(this.calculateMonth.substring(4, 6)) 
        : parseInt(this.calculateMonth)

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

    // 格式化金额
    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: 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);
}

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

  .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>

