<template>
  <view>
    <view class="toolbar">
      <view class="header-actions">
        <view class="filter-tag" v-if="filterUserId">
          <text class="filter-tag-text">用户: {{ filterUserId }}</text>
          <text class="filter-tag-close" @click="clearUserFilter">x</text>
        </view>
        <input type="date" class="search-input date-input" v-model="dateFrom" placeholder="开始日期" />
        <text class="date-sep">~</text>
        <input type="date" class="search-input date-input" v-model="dateTo" placeholder="结束日期" />
        <input
          class="search-input"
          v-model="keyword"
          placeholder="搜索用户"
          placeholder-class="input-placeholder"
          @confirm="onSearch"
        />
        <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="data-table">
        <view class="t-header">
          <view class="t-row">
            <text class="t-th flex1">记录ID</text>
            <text class="t-th flex1">用户</text>
            <text class="t-th flex2">设备编号</text>
            <text class="t-th flex1">使用模式</text>
            <text class="t-th flex1">使用区域</text>
            <text class="t-th flex1">使用时长</text>
            <text class="t-th flex2">使用时间</text>
            <text class="t-th flex1">操作</text>
          </view>
        </view>
        <view class="t-body">
          <view class="t-row" v-for="item in records" :key="item.record_id">
            <text class="t-td flex1">{{ item.record_id ? String(item.record_id) : '-' }}</text>
            <text class="t-td flex1">{{ item.nickname || item.user_id || '-' }}</text>
            <text class="t-td flex2">{{ item.device_id || '-' }}</text>
            <text class="t-td flex1">
              <text :class="item.mode === 1 ? 'badge badge-blue' : 'badge badge-warning'">
                {{ item.mode === 1 ? '✨ 智能模式' : '🔄 普通模式' }}
              </text>
            </text>
            <text class="t-td flex1">{{ formatRegions(item.regions) }}</text>
            <text class="t-td flex1">{{ Math.floor((item.total_duration_ms || 0) / 60000) }}分</text>
            <text class="t-td flex2">{{ formatDate(item.start_time) }}</text>
            <text class="t-td flex1">
              <text class="action-link" @click="onDetail(item)">详情</text>
            </text>
          </view>
        </view>
      </view>

      <view class="empty-state" v-if="records.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'

var REGION_MAP = {
  1: '右区', 2: '左区', 4: '上区', 8: '中区', 16: '下区', 32: '左上区', 64: '右上区'
}

export default {
  name: 'RecordView',
  props: {
    user_id: { type: String, default: '' }
  },
  data() {
    return {
      records: [],
      total: 0,
      page: 1,
      pageSize: 20,
      keyword: '',
      dateFrom: '',
      dateTo: '',
      filterUserId: ''
    }
  },
  computed: {
    totalPages() {
      return Math.ceil(this.total / this.pageSize) || 1
    }
  },
  watch: {
    user_id: {
      immediate: true,
      handler(val) {
        this.filterUserId = val || ''
        this.loadRecords()
      }
    }
  },
  methods: {
    async loadRecords() {
      try {
        var params = {
          type: 'treatment',
          page: this.page,
          page_size: this.pageSize,
          keyword: this.keyword,
          user_id: this.filterUserId,
          date_from: this.dateFrom,
          date_to: this.dateTo
        }
        const data = await get('/api/v1/admin/records', params)
        this.records = data.records || []
        this.total = data.total || 0
      } catch (e) {
        uni.showToast({ title: '加载失败', icon: 'none' })
      }
    },
    onSearch() {
      this.page = 1
      this.loadRecords()
    },
    clearUserFilter() {
      this.filterUserId = ''
      this.page = 1
      this.loadRecords()
    },
    onPage(p) {
      this.page = p
      this.loadRecords()
    },
    formatRegions(mask) {
      if (!mask) return '-'
      var names = []
      var bits = [1, 2, 4, 8, 16, 32, 64]
      for (var i = 0; i < bits.length; i++) {
        if (mask & bits[i]) names.push(REGION_MAP[bits[i]])
      }
      return names.join(',') || '-'
    },
    onDetail(item) {
      var regions = this.formatRegions(item.regions)
      var mode = item.mode === 1 ? '智能模式' : '普通模式'
      var duration = Math.floor((item.total_duration_ms || 0) / 60000)
      var content = '用户: ' + (item.nickname || item.user_id || '-') +
        '\n设备: ' + (item.device_id || '-') +
        '\n模式: ' + mode +
        '\n区域: ' + regions +
        '\n时长: ' + duration + '分钟' +
        '\n时间: ' + this.formatDate(item.start_time)
      uni.showModal({
        title: '使用记录详情 #' + (item.record_id || ''),
        content: content,
        showCancel: false
      })
    },
    formatDate: formatDateUtil,
    async onExport() {
      try {
        const data = await get('/api/v1/admin/records', { page: 1, page_size: 9999, keyword: this.keyword, user_id: this.filterUserId, date_from: this.dateFrom, date_to: this.dateTo })
        var REGION_MAP = { 1: '右区', 2: '左区', 4: '上区', 8: '中区', 16: '下区', 32: '左上区', 64: '右上区' }
        const records = data.records || []
        exportCSV('records_' + new Date().toISOString().slice(0, 10) + '.csv',
          ['记录ID', '用户', '设备编号', '使用模式', '使用区域', '使用时长(分钟)', '使用时间'],
          records.map(function (r) {
            var regions = []
            var bits = [1, 2, 4, 8, 16, 32, 64]
            for (var i = 0; i < bits.length; i++) { if (r.regions & bits[i]) regions.push(REGION_MAP[bits[i]]) }
            return [r.record_id || '', r.nickname || r.user_id || '', r.device_id || '', r.mode === 1 ? '智能模式' : '普通模式', regions.join('+'), Math.floor((r.total_duration_ms || 0) / 60000), r.start_time ? r.start_time.slice(0, 10) : '']
          })
        )
        uni.showToast({ title: '导出成功', icon: 'success' })
      } catch (e) {
        uni.showToast({ title: '导出失败', icon: 'none' })
      }
    }
  }
}
</script>

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

.search-input {
  width: 160px;
}

.date-input {
  width: 120px;
}

.date-sep {
  color: #999;
  font-size: 14px;
}

.filter-tag {
  display: flex;
  align-items: center;
  gap: 4px;
  background: #fff0f6;
  border: 1px solid #E6508C;
  border-radius: 4px;
  padding: 4px 8px;
  font-size: 12px;
}

.filter-tag-text {
  color: #E6508C;
}

.filter-tag-close {
  color: #E6508C;
  cursor: pointer;
  font-weight: bold;
  margin-left: 4px;
}
</style>
