<template>
  <div class="batch-salary-adjuster">
    <el-form ref="batchFormRef" :model="batchForm" label-width="120px">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="调整方式">
            <el-radio-group v-model="adjustmentType" @change="handleAdjustmentTypeChange">
              <el-radio label="percentage">按百分比调整</el-radio>
              <el-radio label="fixed">固定金额调整</el-radio>
              <el-radio label="individual">逐个调整</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="薪资类型">
            <el-select v-model="batchForm.salaryType" placeholder="请选择薪资类型">
              <el-option label="小时制" value="HOURLY" />
              <el-option label="日薪制" value="DAILY" />
              <el-option label="月薪制" value="MONTHLY" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 按百分比调整 -->
      <div v-if="adjustmentType === 'percentage'">
        <el-form-item label="调整百分比">
          <el-input-number 
            v-model="batchForm.adjustmentPercentage" 
            :min="-100" 
            :max="1000" 
            :precision="2"
            placeholder="请输入调整百分比"
          />
          <span class="ml-2">%</span>
        </el-form-item>
        <el-alert 
          :title="`将对所选员工薪资进行${batchForm.adjustmentPercentage > 0 ? '上调' : '下调'}${Math.abs(batchForm.adjustmentPercentage)}%的调整`"
          type="info" 
          show-icon 
          :closable="false"
        />
      </div>

      <!-- 固定金额调整 -->
      <div v-if="adjustmentType === 'fixed'">
        <el-form-item label="调整金额">
          <el-input-number 
            v-model="batchForm.adjustmentAmount" 
            :precision="2"
            placeholder="请输入调整金额"
          />
          <span class="ml-2">元</span>
        </el-form-item>
        <el-alert 
          :title="`将对所选员工薪资进行${batchForm.adjustmentAmount > 0 ? '增加' : '减少'}${Math.abs(batchForm.adjustmentAmount)}元的调整`"
          type="info" 
          show-icon 
          :closable="false"
        />
      </div>

      <!-- 逐个调整 -->
      <div v-if="adjustmentType === 'individual'">
        <el-table :data="individualAdjustments" stripe>
          <el-table-column label="员工ID" align="center" prop="employeeId" />
          <el-table-column label="当前薪资" align="center">
            <template #default="scope">
              <span>¥{{ scope.row.currentSalary }}</span>
            </template>
          </el-table-column>
          <el-table-column label="调整后薪资" align="center">
            <template #default="scope">
              <el-input-number 
                v-model="scope.row.adjustedSalary" 
                :precision="2"
                :min="0"
                size="small"
              />
            </template>
          </el-table-column>
          <el-table-column label="调整幅度" align="center">
            <template #default="scope">
              <span :class="getAdjustmentClass(scope.row)">
                {{ getAdjustmentText(scope.row) }}
              </span>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-form>

    <!-- 预览结果 -->
    <el-card class="mt-4" v-if="previewData.length > 0">
      <template #header>
        <span>调整预览</span>
      </template>
      <el-table :data="previewData" stripe>
        <el-table-column label="员工ID" align="center" prop="employeeId" />
        <el-table-column label="调整前薪资" align="center">
          <template #default="scope">
            <span>¥{{ scope.row.originalSalary }}</span>
          </template>
        </el-table-column>
        <el-table-column label="调整后薪资" align="center">
          <template #default="scope">
            <span>¥{{ scope.row.adjustedSalary }}</span>
          </template>
        </el-table-column>
        <el-table-column label="调整金额" align="center">
          <template #default="scope">
            <span :class="scope.row.adjustmentAmount >= 0 ? 'text-success' : 'text-danger'">
              {{ scope.row.adjustmentAmount >= 0 ? '+' : '' }}¥{{ scope.row.adjustmentAmount }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="调整比例" align="center">
          <template #default="scope">
            <span :class="scope.row.adjustmentPercentage >= 0 ? 'text-success' : 'text-danger'">
              {{ scope.row.adjustmentPercentage >= 0 ? '+' : '' }}{{ scope.row.adjustmentPercentage }}%
            </span>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="mt-4 text-center">
        <el-statistic title="总调整金额" :value="totalAdjustmentAmount" prefix="¥" />
      </div>
    </el-card>

    <!-- 操作按钮 -->
    <div class="mt-4 text-center">
      <el-button type="primary" @click="handlePreview" :loading="previewLoading">预览调整</el-button>
      <el-button type="success" @click="handleConfirmAdjustment" :disabled="previewData.length === 0" :loading="adjustLoading">
        确认调整
      </el-button>
      <el-button @click="handleCancel">取消</el-button>
    </div>
  </div>
</template>

<script setup>
import { batchAdjustSalaryStandards } from "@/api/digitalCredit/contractEmployee";

const props = defineProps({
  servicePeriodId: {
    type: [String, Number],
    required: true
  },
  selectedEmployees: {
    type: Array,
    default: () => []
  }
});

const emit = defineEmits(['adjust-complete']);

const { proxy } = getCurrentInstance();

const adjustmentType = ref('percentage');
const previewLoading = ref(false);
const adjustLoading = ref(false);

const batchForm = ref({
  salaryType: 'DAILY',
  adjustmentPercentage: 0,
  adjustmentAmount: 0
});

const individualAdjustments = ref([]);
const previewData = ref([]);
const totalAdjustmentAmount = ref(0);

/** 调整方式变更 */
function handleAdjustmentTypeChange() {
  previewData.value = [];
  if (adjustmentType.value === 'individual') {
    initIndividualAdjustments();
  }
}

/** 初始化逐个调整数据 */
function initIndividualAdjustments() {
  individualAdjustments.value = props.selectedEmployees.map(emp => ({
    employeeId: emp.employeeId,
    currentSalary: emp.assignedSalary || 0,
    adjustedSalary: emp.assignedSalary || 0
  }));
}

/** 获取调整幅度样式 */
function getAdjustmentClass(row) {
  const diff = row.adjustedSalary - row.currentSalary;
  if (diff > 0) return 'text-success';
  if (diff < 0) return 'text-danger';
  return 'text-info';
}

/** 获取调整幅度文本 */
function getAdjustmentText(row) {
  const diff = row.adjustedSalary - row.currentSalary;
  if (diff === 0) return '无变化';
  
  const percentage = ((diff / row.currentSalary) * 100).toFixed(2);
  return `${diff > 0 ? '+' : ''}¥${diff} (${diff > 0 ? '+' : ''}${percentage}%)`;
}

/** 预览调整 */
function handlePreview() {
  if (props.selectedEmployees.length === 0) {
    proxy.$modal.msgWarning("请先选择要调整的员工");
    return;
  }

  previewLoading.value = true;
  
  try {
    const preview = [];
    let totalAdjustment = 0;

    props.selectedEmployees.forEach(emp => {
      const originalSalary = emp.assignedSalary || 0;
      let adjustedSalary = originalSalary;

      if (adjustmentType.value === 'percentage') {
        adjustedSalary = originalSalary * (1 + batchForm.value.adjustmentPercentage / 100);
      } else if (adjustmentType.value === 'fixed') {
        adjustedSalary = originalSalary + batchForm.value.adjustmentAmount;
      } else if (adjustmentType.value === 'individual') {
        const individualAdj = individualAdjustments.value.find(adj => adj.employeeId === emp.employeeId);
        adjustedSalary = individualAdj ? individualAdj.adjustedSalary : originalSalary;
      }

      const adjustmentAmount = adjustedSalary - originalSalary;
      const adjustmentPercentage = originalSalary > 0 ? ((adjustmentAmount / originalSalary) * 100).toFixed(2) : 0;

      preview.push({
        employeeId: emp.employeeId,
        originalSalary: originalSalary,
        adjustedSalary: Math.round(adjustedSalary * 100) / 100,
        adjustmentAmount: Math.round(adjustmentAmount * 100) / 100,
        adjustmentPercentage: parseFloat(adjustmentPercentage)
      });

      totalAdjustment += adjustmentAmount;
    });

    previewData.value = preview;
    totalAdjustmentAmount.value = Math.round(totalAdjustment * 100) / 100;
    
  } finally {
    previewLoading.value = false;
  }
}

/** 确认调整 */
function handleConfirmAdjustment() {
  if (previewData.value.length === 0) {
    proxy.$modal.msgWarning("请先预览调整结果");
    return;
  }

  proxy.$modal.confirm('确认执行批量薪资调整？').then(() => {
    adjustLoading.value = true;
    
    // 构建调整数据
    const salaryAdjustments = {};
    previewData.value.forEach(item => {
      salaryAdjustments[item.employeeId] = item.adjustedSalary;
    });

    return batchAdjustSalaryStandards(props.servicePeriodId, {
      salaryAdjustments: salaryAdjustments
    });
  }).then(response => {
    proxy.$modal.msgSuccess("批量薪资调整成功");
    emit('adjust-complete');
  }).catch(() => {
    // 用户取消或调整失败
  }).finally(() => {
    adjustLoading.value = false;
  });
}

/** 取消 */
function handleCancel() {
  emit('adjust-complete');
}

onMounted(() => {
  if (adjustmentType.value === 'individual') {
    initIndividualAdjustments();
  }
});
</script>

<style scoped>
.batch-salary-adjuster {
  padding: 20px;
}

.mt-4 {
  margin-top: 16px;
}

.ml-2 {
  margin-left: 8px;
}

.text-success {
  color: #67c23a;
}

.text-danger {
  color: #f56c6c;
}

.text-info {
  color: #909399;
}
</style>