<template>
  <div class="app-container">
    <el-alert
      title="命中规则：企微发送「开」或「慢开」且含11位手机号时，若本库中任一启用记录的 phones 数组含该号码且备注非空，将直接回复备注，不请求 Telegram。"
      type="info"
      :closable="false"
      show-icon
      class="mb8"
    />

    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="手机号" prop="phoneQuery">
        <el-input v-model="queryParams.phoneQuery" placeholder="匹配任一条内的号码" clearable style="width: 200px" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="queryParams.remark" placeholder="备注关键词" clearable style="width: 200px" @keyup.enter.native="handleQuery" />
      </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-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['jarvis:tg:scalperPhone:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['jarvis:tg:scalperPhone:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['jarvis:tg:scalperPhone:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['jarvis:tg:scalperPhone:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="dataList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column label="手机号" align="center" prop="phones" min-width="180" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span>{{ formatPhonesCell(scope.row.phones) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="left" prop="remark" min-width="260" :show-overflow-tooltip="true" />
      <el-table-column label="状态" align="center" prop="status" width="100">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status === 1" type="success" size="small">启用</el-tag>
          <el-tag v-else type="info" size="small">禁用</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="updateTime" width="160">
        <template slot-scope="scope">
          <span>{{ scope.row.updateTime ? parseTime(scope.row.updateTime) : '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="160">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['jarvis:tg:scalperPhone:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['jarvis:tg:scalperPhone: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="88px">
        <el-form-item label="手机号" prop="phonesText">
          <el-input
            v-model="form.phonesText"
            type="textarea"
            :rows="4"
            placeholder="每行一个11位号，或用英文逗号 / 中文逗号 / 分号分隔"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" :rows="5" 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>
      <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 {
  listTgScalperPhone,
  getTgScalperPhone,
  delTgScalperPhone,
  addTgScalperPhone,
  updateTgScalperPhone
} from '@/api/jarvis/tgScalperPhone'

export default {
  name: 'TgScalperPhone',
  data() {
    const checkPhonesText = (rule, value, callback) => {
      if (!value || !String(value).trim()) {
        callback(new Error('请至少填写一个手机号'))
        return
      }
      const lines = String(value)
        .split(/[\n,，;；]+/)
        .map(s => s.trim())
        .filter(Boolean)
      for (const p of lines) {
        if (!/^1\d{10}$/.test(p)) {
          callback(new Error('须为11位数字：' + p))
          return
        }
      }
      callback()
    }
    return {
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      dataList: [],
      title: '',
      open: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        phoneQuery: null,
        remark: null,
        status: null
      },
      form: {},
      rules: {
        phonesText: [{ required: true, validator: checkPhonesText, trigger: 'blur' }],
        remark: [{ required: true, message: '备注不能为空', trigger: 'blur' }],
        status: [{ required: true, message: '请选择状态', trigger: 'change' }]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    formatPhonesCell(jsonStr) {
      if (!jsonStr) return '-'
      try {
        const arr = JSON.parse(jsonStr)
        return Array.isArray(arr) ? arr.join('、') : String(jsonStr)
      } catch (e) {
        return String(jsonStr)
      }
    },
    phonesJsonToText(jsonStr) {
      if (!jsonStr) return ''
      try {
        const arr = JSON.parse(jsonStr)
        return Array.isArray(arr) ? arr.join('\n') : ''
      } catch (e) {
        return ''
      }
    },
    textToPhonesJson(text) {
      const lines = String(text)
        .split(/[\n,，;；]+/)
        .map(s => s.trim())
        .filter(Boolean)
      const seen = new Set()
      const out = []
      for (const p of lines) {
        if (seen.has(p)) continue
        seen.add(p)
        out.push(p)
      }
      return JSON.stringify(out)
    },
    getList() {
      this.loading = true
      listTgScalperPhone(this.queryParams).then(response => {
        this.dataList = response.rows
        this.total = response.total
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    cancel() {
      this.open = false
      this.reset()
    },
    reset() {
      this.form = {
        id: null,
        phonesText: '',
        remark: null,
        status: 1
      }
      this.resetForm('form')
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.resetForm('queryForm')
      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.id || this.ids[0]
      getTgScalperPhone(id).then(response => {
        const d = response.data
        this.form = {
          id: d.id,
          phonesText: this.phonesJsonToText(d.phones),
          remark: d.remark,
          status: parseInt(d.status, 10)
        }
        this.open = true
        this.title = '修改黄牛电话'
      })
    },
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          const phones = this.textToPhonesJson(this.form.phonesText)
          const payload = {
            id: this.form.id,
            phones,
            remark: this.form.remark,
            status: this.form.status
          }
          if (this.form.id != null) {
            updateTgScalperPhone(payload).then(() => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addTgScalperPhone(payload).then(() => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    handleDelete(row) {
      const delIds = row.id || this.ids
      this.$modal.confirm('是否确认删除编号为"' + delIds + '"的数据？').then(() => {
        return delTgScalperPhone(delIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {})
    },
    handleExport() {
      this.download('jarvis/tgScalperPhone/export', { ...this.queryParams }, `tg_scalper_phone_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>

<style scoped>
.mb8 {
  margin-bottom: 8px;
}
</style>
