<template>
  <div class="labor-service-container">
    <!-- 人工费预算明细表 -->
    <el-card class="mb-6">
      <div class="flex items-center justify-between mb-4">
        <h3 class="text-lg font-medium">人工费预算明细表</h3>
        <div class="flex items-center gap-2">
          <span class="text-sm" style="white-space: nowrap">行数:</span>
          <el-input-number v-model="laborAddRowCount" :min="1" :max="100" :step="1" size="small" />
          <el-button type="primary" @click="confirmLaborAdd" size="small">
            <el-icon>
              <Plus />
            </el-icon>
            添加
          </el-button>
          <el-button type="danger" @click="handleLaborBatchDelete" size="small" :disabled="selectedLaborRows.length === 0">
            <el-icon>
              <Delete />
            </el-icon>
            删除
          </el-button>
        </div>
      </div>

      <el-table
        v-loading="loading"
        :data="laborList"
        style="width: 100%"
        :summary-method="getSummaries"
        show-summary
        @selection-change="handleLaborSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="sortOrder" label="序号" width="80" align="center" />
        <el-table-column prop="personnelCategory" label="人员类别" width="150">
          <template #default="scope">
            <el-input v-model="scope.row.personnelCategory" placeholder="请输入人员类别" :data-row-index="scope.$index" />
          </template>
        </el-table-column>
        <el-table-column prop="peopleNumber" label="人数" width="130">
          <template #default="scope">
            <el-input-number v-model="scope.row.peopleNumber" :min="0" :step="1" :precision="0" size="small" @change="calculateLaborAmount" />
          </template>
        </el-table-column>
        <el-table-column prop="cumulativeTime" label="累计时间(月)" width="130">
          <template #default="scope">
            <el-input-number v-model="scope.row.cumulativeTime" :min="0" :step="1" :precision="2" size="small" @change="calculateLaborAmount" />
          </template>
        </el-table-column>
        <el-table-column prop="monthRate" label="人均投入比例(%)" width="150">
          <template #default="scope">
            <el-input-number v-model="scope.row.monthRate" :min="0" :max="100" :step="1" :precision="2" size="small" @change="calculateLaborAmount" />
          </template>
        </el-table-column>
        <el-table-column prop="artificialStandard" label="人工标准(元/人月)" width="150">
          <template #default="scope">
            <el-input-number v-model="scope.row.artificialStandard" :min="0" :step="10" :precision="2" size="small" @change="calculateLaborAmount" />
          </template>
        </el-table-column>
        <el-table-column prop="price" label="金额(万元)" width="120">
          <template #default="scope">
            {{ format2TenThousandNumber(scope.row.price) }}
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" min-width="200">
          <template #default="scope">
            <el-input v-model="scope.row.remark" placeholder="备注" type="textarea" :rows="2" />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="scope">
            <el-button type="danger" size="small" @click="handleLaborDelete(scope.$index, scope.row)" icon="Delete"> 删除 </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="mt-4 bg-gray-50 p-3 rounded text-left font-semibold">
        <p>注： 人工费的预算，人工标准，各项目组按照成员的大概平均工资水平进行估算。表格所给数据为建议参考数据。</p>
        <p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;人员类别，按照各项目实际情况填写。如，产品不在本公司内加工和组装的，生产加工费已经核算在外协件里，不再有生产加工费。</p>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue';
import { ElMessage } from 'element-plus';
import { rdBudgetLaborCostVO } from '@/api/oa/erp/budgetInfo/rd/rdBudgetLaborCost/types';

const LABOR_TYPE = {
  LABOR_FEE: '1', //人工费
  SERVICE_FEE: '2' //劳务费
};

// Props
const props = defineProps<{
  projectId?: string;
}>();

// Emits
const emit = defineEmits<{
  update: [
    data: {
      laborTotal: number;
    }
  ];
}>();

// 响应式数据
const loading = ref(false);

// 人工费相关
const laborList = ref<rdBudgetLaborCostVO[]>([]);
const selectedLaborRows = ref<rdBudgetLaborCostVO[]>([]);
const laborAddRowCount = ref(1);

const toDeletedLaborCostIdList = ref([]);

// const laborTotal = computed(() => {
//   return laborList.value.reduce((sum, item) => {
//     const amountInTenThousand = Number(item.price) || 0;
//     const formattedAmount = parseFloat(amountInTenThousand.toFixed(2));
//     return sum + formattedAmount;
//   }, 0);
// });

// 格式化数字,元转换为万元
const formatNumber = (value: number) => {
  if (!value) return '0.00';
  return parseFloat(value).toFixed(2);
};

// 格式化数字,元转换为万元
const format2TenThousandNumber = (value: number) => {
  if (!value) return '0.00';
  return (parseFloat(value) / 10000).toFixed(2);
};

// 合计方法
const getSummaries = (param: any) => {
  const { columns, data } = param;
  const sums: any[] = [];
  columns.forEach((column: any, index: number) => {
    if (index === 2) {
      sums[index] = '合计';
      return;
    }
    if (column.property === 'price') {
      const values = data.map((item: any) => Number(item[column.property]));
      if (!values.every((value: number) => Number.isNaN(value))) {
        sums[index] = values.reduce((prev: number, curr: number) => {
          const value = Number(curr);
          if (!Number.isNaN(value)) {
            return prev + curr;
          } else {
            return prev;
          }
        }, 0);
        sums[index] = format2TenThousandNumber(sums[index]);
      } else {
        sums[index] = '';
      }
    } else {
      sums[index] = '';
    }
  });
  return sums;
};

// 计算人工费金额
const calculateLaborAmount = () => {
  laborList.value.forEach((item) => {
    // 金额 = 人数 * 累计时间 * 月平均投入比例 * 人工标准 / 10000 / 100
    item.price = ((item.peopleNumber || 0) * (item.cumulativeTime || 0) * (item.monthRate || 0) * (item.artificialStandard || 0)) / 100;
  });
};

const getLaborAmount = () => {
  const laborTotal = laborList.value.reduce((sum, item) => sum + Number(item.price), 0)
  return {
    laborTotal: laborTotal
  };
};

// 人工费相关方法
const confirmLaborAdd = () => {
  const currentSortOrder = laborList.value && laborList.value.length > 0 ? Math.max(...laborList.value.map((item) => item.sortOrder)) : 0;

  for (let i = 0; i < laborAddRowCount.value; i++) {
    const newItem: rdBudgetLaborCostVO = {
      sortOrder: currentSortOrder + i + 1,
      laborType: LABOR_TYPE.LABOR_FEE,
      personnelCategory: '',
      peopleNumber: 1,
      cumulativeTime: 0,
      monthRate: 0,
      artificialStandard: 0,
      price: 0,
      remark: ''
    };
    laborList.value.push(newItem);
  }
};

const handleLaborSelectionChange = (selection: rdBudgetLaborCostVO[]) => {
  selectedLaborRows.value = selection;
};

// 删除单行
const handleLaborDelete = (index: number, row: rdBudgetLaborCostVO) => {
  laborList.value.splice(index, 1);
  // 重新编号
  laborList.value.forEach((item, index) => {
    item.sortOrder = index + 1;
  });
  if (row.laborCostId) {
    toDeletedLaborCostIdList.value.push(row.laborCostId);
  }
};

// 批量删除
const handleLaborBatchDelete = () => {
  if (selectedLaborRows.value.length === 0) {
    ElMessage.warning('请选择要删除的行');
    return;
  }
  selectedLaborRows.value.forEach((selectedRow) => {
    if (selectedRow.laborCostId) {
      toDeletedLaborCostIdList.value.push(selectedRow.laborCostId);
    }
  });

  laborList.value = laborList.value.filter((item) => !selectedLaborRows.value.includes(item));
  // 重新编号
  laborList.value.forEach((item, index) => {
    item.sortOrder = index + 1;
  });
  selectedLaborRows.value = [];
};

// 监听projectId变化，重新加载数据
watch(
  () => props.projectId,
  (newProjectId) => {
    if (newProjectId) {
    }
  },
  { immediate: true }
);

// 暴露方法供父组件调用
defineExpose({
  laborList,
  toDeletedLaborCostIdList,
  getLaborAmount
});
</script>

<style scoped>
.labor-service-container {
  padding: 0;
}

:deep(.el-table) {
  margin-bottom: 16px;
}

:deep(.el-input-number) {
  width: 100%;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.bg-gray-50 {
  background-color: #f5f7fa;
}

.p-2 {
  padding: 8px;
}

.p-3 {
  padding: 12px;
}

.rounded {
  border-radius: 4px;
}

.text-right {
  text-align: right;
}

.font-medium {
  font-weight: 500;
}

.font-semibold {
  font-weight: 600;
}
</style>
