<template>
  <view>
    <view class="toolbar">
      <view class="header-actions">
        <input
          class="search-input"
          v-model="filters.type"
          placeholder="搜索操作类型"
          placeholder-class="input-placeholder"
        />
        <button class="btn-primary btn-sm" @click="onSearch">搜索</button>
        <button class="btn-default btn-sm" @click="onExport">导出</button>
      </view>
    </view>

    <view class="page-card">
      <view class="log-list">
        <view class="log-item" v-for="item in logs" :key="item.log_id">
          <text class="log-time">{{ formatDate(item.created_at) }}</text>
          <view class="log-content">
            <text :class="actorBadge(item)">{{ actorLabel(item) }}</text>
            <text class="log-text">
              <text class="log-action">{{ actionLabel(item.action) }}</text>
              <text class="log-detail" v-if="item.detail"> — {{ item.detail }}</text>
            </text>
            <text class="log-meta" v-if="item.ip">IP: {{ item.ip }}</text>
          </view>
        </view>
      </view>

      <view class="empty-state" v-if="logs.length === 0">暂无数据</view>

      <view class="pagination">
        <button class="btn-page" :disabled="page <= 1" @click="onPage(page - 1)">‹</button>
        <button class="btn-page active">{{ page }}</button>
        <button class="btn-page" :disabled="page >= totalPages" @click="onPage(page + 1)">›</button>
        <text class="page-info">共 {{ totalPages }} 页</text>
      </view>
    </view>
  </view>
</template>

<script>
import { get } from '../utils/request'
import { exportCSV } from '../utils/export'
import { formatDate as formatDateUtil } from '../utils/format'

export default {
  name: 'LogView',
  props: {
    device_id: { type: String, default: '' }
  },
  data() {
    return {
      logs: [],
      total: 0,
      page: 1,
      pageSize: 20,
      filters: { type: '', device_id: '' }
    }
  },
  computed: {
    totalPages() {
      return Math.ceil(this.total / this.pageSize) || 1
    }
  },
  watch: {
    device_id: {
      immediate: true,
      handler(val) {
        this.filters.device_id = val || ''
        this.loadLogs()
      }
    }
  },
  methods: {
    async loadLogs() {
      try {
        var params = { page: this.page, page_size: this.pageSize }
        if (this.filters.type) params.type = this.filters.type
        if (this.filters.device_id) params.device_id = this.filters.device_id
        const data = await get('/api/v1/admin/logs', params)
        this.logs = data.records || []
        this.total = data.total || 0
      } catch (e) {
        uni.showToast({ title: '加载失败', icon: 'none' })
      }
    },
    onSearch() {
      this.page = 1
      this.loadLogs()
    },
    onPage(p) {
      this.page = p
      this.loadLogs()
    },
    actorLabel(item) {
      if (item.admin_id) return '管理员 #' + item.admin_id
      if (item.user_id) return '用户 #' + item.user_id
      return '系统'
    },
    actorBadge(item) {
      if (item.admin_id) return 'badge badge-pink'
      if (item.user_id) return 'badge badge-green'
      return 'badge badge-blue'
    },
    actionLabel(action) {
      var map = {
        admin_login: '管理员登录', admin_device_create: '创建设备', admin_device_unbind: '后台解绑',
        admin_device_command: '下发指令', user_register: '用户注册', user_login: '用户登录',
        device_bind: '设备绑定', device_unbind: '设备解绑', treatment_sync: '使用记录同步',
        subscription_verify: '订阅核销'
      }
      return map[action] || action
    },
    formatDate: formatDateUtil,
    async onExport() {
      try {
        var params = { page: 1, page_size: 9999 }
        if (this.filters.type) params.type = this.filters.type
        const data = await get('/api/v1/admin/logs', params)
        const records = data.records || []
        exportCSV('logs_' + new Date().toISOString().slice(0, 10) + '.csv',
          ['时间', '操作类型', '操作详情', '操作者'],
          records.map(function (r) {
            return [r.created_at ? r.created_at.slice(0, 19).replace('T', ' ') : '', r.action || '', r.detail || '', r.admin_id ? '管理员#' + r.admin_id : r.user_id ? '用户#' + r.user_id : '系统']
          })
        )
        uni.showToast({ title: '导出成功', icon: 'success' })
      } catch (e) {
        uni.showToast({ title: '导出失败', icon: 'none' })
      }
    }
  }
}
</script>

<style scoped>
@import '../styles/common.css';

.log-list {
  margin-top: 8px;
}

.log-item {
  display: flex;
  align-items: flex-start;
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
}

.log-time {
  width: 140px;
  flex-shrink: 0;
  font-size: 13px;
  color: #999;
  padding-top: 2px;
}

.log-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.badge {
  width: fit-content;
}

.badge-pink {
  background: #fff0f6;
  color: #E6508C;
}

.badge-green {
  background: #f6ffed;
  color: #52c41a;
}

.log-text {
  font-size: 14px;
  line-height: 22px;
  color: #666;
}

.log-action {
  color: #333;
  font-weight: 500;
}

.log-detail {
  color: #999;
}

.log-meta {
  font-size: 12px;
  color: #bbb;
  margin-top: 2px;
}
</style>
