<template>
  <div class="app-container">
    <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="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 label="服务商" prop="provider">
        <el-select v-model="queryParams.provider" placeholder="请选择" clearable>
          <el-option label="迈远" value="my" />
          <el-option label="手机卡" value="card" />
        </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="apiList" border size="small" @expand-change="handleExpand">
      <el-table-column type="expand">
        <template slot-scope="props">
          <div style="padding:10px 20px">
            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAddPort(props.row)">新增端口</el-button>
              </el-col>
            </el-row>
            <el-table :data="portMap[props.row.apiId] || []" border size="mini" v-loading="portLoading">
              <el-table-column label="端口ID" align="center" prop="portId" width="70" />
              <el-table-column label="端口名称" align="center" prop="portName" min-width="120" />
              <el-table-column label="端口号" align="center" prop="portNo" min-width="100">
                <template slot-scope="scope">
                  <span v-if="props.row.provider === 'card'">{{ scope.row.portNo }}</span>
                  <span v-else>{{ scope.row.portNo }}</span>
                </template>
              </el-table-column>
              <el-table-column label="独立账户" align="center" prop="account" min-width="100" show-overflow-tooltip />
              <el-table-column label="独立签名" align="center" prop="sign" width="80" />
              <el-table-column v-if="props.row.provider === 'card'" label="卡槽" align="center" prop="slotIndex" width="60">
                <template slot-scope="scope">{{ scope.row.slotIndex || '-' }}</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="mini">{{ scope.row.status === 1 ? '正常' : '禁用' }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" width="120">
                <template slot-scope="scope">
                  <el-button size="mini" type="text" @click="handleEditPort(scope.row, props.row)">修改</el-button>
                  <el-button size="mini" type="text" style="color:#f56c6c" @click="handleDelPort(scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <!-- 中间件配置(仅card服务商) -->
            <template v-if="props.row.provider === 'card'">
              <el-divider content-position="left" style="margin:16px 0 8px">中间件配置</el-divider>
              <el-row :gutter="10" class="mb8">
                <el-col :span="1.5">
                  <el-button type="success" plain icon="el-icon-plus" size="mini" @click="handleAddMiddleware(props.row)">新增中间件</el-button>
                </el-col>
              </el-row>
              <el-table :data="middlewareMap[props.row.apiId] || []" border size="mini" v-loading="mwLoading">
                <el-table-column label="ID" align="center" prop="id" width="60" />
                <el-table-column label="名称" align="center" prop="middlewareName" min-width="120" />
                <el-table-column label="下发URL" align="center" prop="callbackUrl" min-width="180" show-overflow-tooltip />
                <el-table-column label="心跳URL" align="center" prop="heartbeatUrl" min-width="180" show-overflow-tooltip />
                <el-table-column label="Token" align="center" prop="authToken" width="120" show-overflow-tooltip />
                <el-table-column label="重试次数" align="center" prop="maxRetry" width="80" />
                <el-table-column label="超时(秒)" align="center" prop="timeoutSeconds" width="80" />
                <el-table-column label="状态" align="center" prop="status" width="70">
                  <template slot-scope="scope">
                    <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'" size="mini">{{ scope.row.status === 1 ? '正常' : '禁用' }}</el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="操作" align="center" width="120">
                  <template slot-scope="scope">
                    <el-button size="mini" type="text" @click="handleEditMiddleware(scope.row, props.row)">修改</el-button>
                    <el-button size="mini" type="text" style="color:#f56c6c" @click="handleDelMiddleware(scope.row, props.row)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </template>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="ID" align="center" prop="apiId" width="60" />
      <el-table-column label="接口名称" align="center" prop="apiName" min-width="140" />
      <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="account" min-width="100" show-overflow-tooltip />
      <el-table-column label="签名" align="center" prop="sign" width="80" />
      <el-table-column label="成本价(元/条)" align="center" prop="costPrice" width="120">
        <template slot-scope="scope">
          <span style="color:#e6a23c;font-weight:bold">{{ scope.row.costPrice || '-' }}</span>
        </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="dialogTitle" :visible.sync="dialogVisible" width="680px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px" size="small">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="接口名称" prop="apiName">
              <el-input v-model="form.apiName" placeholder="如：迈远行业验证码通知" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发送类型" prop="smsType">
              <el-select v-model="form.smsType" placeholder="请选择" style="width:100%">
                <el-option v-for="item in smsTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="服务商" prop="provider">
              <el-select v-model="form.provider" placeholder="请选择" style="width:100%">
                <el-option label="迈远" value="my" />
                <el-option label="手机卡" value="card" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="成本价(元/条)" prop="costPrice">
              <el-input-number v-model="form.costPrice" :precision="4" :step="0.001" :min="0" style="width:100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider content-position="left">通道配置</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="账户名" prop="account">
              <el-input v-model="form.account" placeholder="接口级默认账户(端口可覆盖)" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="密码" prop="password">
              <el-input v-model="form.password" placeholder="接口级默认密码" show-password />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="短信签名">
              <el-input v-model="form.sign" placeholder="接口级默认签名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="form.provider === 'my'" label="接口地址">
              <el-input v-model="form.url" placeholder="润方专用" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="form.provider === 'my'" :gutter="20">
          <el-col :span="12">
            <el-form-item label="扩展码">
              <el-input v-model="form.code" placeholder="迈远专用(旧,端口优先)" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="是否默认">
              <el-switch v-model="form.isDefault" :active-value="1" :inactive-value="0" active-text="是" inactive-text="否" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-switch v-model="form.status" :active-value="1" :inactive-value="0" active-text="正常" inactive-text="禁用" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input v-model="form.remark" type="textarea" :rows="2" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 新增/修改端口弹窗 -->
    <el-dialog :title="portDialogTitle" :visible.sync="portDialogVisible" width="560px" append-to-body>
      <el-form ref="portForm" :model="portForm" :rules="portRules" label-width="100px" size="small">
        <el-form-item label="端口名称" prop="portName">
          <el-input v-model="portForm.portName" placeholder="如：迈远端口1 / XX医院卡" />
        </el-form-item>
        <el-form-item label="端口号" prop="portNo">
          <el-input v-model="portForm.portNo" :placeholder="currentApiProvider === 'card' ? '手机号' : 'extno扩展码'" />
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="独立账户">
              <el-input v-model="portForm.account" placeholder="覆盖接口级" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="独立密码">
              <el-input v-model="portForm.password" placeholder="覆盖接口级" show-password />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="独立签名">
              <el-input v-model="portForm.sign" placeholder="覆盖接口级" />
            </el-form-item>
          </el-col>
          <el-col v-if="currentApiProvider === 'card'" :span="12">
            <el-form-item label="卡槽号">
              <el-select v-model="portForm.slotIndex" style="width:100%">
                <el-option :value="1" label="卡槽1" />
                <el-option :value="2" label="卡槽2" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="状态">
          <el-switch v-model="portForm.status" :active-value="1" :inactive-value="0" active-text="正常" inactive-text="禁用" />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="primary" @click="submitPortForm">确 定</el-button>
        <el-button @click="portDialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 中间件弹窗 -->
    <el-dialog :title="mwDialogTitle" :visible.sync="mwDialogVisible" width="580px" append-to-body>
      <el-form ref="mwForm" :model="mwForm" :rules="mwRules" label-width="100px" size="small">
        <el-form-item label="中间件名称" prop="middlewareName">
          <el-input v-model="mwForm.middlewareName" placeholder="如：红米Note12中间件" />
        </el-form-item>
        <el-form-item label="下发任务URL" prop="callbackUrl">
          <el-input v-model="mwForm.callbackUrl" placeholder="http://192.168.1.100:8080/sms/send" />
        </el-form-item>
        <el-form-item label="心跳上报URL">
          <el-input v-model="mwForm.heartbeatUrl" placeholder="http://192.168.1.100:8080/sms/heartbeat" />
        </el-form-item>
        <el-form-item label="鉴权Token">
          <el-input v-model="mwForm.authToken" placeholder="Bearer token" />
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="最大重试次数">
              <el-input-number v-model="mwForm.maxRetry" :min="0" :max="10" style="width:100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="超时秒数">
              <el-input-number v-model="mwForm.timeoutSeconds" :min="1" :max="300" style="width:100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="状态">
          <el-switch v-model="mwForm.status" :active-value="1" :inactive-value="0" active-text="正常" inactive-text="禁用" />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="primary" @click="submitMwForm">确 定</el-button>
        <el-button @click="mwDialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listSmsApi, getSmsApi, addSmsApi, updateSmsApi, delSmsApi } from '@/api/system/smsApi'
import { listPortByApi, addPort, updatePort, delPort, listMiddleware, getMiddlewareByApi, addMiddleware, updateMiddleware, delMiddleware } from '@/api/system/smsPort'

export default {
  name: 'AdminSmsApi',
  data() {
    return {
      loading: false,
      portLoading: false,
      apiList: [],
      portMap: {},
      middlewareMap: {},
      mwLoading: false,
      dialogVisible: false,
      dialogTitle: '',
      portDialogVisible: false,
      portDialogTitle: '',
      currentApiId: null,
      currentApiProvider: '',
      smsTypeOptions: [
        { value: 1, label: '行业验证码通知短信' },
        { value: 2, label: '营销短信' },
        { value: 3, label: '5G消息' }
      ],
      queryParams: { apiName: undefined, smsType: undefined, provider: undefined },
      form: {},
      rules: {
        apiName: [{ required: true, message: '接口名称不能为空', trigger: 'blur' }],
        smsType: [{ required: true, message: '请选择发送类型', trigger: 'change' }],
        provider: [{ required: true, message: '请选择服务商', trigger: 'change' }],
        costPrice: [{ required: true, message: '成本价不能为空', trigger: 'blur' }]
      },
      portForm: {},
      portRules: {
        portName: [{ required: true, message: '端口名称不能为空', trigger: 'blur' }],
        portNo: [{ required: true, message: '端口号不能为空', trigger: 'blur' }]
      },
      mwDialogVisible: false,
      mwDialogTitle: '',
      mwForm: {},
      mwRules: {
        middlewareName: [{ required: true, message: '中间件名称不能为空', trigger: 'blur' }],
        callbackUrl: [{ required: true, message: '下发任务URL不能为空', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    smsTypeFormat(type) {
      const map = { 1: '行业验证码通知', 2: '营销短信', 3: '5G消息' }
      return map[type] || '未知'
    },
    providerFormat(p) {
      const map = { my: '迈远', card: '手机卡' }
      return map[p] || p
    },
    getList() {
      this.loading = true
      listSmsApi(this.queryParams).then(res => {
        this.apiList = res.data || []
      }).finally(() => { this.loading = false })
    },
    handleQuery() { this.getList() },
    resetQuery() {
      this.queryParams = { apiName: undefined, smsType: undefined, provider: undefined }
      this.handleQuery()
    },
    resetForm() {
      this.form = {
        apiId: undefined, apiName: '', smsType: 1, provider: 'my',
        account: '', password: '', url: '', code: '', sign: '',
        costPrice: 0, isDefault: 0, status: 1, remark: ''
      }
    },
    handleAdd() {
      this.resetForm()
      this.dialogTitle = '新增短信接口'
      this.dialogVisible = true
    },
    handleUpdate(row) {
      this.resetForm()
      getSmsApi(row.apiId).then(res => {
        this.form = res.data
        this.dialogTitle = '修改短信接口'
        this.dialogVisible = true
      })
    },
    submitForm() {
      this.$refs.form.validate(valid => {
        if (!valid) return
        if (this.form.apiId) {
          updateSmsApi(this.form).then(() => {
            this.$message.success('修改成功')
            this.dialogVisible = false
            this.getList()
          })
        } else {
          addSmsApi(this.form).then(() => {
            this.$message.success('新增成功')
            this.dialogVisible = false
            this.getList()
          })
        }
      })
    },
    handleDelete(row) {
      this.$confirm('确认删除接口"' + row.apiName + '"？删除后端口池和租户绑定也将同步解除。', '提示', {
        confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning'
      }).then(() => {
        delSmsApi(row.apiId).then(() => {
          this.$message.success('删除成功')
          this.getList()
        })
      }).catch(() => {})
    },
    // ========== 端口池 ==========
    loadPorts(apiId) {
      this.portLoading = true
      listPortByApi(apiId).then(res => {
        this.$set(this.portMap, apiId, res.data || [])
      }).finally(() => { this.portLoading = false })
    },
    resetPortForm() {
      this.portForm = { portId: undefined, apiId: null, portName: '', portNo: '', account: '', password: '', sign: '', slotIndex: null, status: 1 }
    },
    handleAddPort(apiRow) {
      this.resetPortForm()
      this.currentApiId = apiRow.apiId
      this.currentApiProvider = apiRow.provider
      this.portForm.apiId = apiRow.apiId
      this.portDialogTitle = '新增端口 - ' + apiRow.apiName
      this.portDialogVisible = true
    },
    handleEditPort(portRow, apiRow) {
      this.resetPortForm()
      this.currentApiId = apiRow.apiId
      this.currentApiProvider = apiRow.provider
      this.portForm = { ...portRow }
      this.portDialogTitle = '修改端口'
      this.portDialogVisible = true
    },
    submitPortForm() {
      this.$refs.portForm.validate(valid => {
        if (!valid) return
        if (this.portForm.portId) {
          updatePort(this.portForm).then(() => {
            this.$message.success('修改成功')
            this.portDialogVisible = false
            this.loadPorts(this.currentApiId)
          })
        } else {
          addPort(this.portForm).then(() => {
            this.$message.success('新增成功')
            this.portDialogVisible = false
            this.loadPorts(this.currentApiId)
          })
        }
      })
    },
    handleDelPort(row) {
      this.$confirm('确认删除端口"' + row.portName + '"？', '提示', {
        confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning'
      }).then(() => {
        delPort(row.portId).then(() => {
          this.$message.success('删除成功')
          this.loadPorts(row.apiId)
        })
      }).catch(() => {})
    },
    // ========== 中间件管理 ==========
    handleExpand(row, expandedRows) {
      if (!this.portMap[row.apiId]) this.loadPorts(row.apiId)
      if (row.provider === 'card' && !this.middlewareMap[row.apiId]) this.loadMiddleware(row.apiId)
    },
    loadMiddleware(apiId) {
      this.mwLoading = true
      getMiddlewareByApi(apiId).then(res => {
        this.$set(this.middlewareMap, apiId, res.data || [])
      }).finally(() => { this.mwLoading = false })
    },
    resetMwForm() {
      this.mwForm = { id: undefined, apiId: null, middlewareName: '', callbackUrl: '', heartbeatUrl: '', authToken: '', maxRetry: 3, timeoutSeconds: 30, status: 1 }
    },
    handleAddMiddleware(apiRow) {
      this.resetMwForm()
      this.currentApiId = apiRow.apiId
      this.mwForm.apiId = apiRow.apiId
      this.mwDialogTitle = '新增中间件 - ' + apiRow.apiName
      this.mwDialogVisible = true
    },
    handleEditMiddleware(mwRow, apiRow) {
      this.resetMwForm()
      this.currentApiId = apiRow.apiId
      this.mwForm = { ...mwRow }
      this.mwDialogTitle = '修改中间件'
      this.mwDialogVisible = true
    },
    submitMwForm() {
      this.$refs.mwForm.validate(valid => {
        if (!valid) return
        if (this.mwForm.id) {
          updateMiddleware(this.mwForm).then(() => {
            this.$message.success('修改成功')
            this.mwDialogVisible = false
            this.loadMiddleware(this.currentApiId)
          })
        } else {
          addMiddleware(this.mwForm).then(() => {
            this.$message.success('新增成功')
            this.mwDialogVisible = false
            this.loadMiddleware(this.currentApiId)
          })
        }
      })
    },
    handleDelMiddleware(row, apiRow) {
      this.$confirm('确认删除中间件"' + row.middlewareName + '"？', '提示', {
        confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning'
      }).then(() => {
        delMiddleware(row.id).then(() => {
          this.$message.success('删除成功')
          this.loadMiddleware(apiRow.apiId)
        })
      }).catch(() => {})
    }
  }
}
</script>

<style scoped>
</style>
