<template>
  <div class="cost-calculation">
    <el-row :gutter="20">
      <!-- 成本概览 -->
      <el-col :span="24">
        <el-card class="mb-4">
          <template #header>
            <div class="card-header">
              <span>成本概览</span>
              <el-button type="primary" @click="refreshCostData">刷新数据</el-button>
            </div>
          </template>
          <el-row :gutter="20">
            <el-col :span="6">
              <div class="cost-item">
                <div class="cost-label">总成本</div>
                <div class="cost-value total-cost">¥{{ costData.totalCost || 0 }}</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="cost-item">
                <div class="cost-label">总员工数</div>
                <div class="cost-value">{{ costData.totalEmployees || 0 }}人</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="cost-item">
                <div class="cost-label">总工作天数</div>
                <div class="cost-value">{{ costData.totalWorkDays || 0 }}天</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="cost-item">
                <div class="cost-label">平均成本/人</div>
                <div class="cost-value">¥{{ costData.averageCostPerEmployee || 0 }}</div>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </el-col>

      <!-- 员工成本明细 -->
      <el-col :span="24">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>员工成本明细</span>
              <div>
                <el-button type="success" @click="exportCostReport">导出报表</el-button>
                <el-button type="warning" @click="handleBatchCostCalculation">批量计算</el-button>
              </div>
            </div>
          </template>
          
          <el-table v-loading="loading" :data="employeeCosts" stripe>
            <el-table-column label="员工ID" align="center" prop="employeeId" />
            <el-table-column label="员工姓名" align="center" prop="employeeName" />
            <el-table-column label="分配岗位" align="center" prop="assignedPosition" />
            <el-table-column label="工作天数" align="center" prop="workDays" />
            <el-table-column label="薪资标准" align="center" prop="assignedSalary">
              <template #default="scope">
                <span>¥{{ scope.row.assignedSalary }}</span>
              </template>
            </el-table-column>
            <el-table-column label="总成本" align="center" prop="totalCost">
              <template #default="scope">
                <span class="cost-highlight">¥{{ scope.row.totalCost }}</span>
              </template>
            </el-table-column>
            <el-table-column label="成本占比" align="center">
              <template #default="scope">
                <el-progress 
                  :percentage="calculateCostPercentage(scope.row.totalCost)" 
                  :color="getProgressColor(calculateCostPercentage(scope.row.totalCost))"
                />
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template #default="scope">
                <el-button link type="primary" @click="handleCalculateEmployeeCost(scope.row)">重新计算</el-button>
                <el-button link type="warning" @click="handleAdjustCost(scope.row)">调整成本</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>

      <!-- 成本分析图表 -->
      <el-col :span="24" class="mt-4">
        <el-card>
          <template #header>
            <span>成本分析</span>
          </template>
          <el-row :gutter="20">
            <el-col :span="12">
              <div ref="costPieChart" style="height: 300px;"></div>
            </el-col>
            <el-col :span="12">
              <div ref="costBarChart" style="height: 300px;"></div>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
    </el-row>

    <!-- 成本调整对话框 -->
    <el-dialog title="成本调整" v-model="costAdjustDialogVisible" width="500px">
      <el-form ref="costAdjustFormRef" :model="costAdjustForm" :rules="costAdjustRules" label-width="100px">
        <el-form-item label="员工ID" prop="employeeId">
          <el-input v-model="costAdjustForm.employeeId" disabled />
        </el-form-item>
        <el-form-item label="当前成本" prop="currentCost">
          <el-input v-model="costAdjustForm.currentCost" disabled />
        </el-form-item>
        <el-form-item label="调整后成本" prop="adjustedCost">
          <el-input-number v-model="costAdjustForm.adjustedCost" :precision="2" placeholder="请输入调整后成本" />
        </el-form-item>
        <el-form-item label="调整原因" prop="adjustReason">
          <el-input v-model="costAdjustForm.adjustReason" type="textarea" placeholder="请输入调整原因" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitCostAdjustment">确 定</el-button>
          <el-button @click="costAdjustDialogVisible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 批量成本计算对话框 -->
    <el-dialog title="批量成本计算" v-model="batchCalculationDialogVisible" width="60%">
      <batch-cost-calculator 
        :service-period-id="servicePeriodId"
        @calculation-complete="handleBatchCalculationComplete"
      />
    </el-dialog>
  </div>
</template>

<script setup>
import { calculateLaborCost, calculateEmployeeCost, recalculateTotalCost } from "@/api/digitalCredit/contractEmployee";
import * as echarts from 'echarts';
import BatchCostCalculator from "./BatchCostCalculator.vue";

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

const emit = defineEmits(['close']);

const { proxy } = getCurrentInstance();

const loading = ref(false);
const costData = ref({});
const employeeCosts = ref([]);

// 对话框状态
const costAdjustDialogVisible = ref(false);
const batchCalculationDialogVisible = ref(false);

// 表单数据
const costAdjustForm = ref({
  employeeId: null,
  currentCost: 0,
  adjustedCost: 0,
  adjustReason: ''
});

// 表单验证规则
const costAdjustRules = {
  adjustedCost: [{ required: true, message: "调整后成本不能为空", trigger: "blur" }],
  adjustReason: [{ required: true, message: "调整原因不能为空", trigger: "blur" }]
};

// 图表实例
const costPieChart = ref(null);
const costBarChart = ref(null);
let pieChartInstance = null;
let barChartInstance = null;

/** 获取成本数据 */
function getCostData() {
  loading.value = true;
  calculateLaborCost(props.servicePeriodId).then(response => {
    costData.value = response.data;
    employeeCosts.value = response.data.employeeCosts || [];
    loading.value = false;
    
    // 更新图表
    nextTick(() => {
      initCharts();
    });
  }).catch(() => {
    loading.value = false;
  });
}

/** 刷新成本数据 */
function refreshCostData() {
  getCostData();
}

/** 计算成本占比 */
function calculateCostPercentage(cost) {
  if (!costData.value.totalCost || costData.value.totalCost === 0) {
    return 0;
  }
  return Math.round((cost / costData.value.totalCost) * 100);
}

/** 获取进度条颜色 */
function getProgressColor(percentage) {
  if (percentage < 30) return '#67c23a';
  if (percentage < 60) return '#e6a23c';
  return '#f56c6c';
}

/** 计算单个员工成本 */
function handleCalculateEmployeeCost(row) {
  calculateEmployeeCost(row.employeeId, row.workDays, 'DAILY').then(response => {
    proxy.$modal.msgSuccess(`员工${row.employeeId}成本计算完成：¥${response.data}`);
    getCostData();
  });
}

/** 调整成本 */
function handleAdjustCost(row) {
  costAdjustForm.value = {
    employeeId: row.employeeId,
    currentCost: row.totalCost,
    adjustedCost: row.totalCost,
    adjustReason: ''
  };
  costAdjustDialogVisible.value = true;
}

/** 提交成本调整 */
function submitCostAdjustment() {
  proxy.$refs["costAdjustFormRef"].validate(valid => {
    if (valid) {
      // 这里应该调用成本调整的API
      proxy.$modal.msgSuccess("成本调整成功");
      costAdjustDialogVisible.value = false;
      getCostData();
    }
  });
}

/** 批量成本计算 */
function handleBatchCostCalculation() {
  batchCalculationDialogVisible.value = true;
}

/** 批量计算完成 */
function handleBatchCalculationComplete() {
  batchCalculationDialogVisible.value = false;
  getCostData();
}

/** 导出成本报表 */
function exportCostReport() {
  // 这里应该调用导出API
  proxy.$modal.msgSuccess("报表导出成功");
}

/** 初始化图表 */
function initCharts() {
  initPieChart();
  initBarChart();
}

/** 初始化饼图 */
function initPieChart() {
  if (pieChartInstance) {
    pieChartInstance.dispose();
  }
  
  pieChartInstance = echarts.init(costPieChart.value);
  
  const pieData = employeeCosts.value.map(item => ({
    name: `员工${item.employeeId}`,
    value: item.totalCost
  }));
  
  const pieOption = {
    title: {
      text: '员工成本分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: ¥{c} ({d}%)'
    },
    series: [
      {
        name: '成本分布',
        type: 'pie',
        radius: '50%',
        data: pieData,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  };
  
  pieChartInstance.setOption(pieOption);
}

/** 初始化柱状图 */
function initBarChart() {
  if (barChartInstance) {
    barChartInstance.dispose();
  }
  
  barChartInstance = echarts.init(costBarChart.value);
  
  const barData = employeeCosts.value.map(item => item.totalCost);
  const xAxisData = employeeCosts.value.map(item => `员工${item.employeeId}`);
  
  const barOption = {
    title: {
      text: '员工成本对比',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      formatter: '{a} <br/>{b}: ¥{c}'
    },
    xAxis: {
      type: 'category',
      data: xAxisData,
      axisLabel: {
        rotate: 45
      }
    },
    yAxis: {
      type: 'value',
      name: '成本(元)'
    },
    series: [
      {
        name: '员工成本',
        type: 'bar',
        data: barData,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#83bff6' },
            { offset: 0.5, color: '#188df0' },
            { offset: 1, color: '#188df0' }
          ])
        }
      }
    ]
  };
  
  barChartInstance.setOption(barOption);
}

onMounted(() => {
  getCostData();
});

onUnmounted(() => {
  if (pieChartInstance) {
    pieChartInstance.dispose();
  }
  if (barChartInstance) {
    barChartInstance.dispose();
  }
});
</script>

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

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

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

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

.cost-item {
  text-align: center;
  padding: 20px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  background-color: #fafafa;
}

.cost-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
}

.cost-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

.total-cost {
  color: #e6a23c;
}

.cost-highlight {
  font-weight: bold;
  color: #409eff;
}
</style>