<template>
  <div class="employee-management">
    <div class="employee-assignment">
      <!-- 操作按钮 -->
      <div class="mb-4">
        <el-row :gutter="10">
          <el-col :span="4">
            <el-button type="primary" icon="Plus" @click="handleAddEmployee">添加员工</el-button>
          </el-col>
          <el-col :span="4">
            <el-button type="success" icon="Upload" @click="handleBatchSelect">批量选择</el-button>
          </el-col>
          <el-col :span="4">
            <el-button type="warning" icon="Money" @click="handleBatchAdjustSalary">批量调薪</el-button>
          </el-col>
          <el-col :span="4">
            <el-button type="danger" icon="Delete" @click="handleBatchRemove" :disabled="selectedEmployees.length === 0">
              批量移除 ({{ selectedEmployees.length }})
            </el-button>
          </el-col>
          <el-col :span="4">
            <el-button type="info" icon="Refresh" @click="handleRecalculateCost">重新计算成本</el-button>
          </el-col>
        </el-row>
      </div>

        <el-table v-loading="loading" :data="employeeList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="员工ID" align="center" prop="employeeId" />
          <el-table-column label="分配岗位" align="center" prop="assignedPosition" />
          <el-table-column label="工作天数" align="center" prop="workDays" />
          <el-table-column label="原始薪资" align="center" min-width="120">
            <template #default="scope">
              <span v-if="scope.row.monthlySalary && scope.row.monthlySalary > 0">
                ¥{{ (scope.row.monthlySalary || 0).toFixed(2) }} (月薪)
              </span>
              <span v-else-if="scope.row.dailySalary && scope.row.dailySalary > 0">
                ¥{{ (scope.row.dailySalary || 0).toFixed(2) }} (日薪)
              </span>
              <span v-else-if="scope.row.hourlySalary && scope.row.hourlySalary > 0">
                ¥{{ (scope.row.hourlySalary || 0).toFixed(2) }} (时薪)
              </span>
              <span v-else>
                ¥{{ (scope.row.monthlySalary || 0).toFixed(2) }} (月薪)
              </span>
            </template>
          </el-table-column>
          <el-table-column label="日薪资" align="center" min-width="100">
            <template #default="scope">
              <span class="daily-salary">¥{{ (scope.row.assignedSalary || 0).toFixed(2) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="总薪资" align="center" min-width="100">
            <template #default="scope">
              <span class="total-salary">¥{{ (scope.row.totalCost || 0).toFixed(2) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="分配状态" align="center" prop="assignmentStatus">
            <template #default="scope">
              <dict-tag :options="assignment_status" :value="scope.row.assignmentStatus"/>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" min-width='150'>
            <template #default="scope">
              <el-button link type="primary" icon="Edit" @click="handleEditEmployee(scope.row)">编辑</el-button>
              <el-button link type="warning" icon="Money" @click="handleAdjustSalary(scope.row)">调薪</el-button>
              <el-button link type="danger" icon="Delete" @click="handleRemoveEmployee(scope.row)">移除</el-button>
            </template>
          </el-table-column>
        </el-table>
    </div>

    <!-- 添加/编辑员工对话框 -->
    <el-dialog :title="employeeDialogTitle" v-model="employeeDialogVisible" width="500px">
      <el-form ref="employeeFormRef" :model="employeeForm" :rules="employeeRules" label-width="100px">
        <el-form-item label="员工ID" prop="employeeId">
          <el-input v-model="employeeForm.employeeId" placeholder="请输入员工ID" />
        </el-form-item>
        <el-form-item label="分配岗位" prop="assignedPosition">
          <el-input v-model="employeeForm.assignedPosition" placeholder="请输入分配岗位" />
        </el-form-item>
        <el-form-item label="工作天数" prop="workDays">
          <el-input-number v-model="employeeForm.workDays" :min="1" placeholder="请输入工作天数" />
        </el-form-item>
        <el-form-item label="日薪资" prop="assignedSalary">
          <el-input-number 
            v-model="employeeForm.assignedSalary" 
            :precision="2" 
            :step="0.01"
            :min="0"
            placeholder="请输入日薪资" 
          />
        </el-form-item>
        <el-form-item label="分配状态" prop="assignmentStatus">
          <el-select v-model="employeeForm.assignmentStatus" placeholder="请选择分配状态">
            <el-option label="已分配" value="ASSIGNED" />
            <el-option label="活跃" value="ACTIVE" />
            <el-option label="已完成" value="COMPLETED" />
            <el-option label="已取消" value="CANCELLED" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitEmployeeForm">确 定</el-button>
          <el-button @click="employeeDialogVisible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 批量选择员工对话框 -->
    <el-dialog 
      title="批量选择员工" 
      v-model="batchSelectDialogVisible" 
      width="70%"
      @close="forceCloseBatchSelectDialog"
    >
      <batch-employee-selector 
        :service-period-id="servicePeriodId"
        @select-complete="handleBatchSelectComplete"
        @cancel="handleBatchSelectCancel"
      ></batch-employee-selector>
    </el-dialog>

    <!-- 薪资调整对话框 -->
    <el-dialog title="薪资调整" v-model="salaryDialogVisible" width="400px">
      <el-form ref="salaryFormRef" :model="salaryForm" :rules="salaryRules" label-width="100px">
        <el-form-item label="员工ID" prop="employeeId">
          <el-input v-model="salaryForm.employeeId" disabled />
        </el-form-item>
        <el-form-item label="调整后薪资" prop="adjustedSalary">
          <el-input-number 
            v-model="salaryForm.adjustedSalary" 
            :precision="2" 
            :step="0.01"
            :min="0"
            placeholder="请输入调整后薪资" 
          />
        </el-form-item>
        <el-form-item label="薪资类型" prop="salaryType">
          <el-select v-model="salaryForm.salaryType" placeholder="请选择薪资类型">
            <el-option label="小时制" value="HOURLY" />
            <el-option label="日薪制" value="DAILY" />
            <el-option label="月薪制" value="MONTHLY" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitSalaryAdjustment">确 定</el-button>
          <el-button @click="salaryDialogVisible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 批量调薪对话框 -->
    <el-dialog 
      title="批量调薪" 
      v-model="batchSalaryDialogVisible" 
      width="60%"
      @close="handleBatchSalaryDialogClose"
    >
      <batch-salary-adjuster 
        :service-period-id="servicePeriodId"
        :selected-employees="selectedEmployees"
        @adjust-complete="handleBatchSalaryComplete"
      ></batch-salary-adjuster>
    </el-dialog>
  </div>
</template>

<script setup>
import { 
  getServicePeriodEmployees, 
  addServicePeriodEmployee, 
  updateServicePeriodEmployee, 
  removeServicePeriodEmployee,
  batchRemoveServicePeriodEmployees,
  clearAllServicePeriodEmployees,
  adjustSalaryStandard,
  recalculateTotalCost
} from "@/api/digitalCredit/contractEmployee";
import BatchEmployeeSelector from "./BatchEmployeeSelector.vue";
import BatchSalaryAdjuster from "./BatchSalaryAdjuster.vue";

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

const emit = defineEmits(['close', 'employee-changed']);

const { proxy } = getCurrentInstance();
const { assignment_status } = proxy.useDict('assignment_status');

const loading = ref(false);
const employeeList = ref([]);
const selectedEmployees = ref([]);

// 对话框状态
const employeeDialogVisible = ref(false);
const batchSelectDialogVisible = ref(false);
const salaryDialogVisible = ref(false);
const batchSalaryDialogVisible = ref(false);
const employeeDialogTitle = ref('');

// 表单数据
const employeeForm = ref({
  employeeId: null,
  assignedPosition: '',
  workDays: 1,
  assignedSalary: 0,
  assignmentStatus: 'ASSIGNED'
});

const salaryForm = ref({
  employeeId: null,
  adjustedSalary: 0,
  salaryType: 'DAILY'
});

// 表单验证规则
const employeeRules = {
  employeeId: [{ required: true, message: "员工ID不能为空", trigger: "blur" }],
  assignedPosition: [{ required: true, message: "分配岗位不能为空", trigger: "blur" }],
  workDays: [{ required: true, message: "工作天数不能为空", trigger: "blur" }],
  assignedSalary: [{ required: true, message: "日薪资不能为空", trigger: "blur" }]
};

const salaryRules = {
  adjustedSalary: [{ required: true, message: "调整后薪资不能为空", trigger: "blur" }],
  salaryType: [{ required: true, message: "薪资类型不能为空", trigger: "change" }]
};



/** 获取员工列表 */
function getEmployeeList() {
  loading.value = true;
  getServicePeriodEmployees(props.servicePeriodId).then(response => {
    employeeList.value = response.data;
    loading.value = false;
    // 通知父组件员工数据已更新
    emit('employee-changed');
  }).catch(error => {
    console.error('获取员工列表失败:', error);
    loading.value = false;
    proxy.$modal.msgError("获取员工列表失败");
  });
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  selectedEmployees.value = selection;
}

/** 添加员工 */
function handleAddEmployee() {
  employeeForm.value = {
    employeeId: null,
    assignedPosition: '',
    workDays: 1,
    assignedSalary: 0,
    assignmentStatus: 'ASSIGNED'
  };
  employeeDialogTitle.value = '添加员工';
  employeeDialogVisible.value = true;
}

/** 编辑员工 */
function handleEditEmployee(row) {
  employeeForm.value = { ...row };
  employeeDialogTitle.value = '编辑员工';
  employeeDialogVisible.value = true;
}

/** 提交员工表单 */
function submitEmployeeForm() {
  proxy.$refs["employeeFormRef"].validate(valid => {
    if (valid) {
      const formData = {
        servicePeriodId: props.servicePeriodId,
        ...employeeForm.value
      };
      
      if (employeeForm.value.assignmentId) {
        updateServicePeriodEmployee(formData).then(() => {
          proxy.$modal.msgSuccess("修改成功");
          employeeDialogVisible.value = false;
        });
      } else {
        addServicePeriodEmployee(formData).then(() => {
          proxy.$modal.msgSuccess("添加成功");
          employeeDialogVisible.value = false;
        });
      }
      getEmployeeList();
    }
  });
}

/** 批量选择 */
function handleBatchSelect() {
  batchSelectDialogVisible.value = true;
}

/** 批量选择完成 */
function handleBatchSelectComplete(eventData) {
  const { employeeCount, workDays } = eventData || {};
  
  // 显示适合独立员工管理对话框的提示
  proxy.$modal.msgSuccess(`员工分配成功！已为 ${employeeCount} 名员工分配 ${workDays} 天工作任务。`);
  
  batchSelectDialogVisible.value = false;
  
  // 清除选择的数据
  selectedEmployees.value = [];
  
  console.log('批量选择完成，开始刷新员工列表');
  // 添加一个小延迟确保后端数据已经保存
  setTimeout(() => {
    getEmployeeList();
  }, 500);
}

/** 批量选择取消 */
function handleBatchSelectCancel() {
  batchSelectDialogVisible.value = false;
  
  // 清除选择的数据
  selectedEmployees.value = [];
}

/** 强制关闭批量选择对话框 */
function forceCloseBatchSelectDialog() {
  batchSelectDialogVisible.value = false;
  
  // 清除选择的数据
  selectedEmployees.value = [];
}

/** 调整薪资 */
function handleAdjustSalary(row) {
  salaryForm.value = {
    employeeId: row.employeeId,
    adjustedSalary: row.assignedSalary,
    salaryType: 'DAILY'
  };
  salaryDialogVisible.value = true;
}

/** 提交薪资调整 */
function submitSalaryAdjustment() {
  proxy.$refs["salaryFormRef"].validate(valid => {
    if (valid) {
      adjustSalaryStandard(props.servicePeriodId, salaryForm.value).then(() => {
        proxy.$modal.msgSuccess("薪资调整成功");
        salaryDialogVisible.value = false;
        getEmployeeList();
      });
    }
  });
}

/** 批量调薪 */
function handleBatchAdjustSalary() {
  if (selectedEmployees.value.length === 0) {
    proxy.$modal.msgWarning("请先选择要调薪的员工");
    return;
  }
  batchSalaryDialogVisible.value = true;
}

/** 批量调薪完成 */
function handleBatchSalaryComplete() {
  batchSalaryDialogVisible.value = false;
  
  // 清除选择的数据
  selectedEmployees.value = [];
  
  getEmployeeList();
}

/** 批量调薪对话框关闭 */
function handleBatchSalaryDialogClose() {
  // 清除选择的数据
  selectedEmployees.value = [];
}

/** 移除员工 */
function handleRemoveEmployee(row) {
  proxy.$modal.confirm('是否确认移除该员工？').then(() => {
    return removeServicePeriodEmployee(row.assignmentId);
  }).then(() => {
    getEmployeeList();
    proxy.$modal.msgSuccess("移除成功");
    // 通知父组件刷新服务周期列表
    emit('employee-changed');
  }).catch(() => {});
}

/** 重新计算成本 */
function handleRecalculateCost() {
  recalculateTotalCost(props.servicePeriodId).then(response => {
    proxy.$modal.msgSuccess(`重新计算完成，总成本：¥${parseFloat(response.data).toFixed(2)}`);
    getEmployeeList();
  });
}

/** 获取原始薪资显示 */
function getOriginalSalary(employee) {
  // 根据薪资类型返回对应的原始薪资值
  if (employee.monthlySalary && employee.monthlySalary > 0) {
    return (employee.monthlySalary || 0).toFixed(2);
  } else if (employee.dailySalary && employee.dailySalary > 0) {
    return (employee.dailySalary || 0).toFixed(2);
  } else if (employee.hourlySalary && employee.hourlySalary > 0) {
    return (employee.hourlySalary || 0).toFixed(2);
  } else {
    // 如果没有明确的薪资类型，返回月薪
    return (employee.monthlySalary || 0).toFixed(2);
  }
}

/** 批量移除员工 */
function handleBatchRemove() {
  if (selectedEmployees.value.length === 0) {
    proxy.$modal.msgWarning("请先选择要移除的员工");
    return;
  }
  
  const employeeCount = selectedEmployees.value.length;
  const employeeNames = selectedEmployees.value.map(emp => `员工ID: ${emp.employeeId}`).join(', ');
  
  proxy.$modal.confirm(`确认要移除选中的 ${employeeCount} 名员工吗？\n${employeeNames}`, '批量移除确认', {
    confirmButtonText: '确定移除',
    cancelButtonText: '取消',
    type: 'warning',
    dangerouslyUseHTMLString: true
  }).then(() => {
    // 使用批量删除API
    const assignmentIds = selectedEmployees.value.map(employee => employee.assignmentId);
    
    batchRemoveServicePeriodEmployees(props.servicePeriodId, {
      assignmentIds: assignmentIds
    }).then(response => {
      const result = response.data;
      if (result.success) {
        proxy.$modal.msgSuccess(`成功移除 ${result.successCount} 名员工`);
      } else {
        proxy.$modal.msgWarning(`移除完成：成功 ${result.successCount} 个，失败 ${result.errors.length} 个`);
      }
      getEmployeeList();
      // 清空选择
      selectedEmployees.value = [];
      // 通知父组件刷新服务周期列表
      emit('employee-changed');
    }).catch(error => {
      proxy.$modal.msgError(`批量移除失败: ${error.message}`);
      getEmployeeList();
    });
  }).catch(() => {
    // 用户取消操作
  });
}

/** 一键清空所有员工 */
function handleRemoveAll() {
  if (employeeList.value.length === 0) {
    proxy.$modal.msgWarning("当前没有员工需要清空");
    return;
  }
  
  const totalCount = employeeList.value.length;
  
  proxy.$modal.confirm(
    `确认要清空当前服务周期的所有 ${totalCount} 名员工吗？\n此操作不可恢复！`, 
    '一键清空确认', 
    {
      confirmButtonText: '确定清空',
      cancelButtonText: '取消',
      type: 'error',
      dangerouslyUseHTMLString: true
    }
  ).then(() => {
    // 使用清空所有员工API
    clearAllServicePeriodEmployees(props.servicePeriodId).then(response => {
      const result = response.data;
      if (result.success) {
        proxy.$modal.msgSuccess(`成功清空所有 ${result.successCount} 名员工`);
      } else {
        proxy.$modal.msgError(`清空失败: ${result.message}`);
      }
      getEmployeeList();
      // 清空选择
      selectedEmployees.value = [];
      // 通知父组件刷新服务周期列表
      emit('employee-changed');
    }).catch(error => {
      proxy.$modal.msgError(`清空操作失败: ${error.message}`);
      getEmployeeList();
    });
  }).catch(() => {
    // 用户取消操作
  });
}

onMounted(() => {
  getEmployeeList();
});
</script>

<style scoped>
.employee-management {
  padding: 20px;
}

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

.daily-salary {
  font-weight: bold;
  color: #67c23a;
}

.total-salary {
  font-weight: bold;
  color: #409eff;
}

.calculated-salary {
  font-weight: bold;
  color: #409eff;
}

.salary-preview {
  margin: 10px 0;
}

.salary-breakdown {
  font-size: 14px;
  line-height: 1.5;
}

.salary-breakdown p {
  margin: 5px 0;
}
</style>