<template>
  <div class="app-container">
    <el-card shadow="never" class="mb16 filter-card">
      <el-form :model="queryParams" ref="queryForm" :inline="true" size="small">
        <el-form-item label="租户" prop="tenantId">
          <el-select v-model="queryParams.tenantId" placeholder="选择租户" clearable filterable remote
            reserve-keyword :remote-method="searchCompanies" :loading="companySearchLoading" style="width:200px">
            <el-option v-for="c in companyOptions" :key="c.companyId" :label="c.companyName" :value="c.companyId" />
          </el-select>
        </el-form-item>
        <el-form-item label="服务类型" prop="serviceType">
          <el-select v-model="queryParams.serviceType" placeholder="请选择" clearable style="width:140px">
            <el-option label="课程流量" :value="2" />
            <el-option label="直播流量" :value="3" />
            <el-option label="AI TOKEN" :value="4" />
            <el-option label="AI外呼附加费" :value="7" />
            <el-option label="微助手" :value="8" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择" clearable size="small">
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['platform:trafficPricing:add']">新增定价</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="dataList" border size="small" style="width:100%">
      <el-table-column label="租户" align="center" prop="tenantName" min-width="120" show-overflow-tooltip />
      <el-table-column label="服务类型" align="center" prop="serviceTypeName" min-width="100" />
      <el-table-column label="租户售价(元/GB)" align="center" prop="price" min-width="130">
        <template slot-scope="scope">
          <span>{{ scope.row.price != null ? scope.row.price : '未定价(使用全局)' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="成本价(元/GB)" align="center" prop="costPrice" min-width="130">
        <template slot-scope="scope">
          <span>{{ scope.row.costPrice != null ? scope.row.costPrice : '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="全局参考售价" align="center" prop="globalPrice" min-width="120">
        <template slot-scope="scope">
          <span>{{ scope.row.globalPrice != null ? scope.row.globalPrice + ' 元/GB' : '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="全局参考成本" align="center" prop="globalCost" min-width="120">
        <template slot-scope="scope">
          <span>{{ scope.row.globalCost != null ? scope.row.globalCost + ' 元/GB' : '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" min-width="70">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status === 1" type="success" size="mini">启用</el-tag>
          <el-tag v-else type="danger" size="mini">禁用</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" min-width="150" show-overflow-tooltip />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="120">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['platform:trafficPricing:edit']">编辑</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" style="color:#f56c6c" @click="handleDelete(scope.row)"
            v-hasPermi="['platform:trafficPricing:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <!-- 新增/编辑弹窗 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="550px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="140px" size="small">
        <el-form-item label="租户" prop="tenantId">
          <el-select v-model="form.tenantId" placeholder="选择租户" filterable remote clearable
            reserve-keyword :remote-method="searchCompanies" :loading="companySearchLoading"
            style="width:100%" :disabled="isEdit">
            <el-option v-for="c in companyOptions" :key="c.companyId" :label="c.companyName" :value="c.companyId" />
          </el-select>
        </el-form-item>
        <el-form-item label="服务类型" prop="serviceType">
          <el-select v-model="form.serviceType" placeholder="请选择服务类型" style="width:100%" :disabled="isEdit">
            <el-option label="课程流量" :value="2" />
            <el-option label="直播流量" :value="3" />
            <el-option label="AI TOKEN" :value="4" />
            <el-option label="AI外呼附加费" :value="7" />
            <el-option label="微助手" :value="8" />
          </el-select>
        </el-form-item>
        <el-form-item label="售价(元/GB)" prop="price">
          <el-input-number v-model="form.price" :precision="4" :min="0" :step="0.01" style="width:100%" />
        </el-form-item>
        <el-form-item label="成本价(元/GB)">
          <el-input-number v-model="form.costPrice" :precision="4" :min="0" :step="0.01" style="width:100%" />
        </el-form-item>
        <el-form-item label="状态">
          <el-switch v-model="form.status" :active-value="1" :inactive-value="0" active-text="启用" inactive-text="禁用" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.remark" type="textarea" :rows="2" placeholder="定价说明" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :loading="submitting">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listTrafficPricing, getTrafficPricing, addTrafficPricing, updateTrafficPricing, delTrafficPricing } from '@/api/admin/trafficPricing'
import { listAllCompanies } from '@/api/admin/sysCompany'

export default {
  name: 'AdminTrafficPricing',
  data() {
    return {
      loading: true,
      submitting: false,
      total: 0,
      dataList: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        tenantId: null,
        serviceType: null,
        status: null
      },
      // 租户搜索
      companyOptions: [],
      companySearchLoading: false,
      // 弹窗
      dialogVisible: false,
      dialogTitle: '',
      isEdit: false,
      form: {},
      rules: {
        tenantId: [{ required: true, message: '请选择租户', trigger: 'change' }],
        serviceType: [{ required: true, message: '请选择服务类型', trigger: 'change' }]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.loading = true
      listTrafficPricing(this.queryParams).then(response => {
        this.dataList = response.rows || []
        this.total = response.total || 0
        this.loading = false
      }).catch(() => { this.loading = false })
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    searchCompanies(query) {
      if (query.length < 1) { this.companyOptions = []; return }
      this.companySearchLoading = true
      listAllCompanies({ companyName: query, pageNum: 1, pageSize: 20 }).then(response => {
        this.companyOptions = (response.rows || []).map(c => ({
          companyId: c.companyId || c.id,
          companyName: c.companyName || c.tenantName
        }))
      }).finally(() => { this.companySearchLoading = false })
    },
    resetFormData() {
      this.form = {
        id: undefined,
        tenantId: null,
        serviceType: null,
        price: null,
        costPrice: null,
        status: 1,
        remark: ''
      }
    },
    handleAdd() {
      this.isEdit = false
      this.resetFormData()
      this.dialogTitle = '新增流量定价'
      this.dialogVisible = true
      this.$nextTick(() => {
        if (this.$refs.form) this.$refs.form.clearValidate()
      })
    },
    handleUpdate(row) {
      this.isEdit = true
      this.dialogTitle = '编辑流量定价'
      this.form = {
        id: row.id,
        tenantId: row.tenantId,
        serviceType: row.serviceType,
        price: row.price,
        costPrice: row.costPrice,
        status: row.status,
        remark: row.remark
      }
      this.dialogVisible = true
      this.$nextTick(() => {
        if (this.$refs.form) this.$refs.form.clearValidate()
      })
    },
    submitForm() {
      this.$refs.form.validate(valid => {
        if (!valid) return
        this.submitting = true
        if (this.isEdit) {
          updateTrafficPricing(this.form).then(() => {
            this.$message.success('修改成功')
            this.dialogVisible = false
            this.getList()
          }).finally(() => { this.submitting = false })
        } else {
          addTrafficPricing(this.form).then(() => {
            this.$message.success('新增成功')
            this.dialogVisible = false
            this.getList()
          }).finally(() => { this.submitting = false })
        }
      })
    },
    handleDelete(row) {
      this.$confirm('确认删除该租户流量定价？', '提示', { type: 'warning' }).then(() => {
        delTrafficPricing(row.id).then(() => {
          this.$message.success('删除成功')
          this.getList()
        })
      }).catch(() => {})
    }
  }
}
</script>

<style scoped>
.mb16 { margin-bottom: 16px; }
.mb8 { margin-bottom: 8px; }
.filter-card { padding-bottom: 0; }
</style>
