<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="deviceList" border size="small">
      <el-table-column label="ID" align="center" prop="deviceId" width="60" />
      <el-table-column label="IMEI" align="center" prop="imei" width="150" />
      <el-table-column label="设备名称" align="center" prop="deviceName" min-width="120" show-overflow-tooltip />
      <el-table-column label="租户" align="center" prop="tenantName" min-width="120" show-overflow-tooltip />
      <el-table-column label="绑定销售" align="center" prop="userName" min-width="100" show-overflow-tooltip />
      <el-table-column label="关联中间件" align="center" prop="middlewareName" min-width="120" show-overflow-tooltip />
      <el-table-column label="卡数量" align="center" width="80">
        <template slot-scope="scope">
          <span>{{ scope.row.cardCount || 0 }} 张</span>
        </template>
      </el-table-column>
      <el-table-column label="在线卡" align="center" width="80">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.onlineCardCount > 0" type="success" size="mini">{{ scope.row.onlineCardCount }}</el-tag>
          <el-tag v-else type="info" size="mini">0</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="APP版本" align="center" prop="appVersion" width="90" />
      <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" prop="lastHeartbeat" width="160" />
      <el-table-column label="操作" align="center" width="200" fixed="right">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handleUpdate(scope.row)">编辑</el-button>
          <el-button size="mini" type="text" @click="handleAssign(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="560px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px" 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号" :disabled="!!form.deviceId" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备名称" prop="deviceName">
              <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.middlewareId" placeholder="选择中间件" clearable filterable style="width:100%">
                <el-option v-for="mw in mwList" :key="mw.id" :label="mw.middlewareName" :value="mw.id" />
              </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.companyUserId" placeholder="选择销售" clearable filterable style="width:100%">
                <el-option v-for="u in userList" :key="u.userId" :label="u.userName" :value="u.userId" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <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-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-dialog title="分配销售" :visible.sync="assignVisible" width="420px" append-to-body>
      <el-form label-width="80px" size="small">
        <el-form-item label="设备">
          <el-input :value="assignRow.deviceName + ' (' + assignRow.imei + ')'" disabled />
        </el-form-item>
        <el-form-item label="选择销售">
          <el-select v-model="assignUserId" placeholder="选择销售用户" filterable style="width:100%">
            <el-option v-for="u in userList" :key="u.userId" :label="u.userName" :value="u.userId" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="primary" @click="submitAssign">确 定</el-button>
        <el-button @click="assignVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listDevice, addDevice, updateDevice, delDevice, assignDevice, listMiddleware } from '@/api/system/smsPort'
import { listAllCompanies } from '@/api/admin/sysCompany'

export default {
  name: 'AdminSmsDevice',
  data() {
    return {
      loading: false,
      deviceList: [],
      companyList: [],
      mwList: [],
      userList: [],
      dialogVisible: false,
      dialogTitle: '',
      assignVisible: false,
      assignRow: {},
      assignUserId: undefined,
      queryParams: { tenantId: undefined, imei: undefined, status: undefined },
      form: {},
      rules: {
        imei: [{ required: true, message: 'IMEI不能为空', trigger: 'blur' }],
        tenantId: [{ required: true, message: '请选择租户', trigger: 'change' }]
      }
    }
  },
  created() {
    this.getList()
    this.loadCompanyList()
    this.loadMwList()
    this.loadUserList()
  },
  methods: {
    getList() {
      this.loading = true
      listDevice(this.queryParams).then(res => {
        this.deviceList = res.data || []
      }).finally(() => { this.loading = false })
    },
    loadCompanyList() {
      listAllCompanies({ pageNum: 1, pageSize: 1000 }).then(res => {
        this.companyList = res.rows || res.data || []
      })
    },
    loadMwList() {
      listMiddleware({ status: 1 }).then(res => {
        this.mwList = res.data || []
      })
    },
    loadUserList() {
      // 查询租户下的销售用户（简化：查全部用户，后续可按租户过滤）
      import('@/api/system/user').then(mod => {
        if (mod.listUser) {
          mod.listUser({ pageNum: 1, pageSize: 5000 }).then(res => {
            this.userList = res.rows || []
          })
        }
      }).catch(() => {
        // 降级: 从公司列表中获取
        this.userList = []
      })
    },
    handleQuery() { this.getList() },
    resetQuery() {
      this.queryParams = { tenantId: undefined, imei: undefined, status: undefined }
      this.handleQuery()
    },
    resetForm() {
      this.form = {
        deviceId: undefined, imei: '', deviceName: '', tenantId: undefined,
        companyUserId: undefined, middlewareId: undefined, status: 0, 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.deviceId) {
          updateDevice(this.form).then(() => {
            this.$message.success('修改成功')
            this.dialogVisible = false
            this.getList()
          })
        } else {
          addDevice(this.form).then(() => {
            this.$message.success('新增成功')
            this.dialogVisible = false
            this.getList()
          })
        }
      })
    },
    handleDelete(row) {
      this.$confirm('确认删除此设备？关联的手机卡不会被删除。', '提示', { type: 'warning' }).then(() => {
        delDevice(row.deviceId).then(() => { this.$message.success('删除成功'); this.getList() })
      }).catch(() => {})
    },
    handleAssign(row) {
      this.assignRow = row
      this.assignUserId = row.companyUserId
      this.assignVisible = true
    },
    submitAssign() {
      if (!this.assignUserId) {
        this.$message.warning('请选择销售用户')
        return
      }
      assignDevice(this.assignRow.deviceId, this.assignUserId).then(() => {
        this.$message.success('分配成功')
        this.assignVisible = false
        this.getList()
      })
    }
  }
}
</script>

<style scoped>
</style>
