<template>
  <div class="page-container">
    <el-card>
      <div slot="header" class="header-row">
        <span>代理定价</span>
        <el-button type="primary" :disabled="!selectedProxyId" @click="batchSave" :loading="saving">全部保存</el-button>
      </div>
      <el-form :inline="true" size="small">
        <el-form-item label="选择代理">
          <el-select v-model="selectedProxyId" placeholder="请选择代理" @change="onProxyChange" style="width:300px" filterable>
            <el-option v-for="a in proxyList" :key="a.proxyId" :label="a.proxyName + ' — 折扣' + (a.platformDiscount || a.profitShareRatio || 0) + '%'" :value="a.proxyId" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="selectedProxyId && proxyDiscount">
          <el-tag type="warning">该代理平台折扣：{{ proxyDiscount }}%</el-tag>
        </el-form-item>
      </el-form>
      <el-table :data="mergedList" border v-loading="loading" v-if="selectedProxyId" max-height="calc(100vh - 280px)">
        <el-table-column type="index" label="#" width="50" />
        <el-table-column prop="modelCode" label="模型编码" min-width="160" />
        <el-table-column prop="modelName" label="模型名称" min-width="160" />
        <el-table-column label="平台上游进价" min-width="130" align="center">
          <template slot-scope="s">¥{{ (s.row.upstreamInputPrice || 0).toFixed(6) }}</template>
        </el-table-column>
        <el-table-column label="平台售价基准" min-width="130" align="center">
          <template slot-scope="s">¥{{ (s.row.baseOutputPrice || 0).toFixed(6) }}</template>
        </el-table-column>
        <el-table-column label="代理进价" min-width="180" align="center">
          <template slot-scope="s">
            <el-input-number v-model="s.row.agentInputPrice" :min="0" :precision="6" :step="0.0001" size="mini" controls-position="right" style="width:150px" />
          </template>
        </el-table-column>
        <el-table-column label="代理售价" min-width="180" align="center">
          <template slot-scope="s">
            <el-input-number v-model="s.row.agentOutputPrice" :min="0" :precision="6" :step="0.0001" size="mini" controls-position="right" style="width:150px" />
          </template>
        </el-table-column>
      </el-table>
      <el-empty v-else description="请先选择一个代理，系统将列出所有模型供批量定价" />
    </el-card>
  </div>
</template>

<script>
import { listProxy, allEnabledProxies } from '@/api/admin/proxy'
import { listServicePrice, batchSaveProxyServicePrice } from '@/api/admin/serviceCost'

export default {
  name: 'AdminAgentPricing',
  data() {
    return {
      loading: false,
      saving: false,
      proxyList: [],
      selectedProxyId: null,
      proxyDiscount: null,
      mergedList: []
    }
  },
  created() {
    this.fetchProxies()
  },
  methods: {
    fetchProxies() {
      allEnabledProxies().then(res => {
        this.proxyList = res.data || []
        // 自动选中第一个代理并加载定价
        if (this.proxyList.length > 0) {
          this.selectedProxyId = this.proxyList[0].proxyId
          this.onProxyChange()
        }
      }).catch(() => {})
    },
    onProxyChange() {
      const proxy = this.proxyList.find(a => a.proxyId === this.selectedProxyId)
      this.proxyDiscount = proxy ? (proxy.platformDiscount || proxy.profitShareRatio) : null
      this.fetchPricing()
    },
    fetchPricing() {
      if (!this.selectedProxyId) return
      this.loading = true
      listServicePrice({ proxyId: this.selectedProxyId, pageNum: 1, pageSize: 999 }).then(res => {
        const rows = res.rows || []
        const discount = (this.proxyDiscount || 100) / 100
        this.mergedList = rows.map(r => ({
          modelCode: r.modelCode || r.serviceCode,
          modelName: r.modelName || r.serviceName,
          upstreamInputPrice: r.upstreamPrice || 0,
          baseOutputPrice: r.basePrice || r.salePrice || 0,
          agentInputPrice: r.proxyPrice || 0,
          agentOutputPrice: r.proxySalePrice || 0
        }))
      }).catch(() => {}).finally(() => { this.loading = false })
    },
    batchSave() {
      if (!this.mergedList.length) {
        this.$message.warning('没有可保存的定价数据')
        return
      }
      this.saving = true
      const data = this.mergedList.map(item => ({
        proxyId: this.selectedProxyId,
        modelCode: item.modelCode,
        modelName: item.modelName,
        upstreamInputPrice: item.upstreamInputPrice,
        baseOutputPrice: item.baseOutputPrice,
        agentInputPrice: item.agentInputPrice,
        agentOutputPrice: item.agentOutputPrice
      }))
      batchSaveProxyServicePrice(data).then(() => {
        this.$message.success('定价保存成功')
        this.fetchPricing()
      }).catch(() => {
        this.$message.error('保存失败，请重试')
      }).finally(() => { this.saving = false })
    }
  }
}
</script>

<style scoped>
.page-container { padding: 16px; }
.header-row { display: flex; justify-content: space-between; align-items: center; }
</style>
