<template>
  <div class="other-cost-container">
    <el-card>
      <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="addRowCount" :min="1" :max="100" :step="1" size="small" />
          <el-button type="primary" @click="confirmAdd" size="small">
            <el-icon>
              <Plus />
            </el-icon>
            添加
          </el-button>
          <el-button type="danger" @click="handleBatchDelete" size="small" :disabled="selectedRows.length === 0">
            <el-icon>
              <Delete />
            </el-icon>
            删除
          </el-button>
        </div>
      </div>

      <el-table
        v-loading="loading"
        :data="otherCostList"
        style="width: 100%"
        show-summary
        :summary-method="
          () => {
            const cols = ['', '', '合计(万元)', ''];
            cols[cols.length - 1] = formatNumber(totalAmount);
            return cols;
          }
        "
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" :selectable="checkSelectable" />
        <el-table-column prop="sortOrder" label="序号" width="80" type="index" />
        <el-table-column prop="itemDesc" label="费用项目" width="200">
          <template #default="scope">
            <el-input v-model="scope.row.itemDesc" placeholder="请输入项目名称" :data-row-index="scope.$index" :disabled="scope.row.sortOrder <= 7"/>
          </template>
        </el-table-column>
        <el-table-column prop="price" label="金额(万元)" width="180">
          <template #default="scope">
            <el-input-number v-model="scope.row.price" :min="0" :step="1" :precision="2" size="small" />
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="费用说明" min-width="200">
          <template #default="scope">
            <el-input v-model="scope.row.remark" placeholder="请输入费用说明" :data-row-index="scope.$index" />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="scope">
            <el-button type="danger" size="small" @click="handleDelete(scope.$index, scope.row)" icon="Delete" v-if="scope.row.sortOrder > 7">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

  </div>
</template>

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

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

// 响应式数据
const loading = ref(false);
// const otherCostList = ref<rdBudgetOtherCostVO[]>([]);
const selectedRows = ref<rdBudgetOtherCostVO[]>([]);
const addRowCount = ref(1);
const toDeletedOtherCostIdList = ref([]);

// 预算数据
const otherCostList = ref([
  { sortOrder: 1, itemDesc: '安装费' },
  { sortOrder: 2, itemDesc: '资料/文献费' },
  { sortOrder: 3, itemDesc: '会议费' },
  { sortOrder: 4, itemDesc: '劳务费' },
  { sortOrder: 5, itemDesc: '运输装卸费' },
  { sortOrder: 6, itemDesc: '中介代理费' },
  { sortOrder: 7, itemDesc: '其他费用' }
]);

const checkSelectable = (row: rdBudgetOtherCostVO, index: number) => {
  return row.sortOrder > 7;
};

// 格式化数字,元转换为万元
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 totalAmount = computed(() => {
  return otherCostList.value.reduce((sum, item) => sum + (Number(item.price) || 0), 0);
});

const getOtherCost = () => {
  return {
    otherTotal: (totalAmount.value || 0) * 10000
  };
};
// 添加行数功能已集成到界面上，无需单独的对话框打开方法

// 确认添加
const confirmAdd = () => {
  const currentSortOrder = otherCostList.value && otherCostList.value.length > 0 ? Math.max(...otherCostList.value.map((item) => item.sortOrder)) : 0;

  for (let i = 0; i < addRowCount.value; i++) {
    const newItem: rdBudgetOtherCostVO = {
      sortOrder: currentSortOrder + i + 1,
      itemDesc: '',
      price: 0
    };
    otherCostList.value.push(newItem);
  }

  // 滚动到表格底部
  setTimeout(() => {
    const tableElement = document.querySelector('.el-table__body-wrapper');
    if (tableElement) {
      tableElement.scrollTop = tableElement.scrollHeight;
    }

    // 聚焦到新添加行的第一个输入框
    const firstNewInput = document.querySelector(`[data-row-index="${currentSortOrder}"]`);
    if (firstNewInput) {
      (firstNewInput as HTMLInputElement).focus();
    }
  }, 100);

};

// 处理选择变化
const handleSelectionChange = (selection: rdBudgetOtherCostVO[]) => {
  selectedRows.value = selection;
};

// 删除单行
const handleDelete = (index: number, row: rdBudgetOtherCostVO) => {
  otherCostList.value.splice(index, 1);
  // 重新编号
  otherCostList.value.forEach((item, index) => {
    item.sortOrder = index + 1;
  });
  if (row.otherCostId) {
    toDeletedOtherCostIdList.value.push(row.otherCostId);
  }
};

// 批量删除
const handleBatchDelete = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要删除的行');
    return;
  }
  selectedRows.value.forEach((selectedRow) => {
    if (selectedRow.otherCostId) {
      toDeletedOtherCostIdList.value.push(selectedRow.otherCostId);
    }
  });

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

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

// 暴露方法供父组件调用
defineExpose({
  otherCostList,
  toDeletedOtherCostIdList,
  getOtherCost
});
</script>

<style scoped>
.other-cost-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-3 {
  padding: 12px;
}

.rounded {
  border-radius: 4px;
}

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

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