<template>
  <el-card class="table-card">
    <template #header>
      <div class="card-header">
        <span class="title">其他费用预算表</span>
        <div class="flex items-center gap-2">
          <span style="white-space: nowrap">行数:</span>
          <el-input-number v-model="addRowCount" :min="1" :max="10" size="small" style="width: 80px" />
          <el-button type="primary" size="small" @click="handleAddRows">
            <el-icon>
              <Plus />
            </el-icon>
            添加</el-button>
          <el-button type="danger" size="small" @click="handleBatchDelete" :disabled="selectedRows.length === 0">
            <el-icon>
              <Delete />
            </el-icon>
            删除 </el-button>
        </div>
      </div>
    </template>

    <!-- 表格 -->
    <el-table :data="otherCostList" border style="width: 100%" :summary-method="getSummaries" show-summary @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />

      <!-- 预算成本 -->
      <el-table-column label="预算成本" align="center">
        <el-table-column prop="sortOrder" label="序号" width="80" align="center" />
        <el-table-column prop="itemDesc" label="项目" width="200">
          <template #default="scope">
            <el-select v-model="scope.row.itemDesc" placeholder="请选择项目" clearable filterable allow-create>
              <el-option v-for="dict in budget_other_item" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="price" label="金额(元)" width="160">
          <template #default="scope">
            <el-input-number v-model="scope.row.price" :min="0" :precision="2" size="small" />
          </template>
        </el-table-column>
      </el-table-column>

      <!-- 降成本后预算成本 -->
      <el-table-column label="降成本后预算成本" align="center">
        <el-table-column prop="reduceItemDesc" label="项目" width="200">
          <template #default="scope">
            <el-select v-model="scope.row.reduceItemDesc" placeholder="请选择项目" clearable filterable allow-create>
              <el-option v-for="dict in budget_other_item" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="reducePrice" label="金额(元)" width="160">
          <template #default="scope">
            <el-input-number v-model="scope.row.reducePrice" :min="0" :precision="2" size="small" />
          </template>
        </el-table-column>
      </el-table-column>

      <el-table-column prop="reduceProposal" label="降成本方案" min-width="200">
        <template #default="scope">
          <el-input v-model="scope.row.reduceProposal" type="textarea" :rows="2" />
        </template>
      </el-table-column>

      <el-table-column label="操作" width="80" align="center">
        <template #default="scope">
          <el-button type="danger" size="small" @click="handleDelete(scope.$index, scope.row)" icon="Delete">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加行数弹窗 -->
    <el-dialog v-model="showAddDialog" title="添加行数" width="400px">
      <el-form>
        <el-form-item label="添加行数">
          <el-input-number v-model="addRowCount" :min="1" :max="10" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddDialog = false">取消</el-button>
        <el-button type="primary" @click="handleAddRows">确定</el-button>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { budgetOtherCostVO } from '@/api/oa/erp/budgetInfo/market/budgetOtherCost/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { budget_other_item } = toRefs<any>(proxy?.useDict('budget_other_item'));

const loaded = ref(false);

// 其他费用数据
const otherCostList = ref<budgetOtherCostVO[]>([]);
const toDeletedOtherCostIdList = ref([]);

// 选中的行
const selectedRows = ref([]);

// 添加行弹窗
const showAddDialog = ref(false);
const addRowCount = ref(1);

// 格式化数字
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 formatBudgetAmount = (row: any) => {
  const value = parseFloat(row.price) || 0;
  row.price = value;
};

// 格式化降成本后金额
const formatReducedAmount = (row: any) => {
  const value = parseFloat(row.reducePrice) || 0;
  row.reducePrice = value;
};

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

// 添加行
const handleAddRows = () => {
  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++) {
    otherCostList.value.push({
      sortOrder: currentSortOrder + i + 1,
      itemDesc: '',
      price: 0,
      reduceItemDesc: '',
      reducePrice: 0,
      reduceProposal: ''
    });
  }
};

// 删除单行
const handleDelete = (index: number, row: budgetOtherCostVO) => {
  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((row) => {
    if (row.otherCostId) {
      toDeletedOtherCostIdList.value.push(row.otherCostId);
    }
  });

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

// 合计方法
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' || column.property === 'reducePrice') {
      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] = sums[index].toFixed(2);
      } else {
        sums[index] = '';
      }
    } else {
      sums[index] = '';
    }
  });
  return sums;
};

// 获取总金额（供父组件调用）
const getTotalAmount = () => {
  const totalBudgetAmount = otherCostList.value.reduce((sum, item) => sum + Number(item.price), 0);
  const totalReducedAmount = otherCostList.value.reduce((sum, item) => sum + Number(item.reducePrice), 0);
  return {
    budgetAmount: totalBudgetAmount,
    reducedAmount: totalReducedAmount
  };
};

// 暴露方法给父组件
defineExpose({
  getTotalAmount,
  otherCostList,
  toDeletedOtherCostIdList
});
</script>

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

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

.title {
  text-align: center;
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 20px;
}

.actions {
  margin-bottom: 20px;
}

.actions .el-button {
  margin-right: 10px;
}
</style>
