<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="90px">
<!--      <el-form-item label="黑名单级别" prop="businessType">-->
<!--        <el-select-->
<!--          v-model="queryParams.businessType"-->
<!--          placeholder="全部（租户级+线路级）"-->
<!--          clearable-->
<!--          size="small"-->
<!--          style="width: 180px"-->
<!--        >-->
<!--          <el-option label="租户级" value="12" />-->
<!--          <el-option label="线路级" value="13" />-->
<!--        </el-select>-->
<!--      </el-form-item>-->
      <el-form-item label="手机号码" prop="targetValue">
        <el-input
          v-model="queryParams.targetValue"
          placeholder="请输入手机号码"
          clearable
          size="small"
          style="width: 200px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small" style="width: 140px">
          <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"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['company:companyVoiceBlacklist:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate()"
          v-hasPermi="['company:companyVoiceBlacklist:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete()"
          v-hasPermi="['company:companyVoiceBlacklist:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['company:companyVoiceBlacklist:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" />
    </el-row>

    <el-table v-loading="loading" :data="list" border height="500" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column label="ID" align="center" prop="id" width="80" />
<!--      <el-table-column label="黑名单级别" align="center" prop="businessType" width="100">-->
<!--        <template slot-scope="scope">-->
<!--          <span v-if="scope.row.businessType === '12'">租户级</span>-->
<!--          <span v-else-if="scope.row.businessType === '13'">线路级</span>-->
<!--          <span v-else>{{ scope.row.businessType || '-' }}</span>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="手机号码" align="center" min-width="180">
        <template slot-scope="scope">
          <span>{{ scope.row.targetValue || '-' }}</span>
          <el-button
            v-if="canQueryPhone(scope.row)"
            type="text"
            icon="el-icon-zoom-in"
            size="mini"
            style="margin-left: 8px"
            @click="handlePhone(scope.row)"
            v-hasPermi="['company:companyVoiceBlacklist:queryPhone']"
          />
        </template>
      </el-table-column>
      <el-table-column label="拉黑原因" align="center" prop="reason" min-width="120" show-overflow-tooltip />
      <el-table-column label="状态" align="center" prop="status" width="90">
        <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" prop="remark" min-width="120" show-overflow-tooltip />
      <el-table-column label="创建人" align="center" prop="createBy" width="100" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="160" />
      <el-table-column label="更新人" align="center" prop="updateBy" width="100" />
      <el-table-column label="更新时间" align="center" prop="updateTime" width="160" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['company:companyVoiceBlacklist:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['company:companyVoiceBlacklist:remove']"
          >删除</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="title" :visible.sync="open" width="560px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
<!--        <el-form-item label="黑名单级别" prop="businessType">-->
<!--          <el-select v-model="form.businessType" placeholder="请选择黑名单级别" style="width: 100%">-->
<!--            <el-option label="租户级" value="12" />-->
<!--            <el-option label="线路级" value="13" />-->
<!--          </el-select>-->
<!--        </el-form-item>-->
        <el-form-item label="手机号码" prop="targetValue">
          <el-input
            v-model="form.targetValue"
            :placeholder="form.id ? '不填写则不修改手机号' : '请输入手机号'"
            clearable
          />
        </el-form-item>
        <el-form-item label="拉黑原因" prop="reason">
          <el-input v-model="form.reason" type="textarea" :rows="2" placeholder="请输入拉黑原因" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">生效</el-radio>
            <el-radio :label="0">失效</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" :rows="2" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listApi,
  getApi,
  addApi,
  updateApi,
  delApi,
  exportApi,
  queryPhoneApi
} from '@/api/company/companyVoiceBlacklist'

export default {
  name: 'CompanyVoiceBlacklist',
  data() {
    return {
      loading: true,
      exportLoading: false,
      showSearch: true,
      total: 0,
      list: [],
      ids: [],
      single: true,
      multiple: true,
      title: '',
      open: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        businessType: null,
        targetType: 1,
        targetValue: null,
        status: null
      },
      form: {},
      rules: {
        // businessType: [
        //   { required: true, message: '请选择黑名单级别', trigger: 'change' }
        // ],
        targetValue: [
          {
            validator: (rule, value, callback) => {
              if (!this.isEditForm() && !this.normalizeTargetValue(value)) {
                callback(new Error('手机号不能为空'))
              } else {
                callback()
              }
            },
            trigger: ['blur', 'change']
          }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    isEditForm() {
      return this.form.id !== undefined && this.form.id !== null && this.form.id !== ''
    },
    normalizeTargetValue(value) {
      if (value == null) return ''
      return String(value).trim()
    },
    canQueryPhone(row) {
      return row && row.id != null && Number(row.targetType) !== 2 && Number(row.targetType) !== 3
    },
    getList() {
      this.loading = true
      listApi(this.queryParams).then(res => {
        this.list = res.rows || []
        this.total = res.total || 0
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    reset() {
      this.form = {
        id: null,
        businessType: '12',
        targetType: 1,
        targetValue: null,
        reason: null,
        status: 1,
        remark: null
      }
      this.resetForm('form')
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.resetForm('queryForm')
      this.queryParams.targetType = 1
      this.handleQuery()
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '新增黑名单'
    },
    handleUpdate(row) {
      this.reset()
      const id = row && row.id != null ? row.id : this.ids[0]
      if (!id) {
        this.$message.warning('请选择要修改的数据')
        return
      }
      getApi(id).then(res => {
        const data = res.data || {}
        this.form = {
          id: data.id,
          businessType: data.businessType || '12',
          targetType: 1,
          targetValue: null,
          reason: data.reason,
          status: data.status != null ? data.status : 1,
          remark: data.remark
        }
        this.open = true
        this.title = '修改黑名单'
      })
    },
    cancel() {
      this.open = false
      this.reset()
    },
    handleSubmitSuccess(msg) {
      this.msgSuccess(msg || '操作成功')
      this.open = false
      this.reset()
      this.getList()
    },
    handleSubmitError(response) {
      const msg = (response && response.msg) || '操作失败'
      this.msgError(msg)
    },
    submitForm() {
      this.$refs.form.validate(valid => {
        if (!valid) return
        const payload = {
          id: this.form.id,
          businessType: this.form.businessType,
          targetType: 1,
          status: this.form.status,
          reason: this.form.reason,
          remark: this.form.remark
        }
        const targetValue = this.normalizeTargetValue(this.form.targetValue)
        if (this.isEditForm()) {
          if (targetValue) {
            payload.targetValue = targetValue
          } else {
            delete payload.targetValue
          }
          updateApi(payload).then(response => {
            if (response && response.code === 200) {
              this.handleSubmitSuccess(response.msg)
            } else {
              this.handleSubmitError(response)
            }
          }).catch(() => {})
        } else {
          if (!targetValue) {
            this.msgError('手机号不能为空')
            return
          }
          payload.targetValue = targetValue
          addApi(payload).then(response => {
            if (response && response.code === 200) {
              this.handleSubmitSuccess(response.msg)
            } else {
              this.handleSubmitError(response)
            }
          }).catch(() => {})
        }
      })
    },
    handleDelete(row) {
      const ids = row && row.id != null ? row.id : this.ids.join(',')
      if (!ids) {
        this.$message.warning('请选择要删除的数据')
        return
      }
      this.$confirm('是否确认删除黑名单编号为"' + ids + '"的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return delApi(ids)
      }).then(response => {
        if (response && response.code === 200) {
          this.getList()
          this.msgSuccess(response.msg || '删除成功')
        } else {
          this.msgError((response && response.msg) || '删除失败')
        }
      }).catch(() => {})
    },
    handleExport() {
      this.$confirm('是否确认导出当前筛选条件下的黑名单数据?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.exportLoading = true
        const data = { ...this.queryParams }
        delete data.pageNum
        delete data.pageSize
        return exportApi(data)
      }).then(res => {
        this.download(res.msg)
        this.exportLoading = false
      }).catch(() => {
        this.exportLoading = false
      })
    },
    handlePhone(row) {
      if (!row || !row.id) return
      queryPhoneApi(row.id).then(res => {
        const mobile = (res && res.mobile) || (res && res.data && res.data.mobile)
        if (mobile) {
          this.$alert(mobile, '手机号', { confirmButtonText: '确定' })
        } else {
          this.msgError((res && res.msg) || '获取手机号失败')
        }
      })
    }
  }
}
</script>
