<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="apiName">
          <el-input
            v-model="queryParams.apiName"
            placeholder="请输入接口名称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="接口类型" prop="apiType">
          <el-select v-model="queryParams.apiType" placeholder="请选择类型" clearable size="small">
            <el-option label="SIP" value="0" />
            <el-option label="网关" value="1" />
            <el-option label="API" value="2" />
          </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" icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="dataList" border size="small" style="width:100%">
      <el-table-column label="接口ID" align="center" prop="apiId" min-width="70" />
      <el-table-column label="接口类型" align="center" prop="apiType" min-width="80">
        <template slot-scope="scope">
          <span>{{ getApiTypeLabel(scope.row.apiType) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="接口名称" align="center" prop="apiName" min-width="130" show-overflow-tooltip />
      <el-table-column label="服务商" align="center" prop="provider" min-width="100">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.provider === 'card'" type="warning">手机卡</el-tag>
          <el-tag v-else type="primary">平台</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="成本价(元/分钟)" align="center" prop="costPrice" min-width="120">
        <template slot-scope="scope">
          <span>{{ scope.row.costPrice != null ? scope.row.costPrice : '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="已分配租户" align="center" min-width="100">
        <template slot-scope="scope">
          <el-button type="text" @click="handleViewTenants(scope.row)">{{ scope.row.tenantCount || 0 }}个租户</el-button>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" min-width="80">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status === 0 || scope.row.status === '0'" type="danger">禁用</el-tag>
          <el-tag v-else type="success">启用</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" min-width="150" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="240">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">编辑</el-button>
          <el-button size="mini" type="text" icon="el-icon-user" @click="handleAssignTenant(scope.row)">分配租户</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(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="formTitle" :visible.sync="formOpen" width="650px" append-to-body>
      <el-form ref="apiForm" :model="apiForm" :rules="apiRules" label-width="120px" size="small">
        <el-form-item label="接口名称" prop="apiName">
          <el-input v-model="apiForm.apiName" placeholder="请输入接口名称" />
        </el-form-item>
        <el-form-item label="接口类型" prop="apiType">
          <el-select v-model="apiForm.apiType" placeholder="请选择类型" clearable size="small" style="width:100%">
            <el-option label="SIP" value="0" />
            <el-option label="网关" value="1" />
            <el-option label="API" value="2" />
          </el-select>
        </el-form-item>
        <template v-if="apiForm.apiType === '1' || apiForm.apiType === '2'">
          <el-form-item label="帐号">
            <el-input v-model="apiForm.apiJsonObj.account" placeholder="请输入帐号" />
          </el-form-item>
          <el-form-item label="密码">
            <el-input v-model="apiForm.apiJsonObj.password" placeholder="请输入密码" />
          </el-form-item>
          <el-form-item label="接口地址">
            <el-input v-model="apiForm.apiJsonObj.url" placeholder="请输入接口地址" />
          </el-form-item>
        </template>
        <template v-if="apiForm.apiType === '2'">
          <el-form-item label="话术跳转地址">
            <el-input v-model="apiForm.apiJsonObj.dialogUrl" placeholder="请输入话术跳转地址" />
          </el-form-item>
        </template>
        <el-form-item label="服务商" prop="provider">
          <el-select v-model="apiForm.provider" placeholder="请选择服务商" clearable size="small" style="width:100%">
            <el-option label="平台外呼" value="platform" />
            <el-option label="手机卡外呼" value="card" />
          </el-select>
        </el-form-item>
        <el-form-item label="成本价(元/分钟)" prop="costPrice">
          <el-input-number v-model="apiForm.costPrice" :precision="4" :min="0" :step="0.01" placeholder="成本价" style="width:100%" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="apiForm.status">
            <el-radio label="1">启用</el-radio>
            <el-radio label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注">
          <el-input type="textarea" v-model="apiForm.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitApiForm" :loading="formSubmitting">确 定</el-button>
        <el-button @click="formOpen = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 分配租户弹窗 -->
    <el-dialog title="分配租户" :visible.sync="assignOpen" width="700px" append-to-body>
      <div style="margin-bottom:12px">
        <span>接口：<strong>{{ assignApi.apiName }}</strong>（ID: {{ assignApi.apiId }}）</span>
      </div>
      <!-- 已分配租户列表 -->
      <el-table :data="assignedTenants" border size="small" style="width:100%;margin-bottom:12px" v-loading="assignLoading">
        <el-table-column label="租户ID" align="center" prop="companyId" width="80" />
        <el-table-column label="租户名称" align="center" prop="companyName" />
        <el-table-column label="状态" align="center" prop="status" width="80">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">{{ scope.row.status === 1 ? '启用' : '禁用' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="100">
          <template slot-scope="scope">
            <el-button size="mini" type="text" style="color:#F56C6C" @click="handleUnassign(scope.row)">取消分配</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 添加租户 -->
      <el-divider>添加租户</el-divider>
      <el-select v-model="selectedCompanyIds" multiple filterable remote reserve-keyword
        placeholder="输入租户名称搜索" :remote-method="searchCompanies" :loading="companySearchLoading"
        style="width:100%" size="small">
        <el-option v-for="item in companyOptions" :key="item.companyId" :label="item.companyName" :value="item.companyId" />
      </el-select>
      <div style="margin-top:12px;text-align:right">
        <el-button type="primary" size="small" @click="submitAssign" :loading="assignSubmitting" :disabled="selectedCompanyIds.length === 0">确认分配</el-button>
      </div>
    </el-dialog>

    <!-- 查看已分配租户弹窗 -->
    <el-dialog title="已分配租户" :visible.sync="tenantListOpen" width="600px" append-to-body>
      <el-table :data="viewTenants" border size="small" style="width:100%" v-loading="viewTenantsLoading">
        <el-table-column label="租户ID" align="center" prop="companyId" width="80" />
        <el-table-column label="租户名称" align="center" prop="companyName" />
        <el-table-column label="状态" align="center" prop="status" width="80">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">{{ scope.row.status === 1 ? '启用' : '禁用' }}</el-tag>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import {
  listCompanyVoiceApi, getCompanyVoiceApi,
  addCompanyVoiceApi, updateCompanyVoiceApi, delCompanyVoiceApi,
  getAssignedTenants, assignTenants, unassignTenant, getTenantCount
} from '@/api/company/companyVoiceApi'
import { listAllCompanies } from '@/api/admin/sysCompany'

export default {
  name: 'AdminVoiceApi',
  data() {
    return {
      loading: true,
      showSearch: true,
      total: 0,
      dataList: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        apiName: null,
        apiType: null,
        provider: null,
        status: null
      },
      apiTypeMap: { '0': 'SIP', '1': '网关', '2': 'API' },
      // 新增/编辑表单
      formOpen: false,
      formTitle: '',
      formSubmitting: false,
      apiForm: {
        apiId: null,
        apiName: null,
        apiType: '1',
        provider: 'platform',
        apiJsonObj: {},
        costPrice: null,
        status: '1',
        remark: null
      },
      apiRules: {
        apiName: [{ required: true, message: '接口名称不能为空', trigger: 'blur' }],
        apiType: [{ required: true, message: '接口类型不能为空', trigger: 'change' }],
        status: [{ required: true, message: '状态不能为空', trigger: 'change' }]
      },
      // 分配租户
      assignOpen: false,
      assignApi: {},
      assignLoading: false,
      assignSubmitting: false,
      assignedTenants: [],
      selectedCompanyIds: [],
      companyOptions: [],
      companySearchLoading: false,
      // 查看租户列表
      tenantListOpen: false,
      viewTenants: [],
      viewTenantsLoading: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.loading = true
      listCompanyVoiceApi(this.queryParams).then(response => {
        this.dataList = response.rows || []
        this.total = response.total || 0
        this.loading = false
        // 加载每个接口的租户数量
        this.dataList.forEach(row => {
          getTenantCount(row.apiId).then(res => {
            this.$set(row, 'tenantCount', res.data || 0)
          }).catch(() => {
            this.$set(row, 'tenantCount', 0)
          })
        })
      })
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    getApiTypeLabel(type) {
      return this.apiTypeMap[String(type)] || '未知'
    },
    // 新增
    handleAdd() {
      this.resetApiForm()
      this.formTitle = '新增通话接口'
      this.formOpen = true
    },
    // 编辑
    handleUpdate(row) {
      this.resetApiForm()
      getCompanyVoiceApi(row.apiId).then(response => {
        const data = response.data
        this.apiForm = {
          apiId: data.apiId,
          apiName: data.apiName,
          apiType: String(data.apiType),
          provider: data.provider || 'platform',
          apiJsonObj: data.apiJson ? JSON.parse(data.apiJson) : {},
          costPrice: data.costPrice,
          status: String(data.status),
          remark: data.remark
        }
        this.formTitle = '编辑通话接口'
        this.formOpen = true
      })
    },
    resetApiForm() {
      this.apiForm = {
        apiId: null,
        apiName: null,
        apiType: '1',
        provider: 'platform',
        apiJsonObj: {},
        costPrice: null,
        status: '1',
        remark: null
      }
      this.$nextTick(() => {
        if (this.$refs.apiForm) this.$refs.apiForm.clearValidate()
      })
    },
    submitApiForm() {
      this.$refs.apiForm.validate(valid => {
        if (!valid) return
        this.formSubmitting = true
        const data = { ...this.apiForm }
        data.apiJson = JSON.stringify(data.apiJsonObj)
        delete data.apiJsonObj
        if (data.apiId) {
          updateCompanyVoiceApi(data).then(() => {
            this.$message.success('修改成功')
            this.formOpen = false
            this.getList()
          }).finally(() => { this.formSubmitting = false })
        } else {
          addCompanyVoiceApi(data).then(() => {
            this.$message.success('新增成功')
            this.formOpen = false
            this.getList()
          }).finally(() => { this.formSubmitting = false })
        }
      })
    },
    // 删除
    handleDelete(row) {
      this.$confirm('是否确认删除接口"' + row.apiName + '"？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return delCompanyVoiceApi(row.apiId)
      }).then(() => {
        this.$message.success('删除成功')
        this.getList()
      }).catch(() => {})
    },
    // 分配租户
    handleAssignTenant(row) {
      this.assignApi = row
      this.assignOpen = true
      this.selectedCompanyIds = []
      this.companyOptions = []
      this.loadAssignedTenants()
    },
    loadAssignedTenants() {
      this.assignLoading = true
      getAssignedTenants(this.assignApi.apiId).then(response => {
        this.assignedTenants = response.data || []
      }).finally(() => { this.assignLoading = false })
    },
    searchCompanies(query) {
      if (query.length < 1) 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 })
    },
    submitAssign() {
      if (this.selectedCompanyIds.length === 0) return
      this.assignSubmitting = true
      assignTenants(this.assignApi.apiId, this.selectedCompanyIds).then(() => {
        this.$message.success('分配成功')
        this.selectedCompanyIds = []
        this.loadAssignedTenants()
        this.getList()
      }).finally(() => { this.assignSubmitting = false })
    },
    handleUnassign(row) {
      this.$confirm('是否取消该租户的接口分配？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return unassignTenant(row.apiId, row.companyId)
      }).then(() => {
        this.$message.success('已取消分配')
        this.loadAssignedTenants()
        this.getList()
      }).catch(() => {})
    },
    // 查看已分配租户
    handleViewTenants(row) {
      this.tenantListOpen = true
      this.viewTenantsLoading = true
      getAssignedTenants(row.apiId).then(response => {
        this.viewTenants = response.data || []
      }).finally(() => { this.viewTenantsLoading = false })
    }
  }
}
</script>

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