<template>
  <div class="page-content">
    <div class="mb-5 flex items-start justify-between"><div><h2 class="text-xl font-semibold">模型价格</h2><p class="text-g-500 mt-1 text-sm">维护带生效时间的价格版本，调用成本按请求时刻和实际输入/输出 Token 核算</p></div><ElButton type="primary" @click="openCreate">新建价格</ElButton></div>
    <ElAlert class="mb-4" type="info" :closable="false" title="价格单位为每百万 Token 的货币金额；模型名支持精确匹配或末尾 * 前缀匹配，精确规则优先。" />
    <ElTable v-loading="loading" :data="items" row-key="id">
      <ElTableColumn prop="provider_code" label="Provider" min-width="130" /><ElTableColumn prop="model_pattern" label="模型" min-width="190" />
      <ElTableColumn label="输入 / 百万 Token" min-width="150"><template #default="{ row }">{{ money(row.input_microunits_per_million,row.currency) }}</template></ElTableColumn>
      <ElTableColumn label="输出 / 百万 Token" min-width="150"><template #default="{ row }">{{ money(row.output_microunits_per_million,row.currency) }}</template></ElTableColumn>
      <ElTableColumn label="生效时间" min-width="190"><template #default="{ row }">{{ formatTime(row.effective_from) }}</template></ElTableColumn><ElTableColumn label="失效时间" min-width="190"><template #default="{ row }">{{ row.effective_to ? formatTime(row.effective_to) : '长期有效' }}</template></ElTableColumn>
      <ElTableColumn label="状态" width="90"><template #default="{ row }"><ElTag :type="row.enabled?'success':'info'">{{ row.enabled?'启用':'停用' }}</ElTag></template></ElTableColumn>
      <ElTableColumn label="操作" width="150" fixed="right"><template #default="{ row }"><ElButton link type="primary" @click="openEdit(row)">编辑</ElButton><ElButton link type="danger" @click="remove(row)">删除</ElButton></template></ElTableColumn>
    </ElTable>
    <ElDialog v-model="visible" :title="editing?'编辑模型价格':'新建模型价格'" width="680px"><ElForm label-width="150px">
      <div class="grid grid-cols-2 gap-x-4"><ElFormItem label="Provider"><ElInput v-model="form.provider_code" placeholder="openai" /></ElFormItem><ElFormItem label="模型匹配"><ElInput v-model="form.model_pattern" placeholder="gpt-5 或 gpt-*" /></ElFormItem></div>
      <div class="grid grid-cols-2 gap-x-4"><ElFormItem label="输入金额 / 百万"><ElInputNumber v-model="inputPrice" :precision="6" :min="0" /></ElFormItem><ElFormItem label="输出金额 / 百万"><ElInputNumber v-model="outputPrice" :precision="6" :min="0" /></ElFormItem></div>
      <div class="grid grid-cols-2 gap-x-4"><ElFormItem label="货币"><ElInput v-model="form.currency" maxlength="3" /></ElFormItem><ElFormItem label="状态"><ElSwitch v-model="form.enabled" active-text="启用" /></ElFormItem></div>
      <ElFormItem label="生效时间"><ElDatePicker v-model="effectiveFrom" type="datetime" class="!w-full" /></ElFormItem><ElFormItem label="失效时间"><ElDatePicker v-model="effectiveTo" type="datetime" clearable class="!w-full" placeholder="留空表示长期有效" /></ElFormItem>
    </ElForm><template #footer><ElButton @click="visible=false">取消</ElButton><ElButton type="primary" :loading="saving" @click="save">保存</ElButton></template></ElDialog>
  </div>
</template>
<script setup lang="ts">
  import { ModelPrice, ModelPriceInput, createModelPrice, deleteModelPrice, fetchModelPrices, updateModelPrice } from '@/api/pricing'
  import { ElMessage, ElMessageBox } from 'element-plus'
  const loading=ref(false),saving=ref(false),visible=ref(false),editing=ref('');const items=ref<ModelPrice[]>([]);const form=reactive<ModelPriceInput>({provider_code:'',model_pattern:'',input_microunits_per_million:0,output_microunits_per_million:0,currency:'USD',effective_from:'',effective_to:null,enabled:true});const inputPrice=ref(0),outputPrice=ref(0),effectiveFrom=ref<Date>(new Date()),effectiveTo=ref<Date|null>(null)
  async function load(){loading.value=true;try{items.value=await fetchModelPrices()}finally{loading.value=false}}
  function openCreate(){editing.value='';Object.assign(form,{provider_code:'',model_pattern:'',currency:'USD',enabled:true});inputPrice.value=0;outputPrice.value=0;effectiveFrom.value=new Date();effectiveTo.value=null;visible.value=true}
  function openEdit(row:ModelPrice){editing.value=row.id;Object.assign(form,{provider_code:row.provider_code,model_pattern:row.model_pattern,input_microunits_per_million:row.input_microunits_per_million,output_microunits_per_million:row.output_microunits_per_million,currency:row.currency,effective_from:row.effective_from,effective_to:row.effective_to,enabled:row.enabled});inputPrice.value=row.input_microunits_per_million/1e6;outputPrice.value=row.output_microunits_per_million/1e6;effectiveFrom.value=new Date(row.effective_from);effectiveTo.value=row.effective_to?new Date(row.effective_to):null;visible.value=true}
  async function save(){saving.value=true;try{form.input_microunits_per_million=Math.round(inputPrice.value*1e6);form.output_microunits_per_million=Math.round(outputPrice.value*1e6);form.effective_from=effectiveFrom.value.toISOString();form.effective_to=effectiveTo.value?.toISOString()||null;editing.value?await updateModelPrice(editing.value,form):await createModelPrice(form);visible.value=false;ElMessage.success('价格版本已保存');await load()}finally{saving.value=false}}
  async function remove(row:ModelPrice){await ElMessageBox.confirm(`确认删除 ${row.provider_code}/${row.model_pattern} 的价格版本？`,'删除价格',{type:'warning'});await deleteModelPrice(row.id);await load()}
  function money(v:number,c:string){return `${c} ${(v/1e6).toFixed(6).replace(/0+$/,'').replace(/\.$/,'')}`}function formatTime(v:string){return new Date(v).toLocaleString()}onMounted(load)
</script>
