<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="80px" size="small">
      <el-form-item label="公司名称" prop="companyName">
        <el-input
          v-model="queryParams.companyName"
          placeholder="请输入公司名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="分机号码" prop="extensionNum">
        <el-input
          v-model="queryParams.extensionNum"
          placeholder="请输入分机号码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="分配状态" prop="assignStatus">
        <el-select v-model="queryParams.assignStatus" placeholder="请选择" clearable style="width:120px">
          <el-option label="分机池" :value="0" />
          <el-option label="已分配" :value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择" clearable style="width:120px">
          <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-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-connection"
          size="mini"
          :disabled="!canAssign"
          @click="handleAssign"
          v-hasPermi="['company:companyVoiceCaller:bind']"
        >分配到公司</el-button>
      </el-col>
      <el-col :span="1.5" v-if="selectedRows.length">
        <span class="selected-tip">已选 {{ selectedRows.length }} 条</span>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="dataList"
      border
      size="small"
      class="voice-seat-table"
      height="500"
      style="width:100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="45" align="center" :selectable="checkSelectable" />
      <el-table-column label="ID" align="center" prop="id" width="70" />
      <el-table-column label="公司名称" align="center" prop="companyName" min-width="120" show-overflow-tooltip />
      <el-table-column label="分机号码" align="center" prop="extensionNum" width="110" />
      <el-table-column label="绑定员工" align="center" prop="companyUserName" min-width="100" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{ scope.row.companyUserName || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="绑定标识" align="center" prop="userCode" min-width="130" show-overflow-tooltip />
      <el-table-column label="状态" align="center" prop="status" width="80">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status === 0 || scope.row.status === '0'" type="danger" size="mini">停用</el-tag>
          <el-tag v-else type="success" size="mini">可用</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="155" />
      <el-table-column label="操作" align="center" width="90">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-view" @click="handleDetail(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="分配分机到公司" :visible.sync="assignOpen" width="480px" append-to-body @close="resetAssignForm">
      <el-form ref="assignForm" :model="assignForm" :rules="assignRules" label-width="100px" size="small">
        <el-form-item label="目标公司" prop="companyId">
          <el-select v-model="assignForm.companyId" placeholder="请选择公司名称" filterable clearable style="width:100%">
            <el-option
              v-for="item in companyOptions"
              :key="item.dictValue"
              :label="item.dictLabel"
              :value="Number(item.dictValue)"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="已选分机">
          <span>{{ assignForm.ids.length }} 个（分机池内可用分机）</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="assignOpen = false">取 消</el-button>
        <el-button type="primary" :loading="assignLoading" @click="submitAssign">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 详情 -->
    <el-dialog title="分机详情" :visible.sync="detailOpen" width="560px" append-to-body>
      <el-form :model="detailForm" label-width="100px" size="small">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="ID"><span>{{ detailForm.id }}</span></el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="公司名称"><span>{{ detailForm.companyName || '-' }}</span></el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分机号码"><span>{{ detailForm.extensionNum }}</span></el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分机密码"><span>{{ detailForm.extensionPass || '-' }}</span></el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="流水编号"><span>{{ detailForm.extId || '-' }}</span></el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="绑定标识"><span>{{ detailForm.userCode || '-' }}</span></el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="绑定员工"><span>{{ detailForm.companyUserName || '-' }}</span></el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-tag v-if="detailForm.status === 0" type="danger">停用</el-tag>
              <el-tag v-else type="success">可用</el-tag>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="创建时间"><span>{{ detailForm.createTime || '-' }}</span></el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import {
  listVoiceSeat,
  getVoiceSeat,
  assignVoiceSeat,
  getCompanyOptions
} from '@/api/company/companyVoiceCaller'

export default {
  name: 'CompanyVoiceCaller',
  data() {
    return {
      loading: true,
      assignLoading: false,
      showSearch: true,
      total: 0,
      dataList: [],
      selectedRows: [],
      companyOptions: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        companyName: null,
        extensionNum: null,
        status: null,
        assignStatus: null
      },
      assignOpen: false,
      assignForm: {
        companyId: null,
        ids: []
      },
      assignRules: {
        companyId: [{ required: true, message: '请选择目标公司', trigger: 'change' }]
      },
      detailOpen: false,
      detailForm: {}
    }
  },
  computed: {
    canAssign() {
      return this.selectedRows.length > 0 && this.selectedRows.every(row => this.isAssignableRow(row))
    }
  },
  created() {
    this.getList()
    this.loadCompanyOptions()
  },
  methods: {
    getList() {
      this.loading = true
      listVoiceSeat(this.queryParams).then(response => {
        this.dataList = response.rows || []
        this.total = response.total || 0
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    loadCompanyOptions() {
      getCompanyOptions().then(res => {
        this.companyOptions = res.data || []
      })
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    handleSelectionChange(selection) {
      this.selectedRows = selection
    },
    /** 分机池内且状态为可用的分机才允许勾选分配 */
    isAssignableRow(row) {
      if (!row) return false
      const inPool = row.companyId === 0 || row.companyId === '0'
      const enabled = row.status === 1 || row.status === '1'
      return inPool && enabled
    },
    checkSelectable(row) {
      return this.isAssignableRow(row)
    },
    handleAssign() {
      if (!this.canAssign) {
        this.msgError('请选择分机池内状态为可用的分机')
        return
      }
      this.assignForm = {
        companyId: null,
        ids: this.selectedRows.map(item => item.id)
      }
      this.assignOpen = true
    },
    resetAssignForm() {
      this.assignForm = { companyId: null, ids: [] }
      if (this.$refs.assignForm) {
        this.$refs.assignForm.resetFields()
      }
    },
    submitAssign() {
      this.$refs.assignForm.validate(valid => {
        if (!valid) return
        this.assignLoading = true
        assignVoiceSeat(this.assignForm).then(res => {
          this.msgSuccess(res.msg || '分配成功')
          this.assignOpen = false
          this.getList()
        }).finally(() => {
          this.assignLoading = false
        })
      })
    },
    handleDetail(row) {
      getVoiceSeat(row.id).then(response => {
        this.detailForm = response.data || {}
        this.detailOpen = true
      })
    }
  }
}
</script>

<style scoped>
.mb8 { margin-bottom: 8px; }
.selected-tip {
  display: inline-block;
  line-height: 28px;
  font-size: 13px;
  color: #909399;
}
</style>
