<template>
  <div class="page-container">
    <div class="page-header">
      <PageTitle title="分项费用类型明细" />
      <el-button type="danger" @click="handleBack">返回</el-button>
    </div>

    <el-table :data="itemDetailList" border>
      <el-table-column prop="deptName" label="部门名称" min-width="200" />
      <el-table-column prop="status" label="状态" min-width="100" align="center">
        <template #default="{ row }">
          <span :class="['status-text', row.status === '0' ? 'active' : '']">{{ row.status == '0' ? '启用' : '禁用' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="existingAmount" label="现有额度(年)" min-width="150" align="center">
        <template #default="{ row }">¥{{ (Number(row.existingAmount) || 0).toLocaleString() }}</template>
      </el-table-column>
      <el-table-column prop="usedQuota" label="已用额度(年)" min-width="150" align="center">
        <template #default="{ row }">¥{{ (Number(row.usedQuota) || 0).toLocaleString() }}</template>
      </el-table-column>
      <el-table-column prop="remainingAmount" label="剩余额度(年)" min-width="150" align="center">
        <template #default="{ row }">¥{{ (Number(row.remainingAmount) || 0).toLocaleString() }}</template>
      </el-table-column>
      <el-table-column label="操作" width="100" align="center">
        <template #default="{ row }">
          <el-button type="primary" link size="small" @click="handleRecharge(row)">充值额度</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog v-model="rechargeVisible" title="充值额度" width="450px" @close="resetRechargeForm">
      <el-form :model="rechargeForm" label-width="110px">
        <el-form-item label="分项费用名称">
          <el-input :model-value="expenseName" disabled />
        </el-form-item>
        <el-form-item label="充值部门">
          <el-input :model-value="rechargeForm.deptName" disabled />
        </el-form-item>
        <el-form-item label="充值额度" required>
          <el-input v-model="rechargeForm.amount" placeholder="请输入充值金额" type="number" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="rechargeVisible = false">取消</el-button>
        <el-button type="primary" @click="handleRechargeSubmit" :loading="rechargeLoading">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';
import { expenseDetail, rechargeLimit } from '@/api/pc/cost/itemExpense';

const router = useRouter();
const route = useRoute();
const itemDetailList = ref<any[]>([]);

const expenseName = ref('');
const rechargeVisible = ref(false);
const rechargeLoading = ref(false);
const rechargeForm = reactive({
  deptId: '',
  deptName: '',
  amount: ''
});

const handleRecharge = (row: any) => {
  expenseName.value = row.expenseName || '';
  rechargeForm.deptId = row.deptId || '';
  rechargeForm.deptName = row.deptName || '';
  rechargeForm.amount = '';
  rechargeVisible.value = true;
};

const resetRechargeForm = () => {
  rechargeForm.deptId = '';
  rechargeForm.deptName = '';
  rechargeForm.amount = '';
};

const handleRechargeSubmit = async () => {
  if (!rechargeForm.amount || Number(rechargeForm.amount) <= 0) {
    ElMessage.warning('请输入有效的充值金额');
    return;
  }
  rechargeLoading.value = true;
  try {
    const res = await rechargeLimit({
      deptId: rechargeForm.deptId,
      recharge: Number(rechargeForm.amount)
    });
    if (res.code === 200 || res.code === 0) {
      ElMessage.success('充值成功');
      rechargeVisible.value = false;
      loadDetail();
    } else {
      ElMessage.error(res.msg || '充值失败');
    }
  } catch (e) {
    console.error('充值失败:', e);
    ElMessage.error('充值失败');
  } finally {
    rechargeLoading.value = false;
  }
};

const loadDetail = async () => {
  const id = route.query.id as string;
  if (!id) return;
  try {
    const res = await expenseDetail(id);
    if (res.code === 200 || res.code === 0) {
      const data = res.data || res.rows || [];
      const list = Array.isArray(data) ? data : [data];
      itemDetailList.value = list.map((item: any) => {
        const existing = Number(item.existingAmount || item.creditAmount) || 0;
        const used = Number(item.usedQuota || item.usedAmount) || 0;
        return {
          id: item.id,
          deptId: item.deptId,
          deptName: item.deptName || '',
          expenseName: item.expenseName || '',
          status: item.status ?? '',
          existingAmount: existing,
          usedQuota: used,
          remainingAmount: existing - used
        };
      });
    }
  } catch (e) {
    console.error('查询费用明细失败:', e);
  }
};

const handleBack = () => {
  router.push({ path: '/cost/itemExpense' });
};

onMounted(() => {
  loadDetail();
});
</script>
<style scoped lang="scss">
.page-container {
  padding: 20px;
  background: #fff;
  min-height: 100%;
  flex: 1;
}
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;

  :deep(.page-title) {
    margin-bottom: 0;
  }
}
.page-title {
  font-size: 16px;
  font-weight: bold;
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 20px;
}
.title-bar {
  display: inline-block;
  width: 3px;
  height: 16px;
  background: #e60012;
  border-radius: 2px;
}
.search-bar {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 20px;
  .search-right {
    flex: 1;
    display: flex;
    justify-content: flex-end;
  }
}
.pagination-wrap {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  .total-text {
    font-size: 14px;
    color: #666;
  }
}
</style>
