<script setup lang="ts">
import { ElMessage } from 'element-plus';
import { computed, onMounted, ref } from 'vue';
import { http } from '../api/http';

interface BillingCostItem {
  operation: string;
  label: string;
  cost: number;
}

const loading = ref(false);
const saving = ref(false);
const rows = ref<BillingCostItem[]>([]);

const costs = computed(() =>
  Object.fromEntries(rows.value.map((item) => [item.operation, Number(item.cost || 0)])),
);

async function load() {
  loading.value = true;
  try {
    rows.value = await http.get<BillingCostItem[]>('/billing/costs');
  } finally {
    loading.value = false;
  }
}

async function save() {
  const invalid = rows.value.find((item) => item.cost == null || Number(item.cost) < 0);
  if (invalid) {
    ElMessage.warning(`${invalid.label || invalid.operation} 的价格不能小于 0`);
    return;
  }
  saving.value = true;
  try {
    rows.value = await http.put<BillingCostItem[]>('/billing/costs', { costs: costs.value });
    ElMessage.success('计费价格已保存，新请求将按新价格扣费');
  } finally {
    saving.value = false;
  }
}

onMounted(load);
</script>

<template>
  <div>
    <div class="page-head">
      <div>
        <h1>计费价格</h1>
        <p>配置客户端生成、提取、合成等操作的积分单价。保存后立即影响新的计费请求。</p>
      </div>
      <el-button type="primary" :loading="saving" @click="save">保存配置</el-button>
    </div>

    <div class="panel">
      <el-alert
        class="mb-4"
        type="info"
        show-icon
        :closable="false"
        title="这里只修改运行时计费价格，不会改历史账单。余额预检和实际扣费都会读取同一份价格。"
      />

      <el-table v-loading="loading" :data="rows" border>
        <el-table-column prop="label" label="操作" min-width="160" />
        <el-table-column prop="operation" label="计费 Key" min-width="220" />
        <el-table-column label="积分单价" width="220">
          <template #default="{ row }">
            <el-input-number v-model="row.cost" :min="0" :precision="2" :step="1" controls-position="right" />
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>
