<template>
  <div class="batch-cost-calculator">
    <el-form ref="calculatorFormRef" :model="calculatorForm" label-width="120px">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="计算方式">
            <el-radio-group v-model="calculationType" @change="handleCalculationTypeChange">
              <el-radio label="all">全部重新计算</el-radio>
              <el-radio label="selected">选择性计算</el-radio>
              <el-radio label="custom">自定义参数</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="计算基准">
            <el-select v-model="calculatorForm.calculationBase" placeholder="请选择计算基准">
              <el-option label="当前薪资标准" value="current_salary" />
              <el-option label="基础薪资标准" value="base_salary" />
              <el-option label="市场薪资标准" value="market_salary" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 自定义参数 -->
      <div v-if="calculationType === 'custom'">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="加班费率">
              <el-input-number 
                v-model="calculatorForm.overtimeRate" 
                :min="1" 
                :max="5" 
                :precision="2"
                placeholder="加班费率"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="津贴系数">
              <el-input-number 
                v-model="calculatorForm.allowanceRate" 
                :min="0" 
                :max="2" 
                :precision="2"
                placeholder="津贴系数"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="社保费率">
              <el-input-number 
                v-model="calculatorForm.socialInsuranceRate" 
                :min="0" 
                :max="0.5" 
                :precision="3"
                placeholder="社保费率"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <!-- 选择性计算 -->
      <div v-if="calculationType === 'selected'">
        <el-form-item label="选择员工">
          <el-transfer
            v-model="selectedEmployeeIds"
            :data="availableEmployees"
            :titles="['可选员工', '已选员工']"
            :button-texts="['移除', '添加']"
            :format="{
              noChecked: '${total}',
              hasChecked: '${checked}/${total}'
            }"
            filterable
          />
        </el-form-item>
      </div>
    </el-form>

    <!-- 计算进度 -->
    <el-card class="mt-4" v-if="calculating">
      <template #header>
        <span>计算进度</span>
      </template>
      <el-progress 
        :percentage="calculationProgress" 
        :status="calculationStatus"
        :stroke-width="20"
      />
      <div class="mt-2 text-center">
        <span>{{ calculationMessage }}</span>
      </div>
    </el-card>

    <!-- 计算结果 -->
    <el-card class="mt-4" v-if="calculationResults.length > 0">
      <template #header>
        <div class="card-header">
          <span>计算结果</span>
          <el-button type="success" @click="exportResults">导出结果</el-button>
        </div>
      </template>
      
      <!-- 汇总信息 -->
      <el-row :gutter="20" class="mb-4">
        <el-col :span="6">
          <el-statistic title="总员工数" :value="summaryData.totalEmployees" />
        </el-col>
        <el-col :span="6">
          <el-statistic title="总成本" :value="summaryData.totalCost" prefix="¥" />
        </el-col>
        <el-col :span="6">
          <el-statistic title="平均成本" :value="summaryData.averageCost" prefix="¥" />
        </el-col>
        <el-col :span="6">
          <el-statistic title="成本变化" :value="summaryData.costChange" prefix="¥" />
        </el-col>
      </el-row>

      <!-- 详细结果 -->
      <el-table :data="calculationResults" stripe max-height="400">
        <el-table-column label="员工ID" align="center" prop="employeeId" />
        <el-table-column label="员工姓名" align="center" prop="employeeName" />
        <el-table-column label="工作天数" align="center" prop="workDays" />
        <el-table-column label="基础薪资" align="center">
          <template #default="scope">
            <span>¥{{ scope.row.baseSalary }}</span>
          </template>
        </el-table-column>
        <el-table-column label="加班费用" align="center">
          <template #default="scope">
            <span>¥{{ scope.row.overtimeCost || 0 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="津贴费用" align="center">
          <template #default="scope">
            <span>¥{{ scope.row.allowanceCost || 0 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="社保费用" align="center">
          <template #default="scope">
            <span>¥{{ scope.row.socialInsuranceCost || 0 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="总成本" align="center">
          <template #default="scope">
            <span class="cost-highlight">¥{{ scope.row.totalCost }}</span>
          </template>
        </el-table-column>
        <el-table-column label="成本变化" align="center">
          <template #default="scope">
            <span :class="getCostChangeClass(scope.row.costChange)">
              {{ scope.row.costChange >= 0 ? '+' : '' }}¥{{ scope.row.costChange }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="计算状态" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.calculationStatus === 'success' ? 'success' : 'danger'">
              {{ scope.row.calculationStatus === 'success' ? '成功' : '失败' }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 操作按钮 -->
    <div class="mt-4 text-center">
      <el-button type="primary" @click="handleStartCalculation" :loading="calculating" :disabled="calculating">
        开始计算
      </el-button>
      <el-button type="success" @click="handleApplyResults" :disabled="calculationResults.length === 0" :loading="applying">
        应用结果
      </el-button>
      <el-button @click="handleCancel">取消</el-button>
    </div>
  </div>
</template>

<script setup>
import { calculateLaborCost, getServicePeriodEmployees } from "@/api/digitalCredit/contractEmployee";

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

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

const { proxy } = getCurrentInstance();

const calculationType = ref('all');
const calculating = ref(false);
const applying = ref(false);
const calculationProgress = ref(0);
const calculationStatus = ref('');
const calculationMessage = ref('');

const calculatorForm = ref({
  calculationBase: 'current_salary',
  overtimeRate: 1.5,
  allowanceRate: 0.1,
  socialInsuranceRate: 0.2
});

const availableEmployees = ref([]);
const selectedEmployeeIds = ref([]);
const calculationResults = ref([]);
const summaryData = ref({
  totalEmployees: 0,
  totalCost: 0,
  averageCost: 0,
  costChange: 0
});

/** 计算方式变更 */
function handleCalculationTypeChange() {
  calculationResults.value = [];
  if (calculationType.value === 'selected') {
    loadAvailableEmployees();
  }
}

/** 加载可选员工 */
function loadAvailableEmployees() {
  getServicePeriodEmployees(props.servicePeriodId).then(response => {
    availableEmployees.value = response.data.map(emp => ({
      key: emp.employeeId,
      label: `${emp.employeeId} - ${emp.employeeName || '未知'}`,
      disabled: false
    }));
  });
}

/** 获取成本变化样式 */
function getCostChangeClass(costChange) {
  if (costChange > 0) return 'text-danger';
  if (costChange < 0) return 'text-success';
  return 'text-info';
}

/** 开始计算 */
function handleStartCalculation() {
  calculating.value = true;
  calculationProgress.value = 0;
  calculationStatus.value = '';
  calculationMessage.value = '正在准备计算...';

  // 模拟计算过程
  simulateCalculation();
}

/** 模拟计算过程 */
function simulateCalculation() {
  const steps = [
    { progress: 20, message: '获取员工数据...' },
    { progress: 40, message: '计算基础薪资...' },
    { progress: 60, message: '计算加班费用...' },
    { progress: 80, message: '计算津贴和社保...' },
    { progress: 100, message: '计算完成' }
  ];

  let currentStep = 0;
  const interval = setInterval(() => {
    if (currentStep < steps.length) {
      calculationProgress.value = steps[currentStep].progress;
      calculationMessage.value = steps[currentStep].message;
      currentStep++;
    } else {
      clearInterval(interval);
      performActualCalculation();
    }
  }, 800);
}

/** 执行实际计算 */
function performActualCalculation() {
  calculateLaborCost(props.servicePeriodId).then(response => {
    const data = response.data;
    
    // 构建计算结果
    const results = data.employeeCosts?.map(emp => ({
      employeeId: emp.employeeId,
      employeeName: emp.employeeName || '未知',
      workDays: emp.workDays || 0,
      baseSalary: emp.assignedSalary || 0,
      overtimeCost: calculateOvertimeCost(emp),
      allowanceCost: calculateAllowanceCost(emp),
      socialInsuranceCost: calculateSocialInsuranceCost(emp),
      totalCost: emp.totalCost || 0,
      costChange: calculateCostChange(emp),
      calculationStatus: 'success'
    })) || [];

    calculationResults.value = results;
    
    // 计算汇总数据
    summaryData.value = {
      totalEmployees: results.length,
      totalCost: results.reduce((sum, item) => sum + item.totalCost, 0),
      averageCost: results.length > 0 ? results.reduce((sum, item) => sum + item.totalCost, 0) / results.length : 0,
      costChange: results.reduce((sum, item) => sum + item.costChange, 0)
    };

    calculationStatus.value = 'success';
    calculationMessage.value = '计算完成';
    
  }).catch(error => {
    calculationStatus.value = 'exception';
    calculationMessage.value = '计算失败';
    proxy.$modal.msgError("计算失败：" + error.message);
  }).finally(() => {
    calculating.value = false;
  });
}

/** 计算加班费用 */
function calculateOvertimeCost(employee) {
  const baseSalary = employee.assignedSalary || 0;
  const overtimeHours = employee.overtimeHours || 0;
  return baseSalary * calculatorForm.value.overtimeRate * (overtimeHours / 8); // 假设8小时工作制
}

/** 计算津贴费用 */
function calculateAllowanceCost(employee) {
  const baseSalary = employee.assignedSalary || 0;
  return baseSalary * calculatorForm.value.allowanceRate;
}

/** 计算社保费用 */
function calculateSocialInsuranceCost(employee) {
  const baseSalary = employee.assignedSalary || 0;
  return baseSalary * calculatorForm.value.socialInsuranceRate;
}

/** 计算成本变化 */
function calculateCostChange(employee) {
  // 这里应该与之前的成本进行比较，暂时返回0
  return 0;
}

/** 应用结果 */
function handleApplyResults() {
  if (calculationResults.value.length === 0) {
    proxy.$modal.msgWarning("没有计算结果可应用");
    return;
  }

  proxy.$modal.confirm('确认应用计算结果？这将更新所有员工的成本信息。').then(() => {
    applying.value = true;
    
    // 这里应该调用API应用计算结果
    setTimeout(() => {
      proxy.$modal.msgSuccess("计算结果应用成功");
      emit('calculation-complete');
      applying.value = false;
    }, 1000);
    
  }).catch(() => {
    // 用户取消
  });
}

/** 导出结果 */
function exportResults() {
  // 这里应该调用导出API
  proxy.$modal.msgSuccess("结果导出成功");
}

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

onMounted(() => {
  if (calculationType.value === 'selected') {
    loadAvailableEmployees();
  }
});
</script>

<style scoped>
.batch-cost-calculator {
  padding: 20px;
}

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

.mb-4 {
  margin-bottom: 16px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.cost-highlight {
  font-weight: bold;
  color: #409eff;
}

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

.text-danger {
  color: #f56c6c;
}

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