<template>
  <el-dialog
    title="大项目部老师工资详情"
    :visible="visible"
    width="1400px"
    :close-on-click-modal="false"
    @close="handleClose"
    class="detail-dialog"
  >
    <div v-if="detailData" class="detail-content">
      <!-- 基本信息 -->
      <div class="detail-section">
        <div class="section-title">
          <i class="el-icon-user"></i>
          <span>基本信息</span>
        </div>
        <div class="section-content">
          <div class="info-row">
            <div class="info-item">
              <span class="label">门店名称：</span>
              <span class="value">{{ detailData.StoreName || '无' }}</span>
            </div>
            <div class="info-item">
              <span class="label">员工姓名：</span>
              <span class="value">{{ detailData.EmployeeName || '无' }}</span>
            </div>
            <div class="info-item">
              <span class="label">岗位：</span>
              <span class="value">{{ detailData.Position || '无' }}</span>
            </div>
            <div class="info-item">
              <span class="label">员工账号：</span>
              <span class="value">{{ detailData.EmployeeAccount || '无' }}</span>
            </div>
            <div class="info-item" v-if="detailData.IsNewStore !== undefined && detailData.IsNewStore !== null">
              <span class="label">是否新店：</span>
              <span class="value">{{ detailData.IsNewStore || '无' }}</span>
            </div>
            <div class="info-item" v-if="detailData.NewStoreProtectionStage !== undefined && detailData.NewStoreProtectionStage !== null">
              <span class="label">新店保护阶段：</span>
              <span class="value">{{ detailData.NewStoreProtectionStage || '0' }}</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 业绩信息 -->
      <div class="detail-section" v-if="hasPerformanceFields">
        <div class="section-title">
          <i class="el-icon-trophy"></i>
          <span>业绩信息</span>
        </div>
        <div class="section-content">
          <div class="info-row">
            <div class="info-item" v-for="field in performanceFields" :key="field.key">
              <span class="label">{{ field.label }}：</span>
              <span class="value" :class="{ highlight: field.highlight }">
                <span v-if="field.type === 'money'">{{ formatMoney(detailData[field.key]) }}</span>
                <span v-else>{{ detailData[field.key] || '无' }}</span>
              </span>
            </div>
          </div>
        </div>
      </div>

      <!-- 提成信息 -->
      <div class="detail-section" v-if="hasCommissionFields">
        <div class="section-title">
          <i class="el-icon-money"></i>
          <span>提成信息</span>
        </div>
        <div class="section-content">
          <div class="info-row">
            <div class="info-item" v-for="field in commissionFields" :key="field.key">
              <span class="label">{{ field.label }}：</span>
              <span class="value" :class="{ highlight: field.highlight }">
                <span v-if="field.type === 'money'">{{ formatMoney(detailData[field.key]) }}</span>
                <span v-else-if="field.type === 'percent'">{{ formatPercent(detailData[field.key]) }}</span>
                <span v-else>{{ detailData[field.key] || '无' }}</span>
              </span>
            </div>
          </div>
        </div>
      </div>

      <!-- 工资信息 -->
      <div class="detail-section" v-if="hasSalaryFields">
        <div class="section-title">
          <i class="el-icon-wallet"></i>
          <span>工资信息</span>
        </div>
        <div class="section-content">
          <div class="info-row">
            <div class="info-item" v-for="field in salaryFields" :key="field.key">
              <span class="label">{{ field.label }}：</span>
              <span class="value" :class="{ highlight: field.highlight, large: field.large }">
                <span v-if="field.type === 'money'">{{ formatMoney(detailData[field.key]) }}</span>
                <span v-else>{{ detailData[field.key] || '0' }}</span>
              </span>
            </div>
          </div>
        </div>
      </div>

      <!-- 保底信息 -->
      <div class="detail-section" v-if="hasGuaranteedFields">
        <div class="section-title">
          <i class="el-icon-lock"></i>
          <span>保底信息</span>
        </div>
        <div class="section-content">
          <div class="info-row">
            <div class="info-item" v-for="field in guaranteedFields" :key="field.key">
              <span class="label">{{ field.label }}：</span>
              <span class="value" :class="{ highlight: field.highlight }">
                <span v-if="field.type === 'money'">{{ formatMoney(detailData[field.key]) }}</span>
                <span v-else>{{ detailData[field.key] || '无' }}</span>
              </span>
            </div>
          </div>
        </div>
      </div>

      <!-- 补贴信息 -->
      <div class="detail-section" v-if="hasSubsidyFields">
        <div class="section-title">
          <i class="el-icon-circle-plus"></i>
          <span>补贴信息</span>
        </div>
        <div class="section-content">
          <div class="info-row">
            <div class="info-item" v-for="field in subsidyFields" :key="field.key">
              <span class="label">{{ field.label }}：</span>
              <span class="value" :class="{ highlight: field.highlight }">
                <span v-if="field.type === 'money'">{{ formatMoney(detailData[field.key]) }}</span>
                <span v-else>{{ detailData[field.key] || '无' }}</span>
              </span>
            </div>
          </div>
        </div>
      </div>

      <!-- 扣款信息 -->
      <div class="detail-section" v-if="hasDeductionFields">
        <div class="section-title">
          <i class="el-icon-circle-minus"></i>
          <span>扣款信息</span>
        </div>
        <div class="section-content">
          <div class="info-row">
            <div class="info-item" v-for="field in deductionFields" :key="field.key">
              <span class="label">{{ field.label }}：</span>
              <span class="value" :class="{ highlight: field.highlight }">
                <span v-if="field.type === 'money'">{{ formatMoney(detailData[field.key]) }}</span>
                <span v-else>{{ detailData[field.key] || '无' }}</span>
              </span>
            </div>
          </div>
        </div>
      </div>

      <!-- 其他信息 -->
      <div class="detail-section" v-if="hasOtherFields">
        <div class="section-title">
          <i class="el-icon-document"></i>
          <span>其他信息</span>
        </div>
        <div class="section-content">
          <div class="info-row">
            <div class="info-item" v-for="field in otherFields" :key="field.key">
              <span class="label">{{ field.label }}：</span>
              <span class="value" :class="{ highlight: field.highlight }">
                <span v-if="field.type === 'money'">{{ formatMoney(detailData[field.key]) }}</span>
                <span v-else>{{ detailData[field.key] || '无' }}</span>
              </span>
            </div>
          </div>
        </div>
      </div>

      <!-- 支付信息 -->
      <div class="detail-section" v-if="hasPaymentFields">
        <div class="section-title">
          <i class="el-icon-credit-card"></i>
          <span>支付信息</span>
        </div>
        <div class="section-content">
          <div class="info-row">
            <div class="info-item" v-for="field in paymentFields" :key="field.key">
              <span class="label">{{ field.label }}：</span>
              <span class="value" :class="{ highlight: field.highlight }">
                <span v-if="field.type === 'money'">{{ formatMoney(detailData[field.key]) }}</span>
                <span v-else>{{ detailData[field.key] || '无' }}</span>
              </span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div v-else class="no-data">
      <i class="el-icon-warning"></i>
      <span>暂无数据</span>
    </div>
  </el-dialog>
</template>

<script>
export default {
  name: 'MajorProjectTeacherDetailDialog',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    detailData: {
      type: Object,
      default: null
    }
  },
  computed: {
    // 业绩相关字段
    performanceFields() {
      return this.getFieldsByCategory('performance')
    },
    hasPerformanceFields() {
      return this.performanceFields.length > 0
    },
    // 提成相关字段
    commissionFields() {
      return this.getFieldsByCategory('commission')
    },
    hasCommissionFields() {
      return this.commissionFields.length > 0
    },
    // 工资相关字段
    salaryFields() {
      return this.getFieldsByCategory('salary')
    },
    hasSalaryFields() {
      return this.salaryFields.length > 0
    },
    // 保底相关字段
    guaranteedFields() {
      return this.getFieldsByCategory('guaranteed')
    },
    hasGuaranteedFields() {
      return this.guaranteedFields.length > 0
    },
    // 补贴相关字段
    subsidyFields() {
      return this.getFieldsByCategory('subsidy')
    },
    hasSubsidyFields() {
      return this.subsidyFields.length > 0
    },
    // 扣款相关字段
    deductionFields() {
      return this.getFieldsByCategory('deduction')
    },
    hasDeductionFields() {
      return this.deductionFields.length > 0
    },
    // 其他字段
    otherFields() {
      return this.getFieldsByCategory('other')
    },
    hasOtherFields() {
      return this.otherFields.length > 0
    },
    // 支付相关字段
    paymentFields() {
      return this.getFieldsByCategory('payment')
    },
    hasPaymentFields() {
      return this.paymentFields.length > 0
    }
  },
  methods: {
    handleClose() {
      this.$emit('update:visible', false)
      this.$emit('close')
    },
    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) + '%'
    },
    // 根据分类获取字段
    getFieldsByCategory(category) {
      if (!this.detailData) return []
      
      const excludeFields = ['StoreName', 'EmployeeName', 'Position', 'EmployeeAccount', 'Id', 'CreateTime', 'UpdateTime', 'CreateUser', 'UpdateUser', 'StatisticsMonth', 'IsNewStore', 'NewStoreProtectionStage']
      
      const categoryMap = {
        performance: ['OrderAchievement', 'ConsumeAchievement', 'RefundAchievement', 'TotalPerformance'],
        commission: ['Commission', 'PerformanceCommissionRate', 'PerformanceCommissionAmount', 'TotalCommission', 'HandworkFee'],
        salary: ['BaseSalary', 'WorkingDays', 'LeaveDays', 'TransportationAllowance', 'LessRest', 'FullAttendance', 'CalculatedGrossSalary'],
        guaranteed: ['GuaranteedSalary', 'GuaranteedLeaveDeduction', 'GuaranteedBaseSalary', 'GuaranteedSupplement', 'FinalGrossSalary'],
        subsidy: ['Subsidy', 'MonthlyTrainingSubsidy', 'MonthlyTransportSubsidy', 'LastMonthTrainingSubsidy', 'LastMonthTransportSubsidy', 'TotalSubsidy'],
        deduction: ['Deduction', 'MissingCard', 'LateArrival', 'LeaveDeduction', 'SocialInsuranceDeduction', 'RewardDeduction', 'AccommodationDeduction', 'StudyPeriodDeduction', 'WorkClothesDeduction', 'TotalDeduction'],
        payment: ['Payment', 'ActualSalary', 'MonthlyPaymentStatus', 'PaidAmount', 'PendingAmount', 'MonthlyTotalPayment'],
        other: ['Bonus', 'ReturnPhoneDeposit', 'ReturnAccommodationDeposit', 'LastMonthSupplement']
      }
      
      const keywords = categoryMap[category] || []
      const fields = []
      
      Object.keys(this.detailData).forEach(key => {
        if (excludeFields.includes(key)) return
        
        const lowerKey = key.toLowerCase()
        const matchesCategory = keywords.some(kw => lowerKey.includes(kw.toLowerCase()))
        
        if (matchesCategory || (category === 'other' && !this.isInOtherCategories(key))) {
          const type = this.getFieldType(key)
          const label = this.formatFieldLabel(key)
          fields.push({
            key,
            label,
            type,
            highlight: this.isHighlightField(key),
            large: key === 'ActualSalary'
          })
        }
      })
      
      return fields.sort((a, b) => {
        const orderA = this.getFieldOrder(a.key)
        const orderB = this.getFieldOrder(b.key)
        return orderA - orderB
      })
    },
    // 判断字段是否在其他分类中
    isInOtherCategories(key) {
      const lowerKey = key.toLowerCase()
      const categories = [
        ['orderachievement', 'consumeachievement', 'refundachievement', 'totalperformance'],
        ['commission', 'performancecommissionrate', 'performancecommissionamount', 'totalcommission', 'handworkfee'],
        ['basesalary', 'workingdays', 'leavedays', 'transportationallowance', 'lessrest', 'fullattendance', 'calculatedgrosssalary'],
        ['guaranteedsalary', 'guaranteedleavededuction', 'guaranteedbasesalary', 'guaranteedsupplement', 'finalgrosssalary'],
        ['subsidy', 'monthlytrainingsubsidy', 'monthlytransportsubsidy', 'lastmonthtrainingsubsidy', 'lastmonthtransportsubsidy', 'totalsubsidy'],
        ['deduction', 'missingcard', 'latearrival', 'leavededuction', 'socialinsurancededuction', 'rewarddeduction', 'accommodationdeduction', 'studyperioddeduction', 'workclothesdeduction', 'totaldeduction'],
        ['payment', 'actualsalary', 'monthlypaymentstatus', 'paidamount', 'pendingamount', 'monthlytotalpayment']
      ]
      
      return categories.some(cat => cat.some(kw => lowerKey.includes(kw)))
    },
    // 获取字段类型
    getFieldType(key) {
      const lowerKey = key.toLowerCase()
      
      const moneyFields = ['achievement', 'commission', 'salary', 'subsidy', 'deduction', 'amount', 'fee', 'bonus', 'deposit', 'supplement', 'payment', 'handwork', 'gross', 'guaranteed', 'transportation', 'allowance', 'total', 'lessrest', 'fullattendance']
      const percentFields = ['rate', 'percentage', 'percent']
      
      if (moneyFields.some(field => lowerKey.includes(field)) && !lowerKey.includes('status')) {
        return 'money'
      } else if (percentFields.some(field => lowerKey.includes(field))) {
        return 'percent'
      }
      return 'text'
    },
    // 格式化字段标签（参考后端 MajorProjectTeacherSalaryOutput.cs 的 XML 注释）
    formatFieldLabel(key) {
      // 根据后端字段定义的中文注释进行映射
      const labelMap = {
        // 基础信息
        'Id': '主键ID',
        'StatisticsMonth': '统计月份',
        'StoreId': '部门ID',
        'StoreName': '部门名称',
        'Position': '核算岗位',
        'EmployeeName': '员工姓名',
        'EmployeeId': '员工ID',
        'EmployeeAccount': '员工账号',
        'StoreType': '门店类型',
        'StoreCategory': '门店类别',
        'IsNewStore': '是否新店',
        'NewStoreProtectionStage': '新店保护阶段',
        'IsLocked': '是否锁定',
        'IsTerminated': '是否离职',
        'UpdateTime': '更新时间',
        'CreateTime': '创建时间',
        'CreateUser': '创建人',
        'UpdateUser': '更新人',
        
        // 业绩相关
        'OrderAchievement': '开单业绩',
        'ConsumeAchievement': '消耗业绩',
        'RefundAchievement': '退卡业绩',
        'TotalPerformance': '总业绩',
        
        // 底薪相关
        'BaseSalary': '底薪',
        
        // 业绩提成相关
        'PerformanceCommissionRate': '业绩提成比例',
        'PerformanceCommissionAmount': '业绩提成金额',
        'TotalCommission': '提成合计',
        
        // 其他收入
        'HandworkFee': '手工费',
        'TransportationAllowance': '车补',
        'LessRest': '少休费',
        'FullAttendance': '全勤奖',
        
        // 考勤相关
        'WorkingDays': '在店天数',
        'LeaveDays': '请假天数',
        
        // 工资计算
        'CalculatedGrossSalary': '核算应发工资',
        'GuaranteedSalary': '保底工资',
        'GuaranteedLeaveDeduction': '保底请假扣款',
        'GuaranteedBaseSalary': '保底底薪',
        'GuaranteedSupplement': '保底补差',
        'FinalGrossSalary': '最终应发工资',
        
        // 补贴相关
        'MonthlyTrainingSubsidy': '当月培训补贴',
        'MonthlyTransportSubsidy': '当月交通补贴',
        'LastMonthTrainingSubsidy': '上月培训补贴',
        'LastMonthTransportSubsidy': '上月交通补贴',
        'TotalSubsidy': '补贴合计',
        
        // 扣款相关
        'MissingCard': '缺卡扣款',
        'LateArrival': '迟到扣款',
        'LeaveDeduction': '请假扣款',
        'SocialInsuranceDeduction': '扣社保',
        'RewardDeduction': '扣除奖励',
        'AccommodationDeduction': '扣住宿费',
        'StudyPeriodDeduction': '扣学习期费用',
        'WorkClothesDeduction': '扣工作服费用',
        'TotalDeduction': '扣款合计',
        
        // 其他
        'Bonus': '发奖金',
        'ReturnPhoneDeposit': '退手机押金',
        'ReturnAccommodationDeposit': '退住宿押金',
        'LastMonthSupplement': '补发上月',
        
        // 支付相关
        'ActualSalary': '实发工资',
        'MonthlyPaymentStatus': '当月是否发放',
        'PaidAmount': '支付金额',
        'PendingAmount': '待支付金额',
        'MonthlyTotalPayment': '当月支付总额'
      }
      
      // 如果映射中存在，直接返回中文
      if (labelMap[key]) {
        return labelMap[key]
      }
      
      // 如果没有映射，尝试将驼峰命名转换为中文
      let chineseLabel = key
        .replace(/([A-Z])/g, ' $1') // 在大写字母前加空格
        .trim()
        .toLowerCase()
      
      // 常见英文单词的中文映射（作为兜底）
      const wordMap = {
        'store': '门店',
        'total': '总',
        'performance': '业绩',
        'order': '开单',
        'consume': '消耗',
        'refund': '退卡',
        'achievement': '业绩',
        'commission': '提成',
        'rate': '比例',
        'amount': '金额',
        'salary': '工资',
        'base': '底薪',
        'gross': '应发',
        'actual': '实发',
        'final': '最终',
        'calculated': '核算',
        'working': '在店',
        'days': '天数',
        'leave': '请假',
        'transportation': '交通',
        'allowance': '补贴',
        'less': '少',
        'rest': '休',
        'full': '全',
        'attendance': '勤',
        'guaranteed': '保底',
        'deduction': '扣款',
        'supplement': '补差',
        'subsidy': '补贴',
        'monthly': '当月',
        'training': '培训',
        'transport': '交通',
        'last': '上月',
        'missing': '缺',
        'card': '卡',
        'late': '迟到',
        'arrival': '到达',
        'social': '社保',
        'insurance': '保险',
        'reward': '奖励',
        'accommodation': '住宿',
        'study': '学习',
        'period': '期',
        'work': '工作',
        'clothes': '服',
        'fee': '费用',
        'bonus': '奖金',
        'return': '退',
        'phone': '手机',
        'deposit': '押金',
        'payment': '支付',
        'status': '状态',
        'paid': '已支付',
        'pending': '待支付',
        'handwork': '手工',
        'is': '是否',
        'new': '新',
        'protection': '保护',
        'stage': '阶段',
        'id': 'ID',
        'name': '名称',
        'type': '类型',
        'category': '类别',
        'time': '时间',
        'user': '人'
      }
      
      // 尝试翻译常见单词
      const words = chineseLabel.split(' ')
      const translatedWords = words.map(word => {
        // 移除常见的后缀
        const cleanWord = word.replace(/s$/, '').replace(/ed$/, '').replace(/ing$/, '')
        return wordMap[cleanWord] || wordMap[word] || word
      })
      
      // 如果翻译后的结果与原文不同，使用翻译结果
      if (translatedWords.some((w, i) => w !== words[i])) {
        chineseLabel = translatedWords.join('')
      } else {
        // 如果无法翻译，至少将驼峰命名转换为更易读的形式
        chineseLabel = key.replace(/([A-Z])/g, ' $1').trim()
      }
      
      return chineseLabel || key
    },
    // 判断是否为高亮字段
    isHighlightField(key) {
      const highlightFields = ['TotalPerformance', 'TotalCommission', 'FinalGrossSalary', 'ActualSalary', 'TotalSubsidy', 'TotalDeduction', 'MonthlyTotalPayment']
      return highlightFields.includes(key)
    },
    // 获取字段顺序
    getFieldOrder(key) {
      const orderMap = {
        'OrderAchievement': 1,
        'ConsumeAchievement': 2,
        'RefundAchievement': 3,
        'TotalPerformance': 4,
        'PerformanceCommissionRate': 10,
        'PerformanceCommissionAmount': 11,
        'TotalCommission': 12,
        'HandworkFee': 13,
        'BaseSalary': 20,
        'WorkingDays': 21,
        'LeaveDays': 22,
        'TransportationAllowance': 23,
        'LessRest': 24,
        'FullAttendance': 25,
        'CalculatedGrossSalary': 26,
        'GuaranteedSalary': 30,
        'GuaranteedLeaveDeduction': 31,
        'GuaranteedBaseSalary': 32,
        'GuaranteedSupplement': 33,
        'FinalGrossSalary': 34,
        'TotalSubsidy': 40,
        'TotalDeduction': 50,
        'ActualSalary': 60,
        'MonthlyTotalPayment': 70
      }
      return orderMap[key] || 999
    }
  }
}
</script>

<style lang="scss" scoped>
.detail-dialog {
  .detail-content {
    max-height: 70vh;
    overflow-y: auto;
    padding-right: 10px;
  }

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

    .section-title {
      display: flex;
      align-items: center;
      gap: 8px;
      margin-bottom: 16px;
      padding-bottom: 12px;
      border-bottom: 2px solid #409EFF;
      font-size: 16px;
      font-weight: 600;
      color: #303133;

      i {
        color: #409EFF;
        font-size: 18px;
      }
    }

    .section-content {
      .info-row {
        display: flex;
        flex-wrap: wrap;
        gap: 20px 40px;

        .info-item {
          display: flex;
          align-items: center;
          min-width: 200px;
          flex: 0 0 calc(33.333% - 27px);

          .label {
            color: #606266;
            font-size: 14px;
            white-space: nowrap;
            margin-right: 8px;
          }

          .value {
            color: #303133;
            font-size: 14px;
            font-weight: 500;

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

            &.large {
              font-size: 18px;
              color: #67C23A;
            }
          }
        }
      }
    }
  }

  .no-data {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 60px 20px;
    color: #909399;

    i {
      font-size: 48px;
      margin-bottom: 16px;
    }

    span {
      font-size: 14px;
    }
  }
}

// 滚动条样式
.detail-content::-webkit-scrollbar {
  width: 6px;
}

.detail-content::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.detail-content::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;

  &:hover {
    background: #a8a8a8;
  }
}
</style>

