<template>
  <view>
    <view class="back-link" @click="$emit('navigate', 'device')">‹ 返回设备列表</view>

    <view class="page-card">
      <view class="page-header">
        <text class="page-title">📱 设备详情 - {{ device ? device.device_id : '' }}</text>
        <button class="btn-danger btn-sm" v-if="device && device.bound_user" @click="onUnbind">解绑设备</button>
      </view>

      <view class="info-grid" v-if="device">
        <view class="info-item">
          <text class="info-label">设备编号</text>
          <text class="info-value">{{ device.device_id }}</text>
        </view>
        <view class="info-item">
          <text class="info-label">状态</text>
          <text class="info-value"><text class="badge badge-success">{{ statusMap[device.status] || '未知' }}</text></text>
        </view>
        <view class="info-item">
          <text class="info-label">绑定用户</text>
          <text class="info-value">{{ device.bound_user || '未绑定' }}</text>
        </view>
        <view class="info-item">
          <text class="info-label">绑定时间</text>
          <text class="info-value">{{ device.activated_at || '-' }}</text>
        </view>
        <view class="info-item">
          <text class="info-label">固件版本</text>
          <view class="info-value-row">
            <text class="info-value">{{ device.firmware_version || '-' }}</text>
            <button class="btn-default btn-xs" @click="onCheckUpdate">检查更新</button>
          </view>
        </view>
        <view class="info-item">
          <text class="info-label">电池电量</text>
          <text class="info-value">{{ device.battery != null ? device.battery + '%' : '-' }}</text>
        </view>
        <view class="info-item">
          <text class="info-label">累计使用</text>
          <text class="info-value">{{ device.total_usage || '-' }}</text>
        </view>
        <view class="info-item">
          <text class="info-label">最后在线</text>
          <text class="info-value">{{ device.last_online_at || '-' }}</text>
        </view>
      </view>
    </view>

    <view class="page-card" v-if="device && device.binding_history">
      <view class="card-title">绑定记录</view>
      <view class="data-table">
        <view class="t-header">
          <view class="t-row">
            <text class="t-th flex2">用户</text>
            <text class="t-th flex2">绑定时间</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="(b, idx) in device.binding_history" :key="idx">
            <text class="t-td flex2">{{ b.nickname || '-' }}</text>
            <text class="t-td flex2">{{ formatDate(b.bind_time) }}</text>
            <text class="t-td flex2">{{ b.unbind_time ? formatDate(b.unbind_time) : '-' }}</text>
            <text class="t-td flex1">
              <text :class="b.bind_status === 1 ? 'badge badge-success' : 'badge badge-default'">
                {{ b.bind_status === 1 ? '有效' : '已解绑' }}
              </text>
            </text>
          </view>
        </view>
      </view>
    </view>

    <view class="page-card" v-if="device && device.recent_treatments">
      <view class="card-title">最近使用记录</view>
      <view class="data-table">
        <view class="t-header">
          <view class="t-row">
            <text class="t-th flex2">用户</text>
            <text class="t-th flex1">时长</text>
            <text class="t-th flex2">时间</text>
          </view>
        </view>
        <view class="t-body">
          <view class="t-row" v-for="(t, idx) in device.recent_treatments" :key="idx">
            <text class="t-td flex2">{{ t.nickname || '-' }}</text>
            <text class="t-td flex1">{{ Math.floor((t.total_duration_ms || 0) / 60000) }}分钟</text>
            <text class="t-td flex2">{{ formatDate(t.started_at) }}</text>
          </view>
        </view>
      </view>
    </view>

    <view class="action-row">
      <button class="btn-primary" @click="onCommand(4)">查询状态</button>
      <button class="btn-default" @click="onViewLogs">查看完整日志</button>
    </view>
  </view>
</template>

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

export default {
  props: {
    device_id: { type: String, default: '' }
  },
  data() {
    return {
      device: null,
      deviceId: '',
      statusMap: { 1: '未激活', 2: '在线', 3: '离线', 4: '故障' }
    }
  },
  watch: {
    device_id: {
      immediate: true,
      handler(val) {
        if (val) {
          this.deviceId = val
          this.loadDevice()
        }
      }
    }
  },
  methods: {
    async loadDevice() {
      try {
        this.device = await get('/api/v1/admin/devices/' + this.deviceId)
      } catch (e) {
        uni.showToast({ title: '加载失败', icon: 'none' })
      }
    },
    async onCommand(type) {
      try {
        await post('/api/v1/admin/devices/' + this.deviceId + '/command', { opcode: type })
        uni.showToast({ title: '指令已发送', icon: 'success' })
      } catch (e) {
        uni.showToast({ title: '发送失败', icon: 'none' })
      }
    },
    onUnbind() {
      uni.showModal({
        title: '确认解绑',
        content: '确定要解绑该设备吗？',
        success: async (res) => {
          if (res.confirm) {
            try {
              await post('/api/v1/admin/devices/' + this.deviceId + '/unbind', {})
              uni.showToast({ title: '已解绑', icon: 'success' })
              this.loadDevice()
            } catch (e) {
              uni.showToast({ title: '解绑失败', icon: 'none' })
            }
          }
        }
      })
    },
    onViewLogs() {
      this.$emit('navigate', 'log', { device_id: this.deviceId })
    },
    async onCheckUpdate() {
      uni.showToast({ title: '正在检查更新...', icon: 'none' })
      try {
        const data = await get('/api/v1/admin/firmware')
        const records = data.records || []
        const latest = records.filter(r => r.status === 1).sort((a, b) => b.firmware_id - a.firmware_id)[0]
        if (!latest) {
          uni.showToast({ title: '暂无固件信息', icon: 'none' })
          return
        }
        const current = this.device && this.device.firmware_version
        if (current && current === latest.version) {
          uni.showToast({ title: '当前已是最新版本', icon: 'success' })
        } else {
          uni.showToast({ title: '发现新版本 v' + latest.version, icon: 'none', duration: 3000 })
        }
      } catch (e) {
        uni.showToast({ title: '检查更新失败', icon: 'none' })
      }
    },
    formatDate: formatDateUtil
  }
}
</script>

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

.back-link {
  color: #E6508C;
  font-size: 14px;
  margin-bottom: 16px;
  cursor: pointer;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.info-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
}

.info-item {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.info-label {
  font-size: 13px;
  color: #999;
}

.info-value {
  font-size: 14px;
  color: #333;
}

.info-value-row {
  display: flex;
  align-items: center;
  gap: 8px;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 16px;
}

.btn-primary {
  padding: 0 20px;
  height: 36px;
  font-size: 14px;
  line-height: 36px;
}

.btn-default {
  padding: 0 20px;
  height: 36px;
  font-size: 14px;
  line-height: 36px;
}

.btn-danger {
  background: #ff4d4f;
  color: #fff;
  border: none;
  border-radius: 6px;
  cursor: pointer;
}

.btn-sm {
  height: 32px;
  padding: 0 16px;
  font-size: 14px;
  line-height: 32px;
}

.btn-xs {
  height: 24px;
  padding: 0 8px;
  font-size: 12px;
  line-height: 24px;
}

.action-row {
  display: flex;
  gap: 12px;
  margin-top: 8px;
}
</style>
