<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="companyId">
          <el-select v-model="queryParams.companyId" 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="apiId">
          <el-select v-model="queryParams.apiId" placeholder="选择接口" clearable filterable style="width:180px">
            <el-option v-for="a in apiOptions" :key="a.apiId" :label="a.apiName" :value="a.apiId" />
          </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">新增绑定</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="companyName" min-width="120" show-overflow-tooltip />
      <el-table-column label="接口名称" align="center" prop="apiName" min-width="120" show-overflow-tooltip />
      <el-table-column label="服务商" align="center" prop="provider" min-width="80">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.provider === 'card'" type="warning" size="mini">手机卡</el-tag>
          <el-tag v-else type="primary" size="mini">平台</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="接口类型" align="center" prop="apiType" min-width="70">
        <template slot-scope="scope">
          <span>{{ apiTypeMap[scope.row.apiType] || scope.row.apiType }}</span>
        </template>
      </el-table-column>
      <el-table-column label="成本价" align="center" prop="costPrice" min-width="90">
        <template slot-scope="scope">
          <span>{{ scope.row.costPrice != null ? scope.row.costPrice + ' 元/分钟' : '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="售价(元/分钟)" align="center" prop="price" min-width="120">
        <template slot-scope="scope">
          <span>{{ scope.row.price != null ? scope.row.price : '未定价' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="优先级" align="center" prop="priority" min-width="70">
        <template slot-scope="scope">
          <el-tag :type="scope.row.isPrimary === 1 ? 'success' : 'info'" size="mini">{{ scope.row.priority || '-' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="主线路" align="center" prop="isPrimary" min-width="70">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.isPrimary === 1" type="success" size="mini">是</el-tag>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="手动选择" align="center" prop="allowManual" min-width="80">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.allowManual === 1" type="warning" size="mini">允许</el-tag>
          <span v-else>否</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" class-name="small-padding fixed-width" width="140">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleEditPricing(scope.row)">定价</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" style="color:#f56c6c" @click="handleUnbind(scope.row)">解除</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="新增外呼接口-租户绑定" :visible.sync="addDialogVisible" width="500px" append-to-body>
      <el-form ref="addForm" :model="addForm" :rules="addRules" label-width="100px" size="small">
        <el-form-item label="选择接口" prop="apiId">
          <el-select v-model="addForm.apiId" placeholder="请选择外呼接口" style="width:100%" @change="onApiChange">
            <el-option v-for="api in apiOptions" :key="api.apiId" :label="api.apiName" :value="api.apiId" />
          </el-select>
        </el-form-item>
        <el-form-item label="选择租户" prop="companyId">
          <el-select v-model="addForm.companyId" placeholder="请选择租户" filterable style="width:100%">
            <el-option v-for="c in companyList" :key="c.companyId" :label="c.companyName" :value="c.companyId" />
          </el-select>
        </el-form-item>
        <el-form-item label="售价(元/分钟)" prop="price">
          <el-input-number v-model="addForm.price" :precision="4" :step="0.01" :min="0" style="width:100%" />
        </el-form-item>
        <el-form-item label="优先级" prop="priority">
          <el-input-number v-model="addForm.priority" :min="1" :max="99" style="width:100%" />
          <span style="color:#909399;font-size:12px;margin-left:8px">1最高，同类型多接口时按优先级选择</span>
        </el-form-item>
        <el-form-item label="主线路">
          <el-switch v-model="addForm.isPrimary" :active-value="1" :inactive-value="0" active-text="是" inactive-text="否" />
        </el-form-item>
        <el-form-item label="允许手动选择">
          <el-switch v-model="addForm.allowManual" :active-value="1" :inactive-value="0" active-text="允许" inactive-text="禁止" />
        </el-form-item>
        <el-form-item v-if="selectedApiCost" label="">
          <span style="color:#909399;font-size:12px">该接口成本价: {{ selectedApiCost }} 元/分钟，建议售价 >= 成本价</span>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="primary" @click="submitAdd" :loading="addSubmitting">确 定</el-button>
        <el-button @click="addDialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 定价编辑弹窗 -->
    <el-dialog title="编辑租户定价" :visible.sync="pricingOpen" width="500px" append-to-body>
      <el-form ref="pricingForm" :model="pricingForm" label-width="140px" size="small">
        <el-form-item label="租户">
          <el-input :value="pricingForm.companyName" disabled />
        </el-form-item>
        <el-form-item label="接口">
          <el-input :value="pricingForm.apiName" disabled />
        </el-form-item>
        <el-form-item label="成本价(元/分钟)">
          <el-input :value="pricingForm.costPrice != null ? pricingForm.costPrice : '-'" disabled />
        </el-form-item>
        <el-form-item label="售价(元/分钟)" prop="price">
          <el-input-number v-model="pricingForm.price" :precision="4" :min="0" :step="0.01" style="width:100%" />
        </el-form-item>
        <el-form-item label="优先级" prop="priority">
          <el-input-number v-model="pricingForm.priority" :min="1" :max="99" :step="1" style="width:100%" />
        </el-form-item>
        <el-form-item label="主线路">
          <el-switch v-model="pricingForm.isPrimary" :active-value="1" :inactive-value="0" active-text="是" inactive-text="否" />
        </el-form-item>
        <el-form-item label="允许手动选择">
          <el-switch v-model="pricingForm.allowManual" :active-value="1" :inactive-value="0" active-text="允许" inactive-text="禁止" />
        </el-form-item>
        <el-form-item label="状态">
          <el-switch v-model="pricingForm.status" :active-value="1" :inactive-value="0" active-text="启用" inactive-text="禁用" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitPricing" :loading="pricingSubmitting">保 存</el-button>
        <el-button @click="pricingOpen = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listVoiceApiTenant, updateTenantPricing, getVoiceApiList, assignTenants, unassignTenant } from '@/api/company/companyVoiceApi'
import { listAllCompanies } from '@/api/admin/sysCompany'

export default {
  name: 'AdminVoiceApiTenant',
  data() {
    return {
      loading: true,
      total: 0,
      dataList: [],
      apiTypeMap: { '0': 'SIP', '1': '网关', '2': 'API' },
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        companyId: null,
        apiId: null,
        status: null
      },
      // 租户搜索
      companyOptions: [],
      companySearchLoading: false,
      // 接口列表
      apiOptions: [],
      // 新增绑定
      addDialogVisible: false,
      addSubmitting: false,
      addForm: { apiId: undefined, companyId: undefined, price: 0, priority: 1, isPrimary: 0, allowManual: 0 },
      addRules: {
        apiId: [{ required: true, message: '请选择接口', trigger: 'change' }],
        companyId: [{ required: true, message: '请选择租户', trigger: 'change' }],
        price: [{ required: true, message: '请填写售价', trigger: 'blur' }]
      },
      // 租户列表(新增绑定用)
      companyList: [],
      // 定价编辑
      pricingOpen: false,
      pricingSubmitting: false,
      pricingForm: {
        id: null,
        companyName: '',
        apiName: '',
        costPrice: null,
        price: null,
        priority: 1,
        isPrimary: 0,
        allowManual: 0,
        status: 1
      }
    }
  },
  computed: {
    selectedApiCost() {
      const api = this.apiOptions.find(a => a.apiId === this.addForm.apiId)
      return api && api.costPrice ? api.costPrice : ''
    }
  },
  created() {
    this.getList()
    this.loadApiOptions()
    this.loadCompanyList()
  },
  methods: {
    getList() {
      this.loading = true
      listVoiceApiTenant(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()
    },
    loadApiOptions() {
      getVoiceApiList().then(response => {
        this.apiOptions = response.rows || response.data || []
      }).catch(() => {})
    },
    loadCompanyList() {
      listAllCompanies({ pageNum: 1, pageSize: 1000 }).then(res => {
        this.companyList = res.rows || res.data || []
      })
    },
    onApiChange(apiId) {
      const api = this.apiOptions.find(a => a.apiId === apiId)
      if (api && api.costPrice) {
        this.addForm.price = api.costPrice
      }
    },
    handleAdd() {
      this.addForm = { apiId: undefined, companyId: undefined, price: 0, priority: 1, isPrimary: 0, allowManual: 0 }
      this.addDialogVisible = true
      this.$nextTick(() => {
        if (this.$refs.addForm) this.$refs.addForm.clearValidate()
      })
    },
    submitAdd() {
      this.$refs.addForm.validate(valid => {
        if (!valid) return
        this.addSubmitting = true
        assignTenants(this.addForm.apiId, [this.addForm.companyId]).then(() => {
          // 分配后设置定价
          if (this.addForm.price || this.addForm.priority > 1 || this.addForm.isPrimary || this.addForm.allowManual) {
            updateTenantPricing({
              apiId: this.addForm.apiId,
              companyId: this.addForm.companyId,
              price: this.addForm.price,
              priority: this.addForm.priority,
              isPrimary: this.addForm.isPrimary,
              allowManual: this.addForm.allowManual,
              status: 1
            }).catch(() => {})
          }
          this.$message.success('绑定成功')
          this.addDialogVisible = false
          this.getList()
        }).finally(() => { this.addSubmitting = false })
      })
    },
    handleUnbind(row) {
      this.$confirm('确认解除租户"' + row.companyName + '"与接口"' + row.apiName + '"的绑定？', '提示', {
        confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning'
      }).then(() => {
        unassignTenant(row.apiId, row.companyId).then(() => {
          this.$message.success('解除绑定成功')
          this.getList()
        })
      }).catch(() => {})
    },
    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 })
    },
    handleEditPricing(row) {
      this.pricingForm = {
        id: row.id,
        companyName: row.companyName,
        apiName: row.apiName,
        costPrice: row.costPrice,
        price: row.price,
        priority: row.priority || 1,
        isPrimary: row.isPrimary || 0,
        allowManual: row.allowManual || 0,
        status: row.status
      }
      this.pricingOpen = true
      this.$nextTick(() => {
        if (this.$refs.pricingForm) this.$refs.pricingForm.clearValidate()
      })
    },
    submitPricing() {
      this.pricingSubmitting = true
      updateTenantPricing({
        id: this.pricingForm.id,
        price: this.pricingForm.price,
        priority: this.pricingForm.priority,
        isPrimary: this.pricingForm.isPrimary,
        allowManual: this.pricingForm.allowManual,
        status: this.pricingForm.status
      }).then(() => {
        this.$message.success('定价保存成功')
        this.pricingOpen = false
        this.getList()
      }).finally(() => { this.pricingSubmitting = false })
    }
  }
}
</script>

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