<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="88px">
      <el-form-item label="发送人" prop="fromUserName">
        <el-input v-model="queryParams.fromUserName" placeholder="UserID" clearable style="width: 160px" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="MsgId" prop="msgId">
        <el-input v-model="queryParams.msgId" placeholder="精确匹配" clearable style="width: 200px" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="AgentID" prop="agentId">
        <el-input v-model="queryParams.agentId" placeholder="应用ID" clearable style="width: 120px" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="会话中" prop="sessionActive">
        <el-select v-model="queryParams.sessionActive" placeholder="全部" clearable style="width: 100px">
          <el-option label="是" :value="1" />
          <el-option label="否" :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item label="接收时间">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          value-format="yyyy-MM-dd"
          range-separator="至"
          start-placeholder="开始"
          end-placeholder="结束"
          style="width: 240px"
        />
      </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="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['jarvis:wecom:inboundTrace:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-delete-solid"
          size="mini"
          @click="openCleanDialog"
          v-hasPermi="['jarvis:wecom:inboundTrace:remove']"
        >清空测试数据</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="list" border @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column label="ID" prop="id" width="72" />
      <el-table-column label="AgentID" prop="agentId" width="96" />
      <el-table-column label="发送人" prop="fromUserName" width="120" show-overflow-tooltip />
      <el-table-column label="内容摘要" prop="content" min-width="180" show-overflow-tooltip />
      <el-table-column label="微信时间" prop="wxMsgTime" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.wxMsgTime) || '—' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="服务端接收" prop="createTime" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="回复摘要" prop="replyContent" min-width="160" show-overflow-tooltip />
      <el-table-column label="会话空间" width="88" align="center">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.sessionActive === 1" type="warning" size="small">进行中</el-tag>
          <el-tag v-else type="info" size="small">无</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="场景/步骤" width="140" show-overflow-tooltip>
        <template slot-scope="scope">
          <span v-if="scope.row.sessionScene">{{ scope.row.sessionScene }} / {{ scope.row.sessionStep || '—' }}</span>
          <span v-else>—</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="120" align="center" fixed="right">
        <template slot-scope="scope">
          <el-button type="text" size="mini" icon="el-icon-view" @click="openDetail(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="cleanOpen" width="520px" append-to-body @close="resetCleanForm">
      <p style="color:#E6A23C;margin:0 0 12px 0;">将按下方勾选删除数据，生产环境请谨慎操作。</p>
      <el-checkbox v-model="cleanOptions.clearTraceTable">消息追踪表（wecom_inbound_trace 全部行）</el-checkbox>
      <br><br>
      <el-checkbox v-model="cleanOptions.clearWecomSessions">企微多轮会话 Redis（interaction_state:wecom:*）</el-checkbox>
      <br><br>
      <el-checkbox v-model="cleanOptions.clearAdhocQueue">分享链待扫描队列（logistics:adhoc:pending:queue）</el-checkbox>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cleanOpen = false">取 消</el-button>
        <el-button type="danger" @click="submitClean">确 定清理</el-button>
      </div>
    </el-dialog>

    <el-dialog title="消息详情" :visible.sync="detailOpen" width="720px" append-to-body>
      <el-descriptions :column="1" border size="small" v-if="detail">
        <el-descriptions-item label="MsgId">{{ detail.msgId || '—' }}</el-descriptions-item>
        <el-descriptions-item label="AgentID">{{ detail.agentId || '—' }}</el-descriptions-item>
        <el-descriptions-item label="CorpId">{{ detail.corpId || '—' }}</el-descriptions-item>
        <el-descriptions-item label="发送人">{{ detail.fromUserName }}</el-descriptions-item>
        <el-descriptions-item label="微信发送时间">{{ parseTime(detail.wxMsgTime) || '—' }}</el-descriptions-item>
        <el-descriptions-item label="服务端接收">{{ parseTime(detail.createTime) }}</el-descriptions-item>
        <el-descriptions-item label="用户内容">
          <pre class="trace-pre">{{ detail.content || '（空）' }}</pre>
        </el-descriptions-item>
        <el-descriptions-item label="Jarvis 回复">
          <pre class="trace-pre">{{ detail.replyContent || '（空）' }}</pre>
        </el-descriptions-item>
        <el-descriptions-item label="会话">
          <span v-if="detail.sessionActive === 1">进行中 — {{ detail.sessionScene }} / {{ detail.sessionStep }}</span>
          <span v-else>本次处理后无未完成的多轮会话</span>
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script>
import { listWecomInboundTrace, delWecomInboundTrace, getWecomInboundTrace, cleanWecomInboundTraceTestData } from '@/api/jarvis/wecomInboundTrace'

export default {
  name: 'WecomInboundTrace',
  data() {
    return {
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      total: 0,
      list: [],
      dateRange: [],
      detailOpen: false,
      detail: null,
      cleanOpen: false,
      cleanOptions: {
        clearTraceTable: true,
        clearWecomSessions: true,
        clearAdhocQueue: true
      },
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        fromUserName: null,
        msgId: null,
        agentId: null,
        sessionActive: null
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.loading = true
      const q = { ...this.queryParams, params: {} }
      if (this.dateRange && this.dateRange.length === 2) {
        q.params = { beginTime: this.dateRange[0], endTime: this.dateRange[1] }
      }
      listWecomInboundTrace(q).then(res => {
        this.list = res.rows
        this.total = res.total
        this.loading = false
      }).catch(() => { this.loading = false })
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.dateRange = []
      this.resetForm('queryForm')
      this.handleQuery()
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    handleDelete() {
      const ids = this.ids
      this.$modal.confirm('是否确认删除选中的追踪记录？').then(() => {
        return delWecomInboundTrace(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {})
    },
    openDetail(row) {
      getWecomInboundTrace(row.id).then(res => {
        this.detail = res.data
        this.detailOpen = true
      })
    },
    openCleanDialog() {
      this.resetCleanForm()
      this.cleanOpen = true
    },
    resetCleanForm() {
      this.cleanOptions = {
        clearTraceTable: true,
        clearWecomSessions: true,
        clearAdhocQueue: true
      }
    },
    submitClean() {
      if (!this.cleanOptions.clearTraceTable && !this.cleanOptions.clearWecomSessions && !this.cleanOptions.clearAdhocQueue) {
        this.$modal.msgWarning('请至少勾选一项')
        return
      }
      this.$modal.confirm('确认按勾选项清理测试数据？此操作不可恢复。').then(() => {
        return cleanWecomInboundTraceTestData(this.cleanOptions)
      }).then(res => {
        this.cleanOpen = false
        this.getList()
        const d = res.data || {}
        const parts = []
        if (d.traceRowsDeleted != null) parts.push('追踪表删除 ' + d.traceRowsDeleted + ' 行')
        if (d.wecomSessionKeysDeleted != null) parts.push('会话键 ' + d.wecomSessionKeysDeleted + ' 个')
        if (d.adhocQueueCleared) parts.push('adhoc 队列已删')
        this.$modal.msgSuccess(parts.length ? parts.join('；') : '已执行')
      }).catch(() => {})
    }
  }
}
</script>

<style scoped>
.trace-pre {
  white-space: pre-wrap;
  word-break: break-word;
  margin: 0;
  font-family: inherit;
  font-size: 13px;
  max-height: 280px;
  overflow: auto;
}
</style>
