<template>
  <div class="app-container">
    <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>
          <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="smsType">
        <el-select v-model="queryParams.smsType" placeholder="请选择" clearable>
          <el-option v-for="item in smsTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
        </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-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="bindList" border size="small">
      <el-table-column label="ID" align="center" prop="id" width="60" />
      <el-table-column label="租户名称" align="center" prop="companyName" min-width="140" show-overflow-tooltip />
      <el-table-column label="接口名称" align="center" prop="apiName" min-width="140" show-overflow-tooltip />
      <el-table-column label="短信类型" align="center" prop="smsType" width="140">
        <template slot-scope="scope">
          <el-tag :type="scope.row.smsType === 1 ? 'success' : scope.row.smsType === 2 ? 'warning' : 'danger'" size="small">
            {{ smsTypeFormat(scope.row.smsType) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="服务商" align="center" prop="provider" width="80">
        <template slot-scope="scope">{{ providerFormat(scope.row.provider) }}</template>
      </el-table-column>
      <el-table-column label="优先级" align="center" prop="priority" width="70">
        <template slot-scope="scope">
          <el-tag type="warning" size="mini">{{ scope.row.priority || 1 }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="成本价" align="center" prop="costPrice" width="100">
        <template slot-scope="scope">
          <span style="color:#909399">{{ scope.row.costPrice || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="租户售价(元/条)" align="center" prop="price" width="130">
        <template slot-scope="scope">
          <span style="color:#e6a23c;font-weight:bold">{{ scope.row.price }}</span>
        </template>
      </el-table-column>
      <el-table-column label="利润(元/条)" align="center" width="110">
        <template slot-scope="scope">
          <span style="color:#67c23a;font-weight:bold">{{ calcProfit(scope.row) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="手动选择" align="center" prop="allowManual" width="80">
        <template slot-scope="scope">
          <el-tag :type="scope.row.allowManual === 1 ? 'success' : 'info'" size="mini">{{ scope.row.allowManual === 1 ? '允许' : '否' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" width="70">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'" size="small">{{ scope.row.status === 1 ? '启用' : '禁用' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="160">
        <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-delete" style="color:#f56c6c" @click="handleDelete(scope.row)">解除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增绑定弹窗 -->
    <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 + ' (' + smsTypeFormat(api.smsType) + ')'" :value="api.apiId" />
          </el-select>
        </el-form-item>
        <el-form-item label="选择租户" prop="tenantId">
          <el-select v-model="addForm.tenantId" placeholder="请选择租户" filterable style="width:100%">
            <el-option v-for="c in companyList" :key="c.tenantId" :label="c.companyName" :value="c.tenantId" />
          </el-select>
        </el-form-item>
        <el-form-item label="租户售价" prop="price">
          <el-input-number v-model="addForm.price" :precision="4" :step="0.001" :min="0" style="width:100%" />
          <span style="color:#909399;font-size:12px;margin-left:8px">元/条</span>
        </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.allowManual" :active-value="1" :inactive-value="0" active-text="允许" inactive-text="否" />
          <span style="color:#909399;font-size:12px;margin-left:8px">是否允许销售手动选择此接口发送</span>
        </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">确 定</el-button>
        <el-button @click="addDialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 调价弹窗 -->
    <el-dialog title="调整租户售价" :visible.sync="editDialogVisible" width="450px" append-to-body>
      <el-form ref="editForm" :model="editForm" label-width="100px" size="small">
        <el-form-item label="租户">
          <span>{{ editForm.companyName }}</span>
        </el-form-item>
        <el-form-item label="接口">
          <span>{{ editForm.apiName }}</span>
        </el-form-item>
        <el-form-item label="成本价">
          <span style="color:#909399">{{ editForm.costPrice }} 元/条</span>
        </el-form-item>
        <el-form-item label="租户售价" prop="price">
          <el-input-number v-model="editForm.price" :precision="4" :step="0.001" :min="0" style="width:100%" />
          <span style="color:#909399;font-size:12px;margin-left:8px">元/条</span>
        </el-form-item>
        <el-form-item label="优先级">
          <el-input-number v-model="editForm.priority" :min="1" :max="99" style="width:100%" />
        </el-form-item>
        <el-form-item label="允许手动选择">
          <el-switch v-model="editForm.allowManual" :active-value="1" :inactive-value="0" active-text="允许" inactive-text="否" />
        </el-form-item>
        <el-form-item label="状态">
          <el-switch v-model="editForm.status" :active-value="1" :inactive-value="0" active-text="启用" inactive-text="禁用" />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="primary" @click="submitEdit">确 定</el-button>
        <el-button @click="editDialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listSmsApiTenant, addSmsApiTenant, updateSmsApiTenant, delSmsApiTenant, listSmsApi } from '@/api/system/smsApi'
import { listAllCompanies } from '@/api/admin/sysCompany'

export default {
  name: 'AdminSmsApiTenant',
  data() {
    return {
      loading: false,
      bindList: [],
      companyList: [],
      apiOptions: [],
      smsTypeOptions: [
        { value: 1, label: '行业验证码通知短信' },
        { value: 2, label: '营销短信' },
        { value: 3, label: '5G消息' }
      ],
      queryParams: { tenantId: undefined, smsType: undefined },
      addDialogVisible: false,
      editDialogVisible: false,
      addForm: { apiId: undefined, tenantId: undefined, price: 0, priority: 1, allowManual: 0 },
      editForm: { id: undefined, price: 0, priority: 1, allowManual: 0, status: 1, companyName: '', apiName: '', costPrice: 0 },
      addRules: {
        apiId: [{ required: true, message: '请选择接口', trigger: 'change' }],
        tenantId: [{ required: true, message: '请选择租户', trigger: 'change' }],
        price: [{ required: true, message: '请填写售价', trigger: 'blur' }]
      }
    }
  },
  computed: {
    selectedApiCost() {
      const api = this.apiOptions.find(a => a.apiId === this.addForm.apiId)
      return api && api.costPrice ? api.costPrice : ''
    }
  },
  created() {
    this.getList()
    this.loadCompanyList()
    this.loadApiOptions()
  },
  methods: {
    smsTypeFormat(type) {
      const map = { 1: '行业验证码通知', 2: '营销短信', 3: '5G消息' }
      return map[type] || '未知'
    },
    providerFormat(p) {
      const map = { my: '迈远', card: '手机卡' }
      return map[p] || p
    },
    calcProfit(row) {
      if (row.price != null && row.costPrice != null) {
        return (row.price - row.costPrice).toFixed(4)
      }
      return '-'
    },
    getList() {
      this.loading = true
      listSmsApiTenant(this.queryParams).then(res => {
        this.bindList = res.data || []
      }).finally(() => { this.loading = false })
    },
    loadCompanyList() {
      listAllCompanies({ pageNum: 1, pageSize: 1000 }).then(res => {
        this.companyList = res.rows || res.data || []
      })
    },
    loadApiOptions() {
      listSmsApi({ status: 1 }).then(res => {
        this.apiOptions = res.data || []
      })
    },
    onApiChange(apiId) {
      // 当选择接口时，自动填充默认售价
      const api = this.apiOptions.find(a => a.apiId === apiId)
      if (api && api.costPrice) {
        this.addForm.price = api.costPrice
      }
    },
    handleQuery() { this.getList() },
    resetQuery() {
      this.queryParams = { tenantId: undefined, smsType: undefined }
      this.handleQuery()
    },
    handleAdd() {
      this.addForm = { apiId: undefined, tenantId: undefined, price: 0, priority: 1, allowManual: 0 }
      this.addDialogVisible = true
    },
    submitAdd() {
      this.$refs.addForm.validate(valid => {
        if (!valid) return
        addSmsApiTenant({ ...this.addForm, status: 1 }).then(() => {
          this.$message.success('绑定成功')
          this.addDialogVisible = false
          this.getList()
        })
      })
    },
    handleUpdate(row) {
      this.editForm = {
        id: row.id,
        price: row.price,
        priority: row.priority || 1,
        allowManual: row.allowManual || 0,
        status: row.status,
        companyName: row.companyName,
        apiName: row.apiName,
        costPrice: row.costPrice
      }
      this.editDialogVisible = true
    },
    submitEdit() {
      updateSmsApiTenant({ id: this.editForm.id, price: this.editForm.price, priority: this.editForm.priority, allowManual: this.editForm.allowManual, status: this.editForm.status }).then(() => {
        this.$message.success('修改成功')
        this.editDialogVisible = false
        this.getList()
      })
    },
    handleDelete(row) {
      this.$confirm('确认解除租户"' + row.companyName + '"与接口"' + row.apiName + '"的绑定？', '提示', {
        confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning'
      }).then(() => {
        delSmsApiTenant(row.id).then(() => {
          this.$message.success('解除绑定成功')
          this.getList()
        })
      }).catch(() => {})
    }
  }
}
</script>

<style scoped>
</style>
