<template>
  <div class="store-page">
    <Breadcrumb />
    <a-card title="绑定解绑审计">
      <AppQueryFilter>
      <a-row class="query-row">
        <a-col :flex="'1000px'" class="query-main">
          <a-form class="queryForm app-query-form" :model="query" :label-col-props="{ span: 6 }" :wrapper-col-props="{ span: 18 }" label-align="left">
            <a-row :gutter="16">
              <a-col :span="12">
                <a-form-item field="student_num" label="学号">
                  <a-input v-model="query.student_num" placeholder="请输入学号" allow-clear />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item field="owner_uuid" label="所属用户UUID">
                  <a-input v-model="query.owner_uuid" placeholder="用于精确筛选（可选）" allow-clear />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item field="operator_uuid" label="操作者UUID">
                  <a-input v-model="query.operator_uuid" placeholder="用于精确筛选（可选）" allow-clear />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item field="action" label="动作">
                  <a-select v-model="query.action" placeholder="请选择动作" allow-clear>
                    <a-option value="">全部动作</a-option>
                    <a-option value="platform_bind">平台绑定</a-option>
                    <a-option value="platform_unbind">平台解绑</a-option>
                    <a-option value="bot_bind">机器人绑定</a-option>
                    <a-option value="bot_unbind">机器人解绑</a-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item field="source" label="来源">
                  <a-select v-model="query.source" placeholder="请选择来源" allow-clear>
                    <a-option value="">全部来源</a-option>
                    <a-option value="user_api">用户接口</a-option>
                    <a-option value="admin_api">管理员接口</a-option>
                    <a-option value="service_api">客服接口</a-option>
                    <a-option value="mcp_qq">机器人MCP</a-option>
                    <a-option value="mcp_work_order">工单MCP</a-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item field="queryTime" label="时间范围">
                  <a-range-picker v-model="query.queryTime" show-time format="YYYY-MM-DD HH:mm" value-format="x" />
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </a-col>
        <a-divider class="query-divider" style="height: 84px" direction="vertical" />
        <a-col :flex="1" class="app-query-actions">
          <a-space class="query-actions-space" direction="vertical" :size="18">
            <a-button type="primary" @click="search">搜索</a-button>
            <a-button @click="reset">重置</a-button>
          </a-space>
        </a-col>
      </a-row>
      </AppQueryFilter>

      <a-table :bordered="false"
        class="table"
        :data="data"
        :loading="loading"
        :scroll="{ x: 1450 }"
        :pagination="{
          showPageSize: true,
          showJumper: true,
          showTotal: true,
          pageSize: pagination.pagesize,
          current: pagination.current,
          total: pagination.total
        }"
        @page-change="onPageChange"
        @page-size-change="onPageSizeChange"
      >
        <template #columns>
          <a-table-column title="学号" data-index="student_num" :width="130" />
          <a-table-column title="乐跑账号" :width="180">
            <template #cell="{ record }">
              <a-space>
                <a-avatar :size="26">
                  <img :src="record.lepao_avatar || 'https://lepao-cloud.xxoo365.top/view.php/25aa126dc406974ff3579a99a2c6501a.png'" />
                </a-avatar>
                {{ record.lepao_name || '-' }}
              </a-space>
            </template>
          </a-table-column>
          <a-table-column title="所属用户" :width="180">
            <template #cell="{ record }">
              <a-space>
                <a-avatar :size="26">
                  <img :src="record.owner_avatar || 'https://lepao-cloud.xxoo365.top/view.php/25aa126dc406974ff3579a99a2c6501a.png'" />
                </a-avatar>
                {{ record.owner_username || '-' }}
              </a-space>
            </template>
          </a-table-column>
          <a-table-column title="动作" :width="130">
            <template #cell="{ record }">
              <a-tag>{{ actionLabel(record.action) }}</a-tag>
            </template>
          </a-table-column>
          <a-table-column title="来源" :width="150">
            <template #cell="{ record }">
              {{ sourceLabel(record.source) }}
            </template>
          </a-table-column>
          <a-table-column title="操作者" :width="180">
            <template #cell="{ record }">
              <a-space>
                <a-avatar :size="26">
                  <img :src="record.operator_avatar || 'https://lepao-cloud.xxoo365.top/view.php/25aa126dc406974ff3579a99a2c6501a.png'" />
                </a-avatar>
                {{ record.operator_username || '-' }}
              </a-space>
            </template>
          </a-table-column>
          <a-table-column title="详情" :width="220" ellipsis tooltip>
            <template #cell="{ record }">{{ formatDetail(record.detail_json) }}</template>
          </a-table-column>
          <a-table-column title="时间" :width="180">
            <template #cell="{ record }">{{ formatTime(record.created_at) }}</template>
          </a-table-column>
        </template>
      </a-table>
    </a-card>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted } from 'vue'
import { Notification } from '@arco-design/web-vue'
import { getAdminBindAuditList } from '@/api/lepao'

const loading = ref(false)
const data = ref([])
const query = reactive({
  student_num: '',
  owner_uuid: '',
  operator_uuid: '',
  action: '',
  source: '',
  queryTime: []
})
const pagination = reactive({
  total: 0,
  current: 1,
  pagesize: 20
})

const actionLabel = (action) => {
  const map = {
    platform_bind: '平台绑定',
    platform_unbind: '平台解绑',
    bot_bind: '机器人绑定',
    bot_unbind: '机器人解绑'
  }
  return map[action] || action
}

const sourceLabel = (source) => {
  const map = {
    user_api: '用户接口',
    admin_api: '管理员接口',
    service_api: '客服接口',
    mcp_qq: '机器人MCP',
    mcp_work_order: '工单MCP'
  }
  return map[source] || source
}

const formatDetail = (detail) => {
  if (!detail) return '-'
  if (typeof detail === 'string') return detail
  const keyMap = {
    via: '触发方式',
    sender: '发送者',
    old_owner_uuid: '原所属用户UUID',
    new_owner_uuid: '新所属用户UUID'
  }
  const valueMap = {
    AddAccount: '用户新增账号',
    DeleteAccount: '账号解绑接口',
    'AddAccount:auto_unbind_rebind': '新增账号自动解绑并重绑'
  }
  return Object.keys(detail)
    .map((key) => {
      const label = keyMap[key] || key
      const rawValue = detail[key]
      const value = (typeof rawValue === 'string' && valueMap[rawValue]) ? valueMap[rawValue] : rawValue
      return `${label}:${value}`
    })
    .join('；')
}

const formatTime = (time) => new Date(time).toLocaleString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' })

const getList = async () => {
  try {
    loading.value = true
    const res = await getAdminBindAuditList({
      ...query,
      current: pagination.current,
      pagesize: pagination.pagesize
    })
    if (!res || res.code !== 0)
      return Notification.error({
        title: '获取审计记录失败',
        content: res?.msg ?? '请稍后再试'
      })
    data.value = res.data || []
    pagination.total = res.pagination?.total || 0
  } catch (error) {
    Notification.error({
      title: '获取审计记录失败',
      content: error.message || '请稍后再试'
    })
  } finally {
    loading.value = false
  }
}

const search = () => {
  pagination.current = 1
  getList()
}

const reset = () => {
  query.student_num = ''
  query.owner_uuid = ''
  query.operator_uuid = ''
  query.action = ''
  query.source = ''
  query.queryTime = []
  pagination.current = 1
  getList()
}

const onPageChange = (page) => {
  pagination.current = page
  getList()
}
const onPageSizeChange = (size) => {
  pagination.pagesize = size
  pagination.current = 1
  getList()
}

onMounted(() => {
  getList()
})
</script>

<style scoped>
.query-row {
  margin-bottom: 10px;
}

.query-main {
  min-width: 0;
}

.query-actions-space {
  width: 100%;
}

.table {
  margin-top: 16px;
}

@media (max-width: 768px) {
  .query-row {
    display: block;
  }

  .query-divider {
    display: none;
  }

  .query-actions-space {
    margin-top: 4px;
    flex-direction: row !important;
    gap: 10px !important;
  }

  .query-actions-space :deep(.arco-btn) {
    flex: 1;
  }
}
</style>
