<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="IMEI" prop="imei">
        <el-input v-model="queryParams.imei" placeholder="IMEI号" clearable style="width:160px" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择" clearable>
          <el-option label="在线" :value="1" />
          <el-option label="离线" :value="0" />
          <el-option label="禁用" :value="2" />
        </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="cardList" border size="small">
      <el-table-column label="ID" align="center" prop="cardId" width="60" />
      <el-table-column label="IMEI" align="center" prop="imei" width="150" />
      <el-table-column label="所属设备" align="center" min-width="120" show-overflow-tooltip>
        <template slot-scope="scope">
          <span v-if="scope.row.deviceId">{{ scope.row.deviceName || '设备#' + scope.row.deviceId }}</span>
          <el-tag v-else type="info" size="mini">未关联</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="卡槽" align="center" width="60">
        <template slot-scope="scope">
          <span>{{ scope.row.slotIndex || 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="租户" align="center" prop="tenantName" min-width="120" show-overflow-tooltip />
      <el-table-column label="卡槽1手机号" align="center" prop="phone1" width="130" />
      <el-table-column label="卡槽2手机号" align="center" prop="phone2" width="130" />
      <el-table-column label="关联端口" align="center" prop="portName" min-width="100" />
      <el-table-column label="状态" align="center" prop="status" width="70">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : scope.row.status === 0 ? 'danger' : 'info'" size="small">
            {{ scope.row.status === 1 ? '在线' : scope.row.status === 0 ? '离线' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <!-- 短信相关列 -->
      <el-table-column label="今日已发" align="center" width="80">
        <template slot-scope="scope">
          <span :class="{'text-danger': scope.row.smsSentToday >= scope.row.smsDailyLimit}">{{ scope.row.smsSentToday || 0 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="每小时限制" align="center" prop="smsHourlyLimit" width="90" />
      <el-table-column label="每日限制" align="center" prop="smsDailyLimit" width="80" />
      <el-table-column label="短信余额" align="center" width="80">
        <template slot-scope="scope">
          <span :class="{'text-danger': scope.row.smsBalance <= 0}">{{ scope.row.smsBalance || 0 }}</span>
        </template>
      </el-table-column>
      <!-- 通话相关列 -->
      <el-table-column label="今日已拨" align="center" prop="callSentToday" width="80" />
      <el-table-column label="拨打间隔(秒)" align="center" prop="callIntervalSeconds" width="100" />
      <el-table-column label="通话余额(分)" align="center" prop="callMinutesBalance" width="100" />
      <el-table-column label="话费余额(元)" align="center" prop="phoneBillBalance" width="100" />
      <el-table-column label="呼转" align="center" width="60">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.allowCallForward === 1" type="success" size="mini">是</el-tag>
          <el-tag v-else type="info" size="mini">否</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="最后心跳" align="center" prop="lastHeartbeat" width="160" />
      <el-table-column label="操作" align="center" width="160" fixed="right">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handleUpdate(scope.row)">编辑</el-button>
          <el-button size="mini" type="text" 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="IMEI" prop="imei">
              <el-input v-model="form.imei" placeholder="手机IMEI号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备名称">
              <el-input v-model="form.deviceName" placeholder="如：红米Note12" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="所属租户" prop="tenantId">
              <el-select v-model="form.tenantId" 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-col>
          <el-col :span="12">
            <el-form-item label="关联设备">
              <el-select v-model="form.deviceId" placeholder="选择设备" clearable filterable style="width:100%">
                <el-option v-for="d in deviceList" :key="d.deviceId" :label="d.deviceName + ' (' + d.imei + ')'" :value="d.deviceId" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="卡槽位置">
              <el-select v-model="form.slotIndex" style="width:100%">
                <el-option :value="1" label="卡槽1" />
                <el-option :value="2" label="卡槽2" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="关联端口">
              <el-input v-model="form.portId" placeholder="端口ID(可选)" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="卡槽1手机号">
              <el-input v-model="form.phone1" placeholder="手机号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="卡槽2手机号">
              <el-input v-model="form.phone2" placeholder="双卡时填写" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="状态">
          <el-select v-model="form.status" style="width:100%">
            <el-option :value="0" label="离线" />
            <el-option :value="1" label="在线" />
            <el-option :value="2" label="禁用" />
          </el-select>
        </el-form-item>

        <!-- 短信限制设置 -->
        <el-divider content-position="left">短信发送限制</el-divider>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="每小时限制" prop="smsHourlyLimit">
              <el-input-number v-model="form.smsHourlyLimit" :min="0" :max="9999" style="width:100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="每日限制" prop="smsDailyLimit">
              <el-input-number v-model="form.smsDailyLimit" :min="0" :max="99999" style="width:100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="短信余额(条)" prop="smsBalance">
              <el-input-number v-model="form.smsBalance" :min="0" :max="999999" style="width:100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="今日已发">
              <el-input-number v-model="form.smsSentToday" :min="0" style="width:100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="当前小时已发">
              <el-input-number v-model="form.smsSentHour" :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="8">
            <el-form-item label="拨打间隔(秒)" prop="callIntervalSeconds">
              <el-input-number v-model="form.callIntervalSeconds" :min="0" :max="3600" style="width:100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="今日已拨">
              <el-input-number v-model="form.callSentToday" :min="0" style="width:100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="通话余额(分)">
              <el-input-number v-model="form.callMinutesBalance" :min="0" :precision="2" :step="1" style="width:100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="话费余额(元)">
              <el-input-number v-model="form.phoneBillBalance" :min="0" :precision="4" :step="1" style="width:100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="允许呼转">
              <el-switch v-model="form.allowCallForward" :active-value="1" :inactive-value="0" active-text="是" inactive-text="否" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="呼转手机号">
              <el-input v-model="form.forwardPhone" placeholder="呼转目标手机号" :disabled="form.allowCallForward !== 1" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="备注">
          <el-input v-model="form.remark" type="textarea" :rows="2" />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 中间件配置区域 -->
    <el-divider content-position="left">手机卡发送中间件配置</el-divider>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAddMw">新增中间件</el-button>
      </el-col>
    </el-row>
    <el-table :data="mwList" border size="small" v-loading="mwLoading">
      <el-table-column label="ID" align="center" prop="id" width="60" />
      <el-table-column label="接口" align="center" prop="apiName" min-width="140" />
      <el-table-column label="名称" align="center" prop="middlewareName" min-width="120" />
      <el-table-column label="回调URL" align="center" prop="callbackUrl" min-width="200" show-overflow-tooltip />
      <el-table-column label="心跳URL" align="center" prop="heartbeatUrl" min-width="180" 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="handleEditMw(scope.row)">编辑</el-button>
          <el-button size="mini" type="text" style="color:#f56c6c" @click="handleDelMw(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 中间件弹窗 -->
    <el-dialog :title="mwDialogTitle" :visible.sync="mwDialogVisible" width="560px" append-to-body>
      <el-form ref="mwForm" :model="mwForm" :rules="mwRules" label-width="100px" size="small">
        <el-form-item label="关联接口" prop="apiId">
          <el-select v-model="mwForm.apiId" placeholder="选择手机卡类型接口" style="width:100%">
            <el-option v-for="api in cardApiList" :key="api.apiId" :label="api.apiName" :value="api.apiId" />
          </el-select>
        </el-form-item>
        <el-form-item label="名称" prop="middlewareName">
          <el-input v-model="mwForm.middlewareName" />
        </el-form-item>
        <el-form-item label="回调URL" prop="callbackUrl">
          <el-input v-model="mwForm.callbackUrl" placeholder="下发发送任务的URL" />
        </el-form-item>
        <el-form-item label="心跳URL">
          <el-input v-model="mwForm.heartbeatUrl" placeholder="心跳上报URL" />
        </el-form-item>
        <el-form-item label="鉴权Token">
          <el-input v-model="mwForm.authToken" />
        </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="5" :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 { listCard, addCard, updateCard, delCard, listMiddleware, addMiddleware, updateMiddleware, delMiddleware, listDevice } from '@/api/system/smsPort'
import { listSmsApi } from '@/api/system/smsApi'
import { listAllCompanies } from '@/api/admin/sysCompany'

export default {
  name: 'AdminSmsCard',
  data() {
    return {
      loading: false,
      mwLoading: false,
      cardList: [],
      deviceList: [],
      mwList: [],
      companyList: [],
      cardApiList: [],
      dialogVisible: false,
      dialogTitle: '',
      mwDialogVisible: false,
      mwDialogTitle: '',
      queryParams: { tenantId: undefined, imei: undefined, status: undefined },
      form: {},
      rules: {
        imei: [{ required: true, message: 'IMEI不能为空', trigger: 'blur' }],
        tenantId: [{ required: true, message: '请选择租户', trigger: 'change' }]
      },
      mwForm: {},
      mwRules: {
        apiId: [{ required: true, message: '请选择接口', trigger: 'change' }],
        middlewareName: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
        callbackUrl: [{ required: true, message: '回调URL不能为空', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getList()
    this.loadMwList()
    this.loadDeviceList()
    this.loadCompanyList()
    this.loadCardApiList()
  },
  methods: {
    getList() {
      this.loading = true
      listCard(this.queryParams).then(res => {
        this.cardList = res.data || []
      }).finally(() => { this.loading = false })
    },
    loadMwList() {
      this.mwLoading = true
      listMiddleware({}).then(res => {
        this.mwList = res.data || []
      }).finally(() => { this.mwLoading = false })
    },
    loadDeviceList() {
      listDevice({}).then(res => {
        this.deviceList = res.data || []
      })
    },
    loadCompanyList() {
      listAllCompanies({ pageNum: 1, pageSize: 1000 }).then(res => {
        this.companyList = res.rows || res.data || []
      })
    },
    loadCardApiList() {
      listSmsApi({ provider: 'card', status: 1 }).then(res => {
        this.cardApiList = res.data || []
      })
    },
    handleQuery() { this.getList() },
    resetQuery() {
      this.queryParams = { tenantId: undefined, imei: undefined, status: undefined }
      this.handleQuery()
    },
    resetForm() {
      this.form = {
        cardId: undefined, imei: '', deviceName: '', tenantId: undefined, deviceId: undefined, slotIndex: 1, portId: undefined,
        phone1: '', phone2: '', simCount: 1, status: 0,
        smsHourlyLimit: 100, smsDailyLimit: 500, smsBalance: 0,
        smsSentToday: 0, smsSentHour: 0,
        callSentToday: 0, callIntervalSeconds: 30,
        callMinutesBalance: 0, phoneBillBalance: 0,
        allowCallForward: 0, forwardPhone: '',
        remark: ''
      }
    },
    handleAdd() {
      this.resetForm()
      this.dialogTitle = '新增手机卡'
      this.dialogVisible = true
    },
    handleUpdate(row) {
      this.resetForm()
      this.form = { ...row }
      this.dialogTitle = '修改手机卡'
      this.dialogVisible = true
    },
    submitForm() {
      this.$refs.form.validate(valid => {
        if (!valid) return
        if (this.form.cardId) {
          updateCard(this.form).then(() => {
            this.$message.success('修改成功')
            this.dialogVisible = false
            this.getList()
          })
        } else {
          this.form.simCount = (this.form.phone2 && this.form.phone2.length > 0) ? 2 : 1
          addCard(this.form).then(() => {
            this.$message.success('新增成功')
            this.dialogVisible = false
            this.getList()
          })
        }
      })
    },
    handleDelete(row) {
      this.$confirm('确认删除此手机卡记录？', '提示', { type: 'warning' }).then(() => {
        delCard(row.cardId).then(() => { this.$message.success('删除成功'); this.getList() })
      }).catch(() => {})
    },
    // ========== 中间件 ==========
    resetMwForm() {
      this.mwForm = { id: undefined, apiId: undefined, middlewareName: '', callbackUrl: '', heartbeatUrl: '', authToken: '', maxRetry: 3, timeoutSeconds: 30, status: 1 }
    },
    handleAddMw() {
      this.resetMwForm()
      this.mwDialogTitle = '新增中间件'
      this.mwDialogVisible = true
    },
    handleEditMw(row) {
      this.resetMwForm()
      this.mwForm = { ...row }
      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.loadMwList()
          })
        } else {
          addMiddleware(this.mwForm).then(() => {
            this.$message.success('新增成功')
            this.mwDialogVisible = false
            this.loadMwList()
          })
        }
      })
    },
    handleDelMw(row) {
      this.$confirm('确认删除此中间件配置？', '提示', { type: 'warning' }).then(() => {
        delMiddleware(row.id).then(() => { this.$message.success('删除成功'); this.loadMwList() })
      }).catch(() => {})
    }
  }
}
</script>

<style scoped>
.text-danger {
  color: #f56c6c;
  font-weight: bold;
}
</style>
