<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" v-if="detailData.GoldTriangleTeam">
              <span class="label">金三角团队：</span>
              <span class="value">{{ detailData.GoldTriangleTeam || '无' }}</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 class="info-item" v-if="detailData.IsLocked !== undefined && detailData.IsLocked !== null">
              <span class="label">锁定状态：</span>
              <el-tag :type="detailData.IsLocked === 1 ? 'danger' : 'success'" size="mini">
                {{ detailData.IsLocked === 1 ? '已锁定' : '未锁定' }}
              </el-tag>
            </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-if="field.type === 'percent'">{{ formatPercent(detailData[field.key]) }}</span>
                <el-tag v-else-if="field.type === 'tag'" :type="getTagType(detailData[field.key])" size="mini">
                  {{ detailData[field.key] || '否' }}
                </el-tag>
                <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="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-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="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: 'DirectorDetailDialog',
  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
    },
    // 补贴相关字段
    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) + '%'
    },
    getTagType(value) {
      if (value === '是' || value === 1) {
        return 'success'
      }
      return 'info'
    },
    // 根据分类获取字段
    getFieldsByCategory(category) {
      if (!this.detailData) return []
      
      const excludeFields = ['StoreName', 'EmployeeName', 'Position', 'Id', 'CreateTime', 'UpdateTime', 'CreateUser', 'UpdateUser', 'StatisticsMonth', 'GoldTriangleTeam', 'IsNewStore', 'NewStoreProtectionStage', 'IsLocked']
      
      const categoryMap = {
        performance: ['Performance', 'Lifeline', 'CompletionRate', 'Reached', 'HeadCount', 'Target', 'Consume'],
        commission: ['Commission', 'Point', 'Rate'],
        salary: ['Salary', 'BaseSalary', 'Gross', 'Actual'],
        subsidy: ['Subsidy', 'Allowance', 'Transportation', 'Training', 'FullAttendance', 'LessRest'],
        deduction: ['Deduction', 'MissingCard', 'LateArrival', 'Leave', 'SocialInsurance', 'Reward', 'Accommodation', 'StudyPeriod', 'WorkClothes', 'Assessment'],
        payment: ['Payment', 'Paid', 'Pending', 'Monthly'],
        other: ['Bonus', 'Deposit', 'Supplement', 'Category', 'Type']
      }
      
      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 = [
        ['performance', 'lifeline', 'completionrate', 'reached', 'headcount', 'target', 'consume'],
        ['commission', 'point', 'rate'],
        ['salary', 'basesalary', 'gross', 'actual'],
        ['subsidy', 'allowance', 'transportation', 'training', 'fullattendance', 'lessrest'],
        ['deduction', 'missingcard', 'latearrival', 'leave', 'socialinsurance', 'reward', 'accommodation', 'studyperiod', 'workclothes', 'assessment'],
        ['payment', 'paid', 'pending', 'monthly']
      ]
      
      return categories.some(cat => cat.some(kw => lowerKey.includes(kw)))
    },
    // 获取字段类型
    getFieldType(key) {
      const lowerKey = key.toLowerCase()
      
      // 状态类字段
      const statusFields = ['status', 'reached', 'isnewstore', 'islocked']
      if (statusFields.some(field => lowerKey.includes(field))) {
        return 'tag'
      }
      
      const moneyFields = ['performance', 'commission', 'salary', 'subsidy', 'deduction', 'amount', 'fee', 'bonus', 'deposit', 'supplement', 'payment', 'consumption', 'reward', 'handwork', 'gross', 'guaranteed', 'transportation', 'allowance', 'total']
      const percentFields = ['point', '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'
    },
    // 格式化字段标签
    formatFieldLabel(key) {
      // 字段名中文映射（与 director.vue 保持一致）
      const labelMap = {
        // 业绩相关
        'StoreTotalPerformance': '门店总业绩',
        'StoreBillingPerformance': '门店开单业绩',
        'StoreRefundPerformance': '门店退卡业绩',
        'StoreLifeline': '门店生命线',
        'PerformanceCompletionRate': '业绩完成率',
        'TotalPerformance': '总业绩',
        'BasePerformance': '基础业绩',
        'CooperationPerformance': '合作业绩',
        'GoldTriangleTeam': '金三角团队',
        
        // 考核相关
        'PerformanceReached': '业绩是否达标',
        'HeadCountReached': '人头是否达标',
        'ConsumeReached': '消耗是否达标',
        'AssessmentDeduction': '考核扣款金额',
        'UnreachedIndicatorCount': '未达标指标数量',
        
        // 人头相关
        'HeadCount': '进店消耗人数',
        'TargetHeadCount': '目标人头数',
        
        // 消耗相关
        'StoreConsume': '门店消耗金额',
        'TargetConsume': '目标消耗金额',
        
        // 提成相关
        'CommissionRateBelowLifeline': '≤生命线部分提成比例',
        'CommissionRateAboveLifeline': '>生命线部分提成比例',
        'CommissionAmountBelowLifeline': '≤生命线部分提成金额',
        'CommissionAmountAboveLifeline': '>生命线部分提成金额',
        'TotalCommissionAmount': '提成总金额',
        'TotalCommission': '提成合计',
        'BasePerformanceCommission': '基础业绩提成',
        'CooperationPerformanceCommission': '合作业绩提成',
        'CommissionRate': '提成比例',
        'CommissionAmount': '提成金额',
        
        // 底薪相关
        'BaseSalary': '底薪金额',
        'ActualBaseSalary': '实际底薪',
        
        // 考勤相关
        'WorkingDays': '在店天数',
        'LeaveDays': '请假天数',
        
        // 工资相关
        'GrossSalary': '应发工资',
        'FinalGrossSalary': '最终应发工资',
        'ActualSalary': '实发工资',
        
        // 扣款相关
        'TotalDeduction': '扣款合计',
        'MissingCard': '缺卡扣款',
        'LateArrival': '迟到扣款',
        'LeaveDeduction': '请假扣款',
        'SocialInsuranceDeduction': '扣社保',
        'RewardDeduction': '扣除奖励',
        'AccommodationDeduction': '扣住宿费',
        'StudyPeriodDeduction': '扣学习期费用',
        'WorkClothesDeduction': '扣工作服费用',
        
        // 补贴相关
        'TotalSubsidy': '补贴合计',
        'MonthlyTrainingSubsidy': '当月培训补贴',
        'MonthlyTransportSubsidy': '当月交通补贴',
        'LastMonthTrainingSubsidy': '上月培训补贴',
        'LastMonthTransportSubsidy': '上月交通补贴',
        'TransportationAllowance': '车补',
        'LessRest': '少休费',
        'FullAttendance': '全勤奖',
        
        // 奖金相关
        'Bonus': '发奖金',
        'ReturnPhoneDeposit': '退手机押金',
        'ReturnAccommodationDeposit': '退住宿押金',
        
        // 支付相关
        'MonthlyPaymentStatus': '当月是否发放',
        'PaidAmount': '支付金额',
        'PendingAmount': '待支付金额',
        'LastMonthSupplement': '补发上月',
        'MonthlyTotalPayment': '当月支付总额',
        
        // 其他
        'IsLocked': '是否锁定',
        'StoreType': '门店类型',
        'StoreCategory': '门店类别',
        'IsNewStore': '是否新店',
        'NewStoreProtectionStage': '新店保护阶段'
      }
      
      // 如果映射中存在，直接返回中文
      if (labelMap[key]) {
        return labelMap[key]
      }
      
      // 如果没有映射，尝试将驼峰命名转换为中文
      // 将驼峰命名转换为中文（简单处理）
      let chineseLabel = key
        .replace(/([A-Z])/g, ' $1') // 在大写字母前加空格
        .trim()
        .toLowerCase()
      
      // 常见英文单词的中文映射
      const wordMap = {
        'store': '门店',
        'total': '总',
        'performance': '业绩',
        'billing': '开单',
        'refund': '退卡',
        'lifeline': '生命线',
        'completion': '完成',
        'rate': '率',
        'base': '基础',
        'cooperation': '合作',
        'reached': '是否达标',
        'head': '人头',
        'count': '数',
        'target': '目标',
        'consume': '消耗',
        'commission': '提成',
        'amount': '金额',
        'salary': '工资',
        'gross': '应发',
        'actual': '实际',
        'final': '最终',
        'deduction': '扣款',
        'subsidy': '补贴',
        'working': '在店',
        'days': '天数',
        'leave': '请假',
        'missing': '缺',
        'card': '卡',
        'late': '迟到',
        'arrival': '到达',
        'social': '社保',
        'insurance': '保险',
        'reward': '奖励',
        'accommodation': '住宿',
        'study': '学习',
        'period': '期',
        'work': '工作',
        'clothes': '服',
        'monthly': '当月',
        'training': '培训',
        'transport': '交通',
        'last': '上月',
        'payment': '支付',
        'status': '状态',
        'paid': '已支付',
        'pending': '待支付',
        'supplement': '补发',
        'bonus': '奖金',
        'return': '退',
        'phone': '手机',
        'deposit': '押金',
        'transportation': '交通',
        'allowance': '补贴',
        'less': '少',
        'rest': '休',
        'full': '全',
        'attendance': '勤',
        'is': '是否',
        'locked': '锁定',
        'new': '新',
        'protection': '保护',
        'stage': '阶段',
        'type': '类型',
        'category': '类别',
        'assessment': '考核',
        'unreached': '未达标',
        'indicator': '指标',
        'below': '以下',
        'above': '以上',
        'lifeline': '生命线',
        'point': '点',
        'percent': '百分比'
      }
      
      // 尝试翻译常见单词
      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 = {
        'TotalPerformance': 1,
        'BasePerformance': 2,
        'CooperationPerformance': 3,
        'TotalCommission': 10,
        'BasePerformanceCommission': 11,
        'CooperationPerformanceCommission': 12,
        'FinalGrossSalary': 20,
        'ActualSalary': 21,
        'TotalSubsidy': 30,
        'TotalDeduction': 40,
        'MonthlyTotalPayment': 50
      }
      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>

