<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="installCostList"
      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="60" align="center" />
        <el-table-column prop="type" label="类型" width="120">
          <template #default="scope">
            <el-select v-model="scope.row.installType" placeholder="请选择类型" clearable @change="handleTypeChange(scope.row)">
              <el-option v-for="dict in install_type" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="personnelCategory" label="人员类别" width="150">
          <template #default="scope">
            <el-input v-model="scope.row.personnelCategory" placeholder="请输入人员类别" />
          </template>
        </el-table-column>
        <el-table-column prop="peopleNumber" label="人数" width="120">
          <template #default="scope">
            <el-input-number v-if="scope.row.installType === INSTALL_TYPE.NON_CONTRACT" v-model="scope.row.peopleNumber" :min="0" :precision="0" size="small" @change="calculateBudgetAmount(scope.row)" style="width:106px;"/>
            <span v-else></span>
          </template>
        </el-table-column>
        <el-table-column prop="cumulativeTime" label="累计时间(月)" width="120">
          <template #default="scope">
            <el-input-number v-if="scope.row.installType === INSTALL_TYPE.NON_CONTRACT" v-model="scope.row.cumulativeTime" :min="0" :precision="2" size="small" @change="calculateBudgetAmount(scope.row)" style="width:106px;"/>
            <span v-else></span>
          </template>
        </el-table-column>
        <el-table-column prop="monthRate" label="月平均投入比例(%)" width="150">
          <template #default="scope">
            <el-input-number v-if="scope.row.installType === INSTALL_TYPE.NON_CONTRACT" v-model="scope.row.monthRate" :min="0" :max="100" :precision="2" size="small" @change="calculateBudgetAmount(scope.row)" style="width:136px;"/>
            <span v-else></span>
          </template>
        </el-table-column>
        <el-table-column prop="artificialStandard" label="人工标准(元/人月)" width="150">
          <template #default="scope">
            <el-input-number v-if="scope.row.installType === INSTALL_TYPE.NON_CONTRACT" v-model="scope.row.artificialStandard" :min="0" :precision="2" :step="10" size="small" @change="calculateBudgetAmount(scope.row)" style="width:136px;"/>
            <span v-else></span>
          </template>
        </el-table-column>
        <el-table-column prop="price" label="金额(元)" width="150">
          <template #default="scope">
            <el-input-number v-if="scope.row.installType === INSTALL_TYPE.CONTRACT" v-model="scope.row.price" :min="0" :precision="2" size="small" style="width:136px;"/>
            <span v-else>{{ formatNumber(scope.row.price) }}</span>
          </template>
        </el-table-column>
      </el-table-column>

      <!-- 降成本后预算成本 -->
      <el-table-column label="降成本后预算成本" align="center">
        <el-table-column prop="reducePersonnelCategory" label="人员类别" width="150">
          <template #default="scope">
            <el-input v-model="scope.row.reducePersonnelCategory" placeholder="请输入人员类别" />
          </template>
        </el-table-column>
        <el-table-column prop="reducePeopleNumber" label="人数" width="120">
          <template #default="scope">
            <el-input-number v-if="scope.row.installType === INSTALL_TYPE.NON_CONTRACT" v-model="scope.row.reducePeopleNumber" :min="0" :precision="0" size="small" @change="calculateReducedAmount(scope.row)" style="width:106px;"/>
            <span v-else></span>
          </template>
        </el-table-column>
        <el-table-column prop="reduceCumulativeTime" label="累计时间(月)" width="120">
          <template #default="scope">
            <el-input-number v-if="scope.row.installType === INSTALL_TYPE.NON_CONTRACT" v-model="scope.row.reduceCumulativeTime" :min="0" :precision="2" size="small" @change="calculateReducedAmount(scope.row)" style="width:106px;"/>
            <span v-else></span>
          </template>
        </el-table-column>
        <el-table-column prop="reduceMonthRate" label="月平均投入比例(%)" width="150">
          <template #default="scope">
            <el-input-number v-if="scope.row.installType === INSTALL_TYPE.NON_CONTRACT" v-model="scope.row.reduceMonthRate" :min="0" :max="100" :precision="2" size="small" @change="calculateReducedAmount(scope.row)" style="width:136px;"/>
            <span v-else></span>
          </template>
        </el-table-column>
        <el-table-column prop="reduceArtificialStandard" label="人工标准(元/人月)" width="150">
          <template #default="scope">
            <el-input-number v-if="scope.row.installType === INSTALL_TYPE.NON_CONTRACT" v-model="scope.row.reduceArtificialStandard" :min="0" :precision="2" :step="10" size="small" @change="calculateReducedAmount(scope.row)" style="width:136px;"/>
            <span v-else></span>
          </template>
        </el-table-column>
        <el-table-column prop="reducePrice" label="金额(元)" width="150">
          <template #default="scope">
            <el-input-number v-if="scope.row.installType === INSTALL_TYPE.CONTRACT" v-model="scope.row.reducePrice" :min="0" :precision="2" size="small" style="width:136px;"/>
            <span v-else>{{ formatNumber(scope.row.reducePrice) }}</span>
          </template>
        </el-table-column>
      </el-table-column>

      <el-table-column prop="reduceProposal" label="降成本方案" 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 { budgetInstallCostVO } from '@/api/oa/erp/budgetInfo/market/budgetInstallCost/types';

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

const INSTALL_TYPE = {
  NON_CONTRACT: '1', //非承包
  CONTRACT: '2' //承包
}
// 安装费数据
const installCostList = ref<budgetInstallCostVO[]>([]);
const toDeletedInstallCostIdList = ref([]);

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

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

// 人员类别选项
const personnelCategories = ref([
  { label: '项目经理', value: '项目经理' },
  { label: '技术经理', value: '技术经理' },
  { label: '工程师', value: '工程师' },
  { label: '技术员', value: '技术员' },
  { label: '施工员', value: '施工员' },
  { label: '质检员', value: '质检员' },
  { label: '安全员', value: '安全员' },
  { label: '材料员', value: '材料员' },
  { label: '预算员', value: '预算员' },
  { label: '其他', value: '其他' }
])

// 格式化数字
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 handleTypeChange = (row: any) => {
  if (row.installType === INSTALL_TYPE.NON_CONTRACT) {
    // 非承包类型，重新计算金额
    calculateBudgetAmount(row)
  }
}

// 计算预算金额
const calculateBudgetAmount = (row: any) => {
  // 只有非承包类型才需要计算金额
  if (row.installType === INSTALL_TYPE.NON_CONTRACT) {
    const peopleNumber = parseFloat(row.peopleNumber) || 0
    const cumulativeTime = parseFloat(row.cumulativeTime) || 0
    const monthRate = parseFloat(row.monthRate) || 0
    const artificialStandard = parseFloat(row.artificialStandard) || 0

    row.price = peopleNumber * cumulativeTime * (monthRate / 100) * artificialStandard
  }
}

// 计算降成本后金额
const calculateReducedAmount = (row: any) => {
  if (row.installType === INSTALL_TYPE.NON_CONTRACT) {
    const peopleNumber = parseFloat(row.reducePeopleNumber) || 0
    const cumulativeTime = parseFloat(row.reduceCumulativeTime) || 0
    const monthRate = parseFloat(row.reduceMonthRate) || 0
    const artificialStandard = parseFloat(row.reduceArtificialStandard) || 0

    row.reducePrice = peopleNumber * cumulativeTime * (monthRate / 100) * artificialStandard
  }
}

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

// 添加行
const handleAddRows = () => {
  const currentSortOrder =
    installCostList.value && installCostList.value.length > 0
      ? Math.max(...installCostList.value.map((item) => item.sortOrder))
      : 0;
  for (let i = 0; i < addRowCount.value; i++) {
    installCostList.value.push({
      sortOrder: currentSortOrder + i + 1,
      installType: INSTALL_TYPE.NON_CONTRACT,
      personnelCategory: '',
      peopleNumber: 0,
      cumulativeTime: 0,
      monthRate: 0,
      artificialStandard: 0,
      price: 0,
      reducedPersonnelCategory: '',
      reducePeopleNumber: 0,
      reduceCumulativeTime: 0,
      reduceMonthRate: 0,
      reduceArtificialStandard: 0,
      reducePrice: 0,
      reduceProposal: ''
    })
  }
}

// 删除单行
const handleDelete = (index: number, row: budgetInstallCostVO) => {
  installCostList.value.splice(index, 1)
  // 重新编号
  installCostList.value.forEach((item, index) => {
    item.sortOrder = index + 1;
  });

  if(row.installCostId){
    toDeletedInstallCostIdList.value.push(row.installCostId);
  }
}

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

  selectedRows.value.forEach((row) => {
    if (row.installCostId) {
      toDeletedInstallCostIdList.value.push(row.installCostId);
    }
  });

  installCostList.value = installCostList.value.filter(item => !selectedRows.value.includes(item))
  // 重新编号
  installCostList.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] = formatNumber(sums[index])
      } else {
        sums[index] = ''
      }
    } else {
      sums[index] = ''
    }
  })
  return sums
}

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

// 暴露方法给父组件
defineExpose({
  getTotalAmount,
  installCostList,
  toDeletedInstallCostIdList
})
</script>

<style scoped>
.installation-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>
