<template>
  <div class="asset-scan">
    <el-page-header @back="$router.back()" title="返回" content="扫码查询" />

    <el-row :gutter="20" style="margin-top: 20px">
      <!-- 左侧：扫码区域 -->
      <el-col :span="12">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>扫码查询</span>
              <el-button
                type="primary"
                :icon="cameraActive ? VideoPause : VideoPlay"
                @click="toggleCamera"
              >
                {{ cameraActive ? '关闭相机' : '打开相机' }}
              </el-button>
            </div>
          </template>

          <div class="scan-area">
            <!-- 视频预览 -->
            <div v-show="cameraActive" class="video-container">
              <video
                ref="videoRef"
                class="scan-video"
                autoplay
                muted
                playsinline
              />
              <div class="scan-overlay">
                <div class="scan-frame"></div>
                <p class="scan-tip">将二维码放入框内</p>
              </div>
            </div>

            <!-- 空状态 -->
            <div v-show="!cameraActive" class="scan-placeholder">
              <el-icon :size="80" color="#909399">
                <Camera />
              </el-icon>
              <p>点击上方按钮打开相机</p>
            </div>

            <!-- 手动输入 -->
            <el-divider>或手动输入</el-divider>
            <el-input
              v-model="inputCode"
              placeholder="请输入资产编码"
              clearable
              @keyup.enter="handleManualSearch"
            >
              <template #append>
                <el-button :icon="Search" @click="handleManualSearch">
                  查询
                </el-button>
              </template>
            </el-input>
          </div>
        </el-card>

        <!-- 扫码历史 -->
        <el-card style="margin-top: 20px">
          <template #header>
            <div class="card-header">
              <span>扫码历史</span>
              <el-button link type="primary" @click="clearHistory">
                清空
              </el-button>
            </div>
          </template>
          <div class="history-list">
            <el-empty v-if="scanHistory.length === 0" description="暂无扫码记录" />
            <div
              v-for="(item, index) in scanHistory"
              v-else
              :key="index"
              class="history-item"
              @click="viewHistoryItem(item)"
            >
              <div class="history-code">{{ item.assetCode }}</div>
              <div class="history-time">{{ formatTime(item.timestamp) }}</div>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 右侧：资产详情 -->
      <el-col :span="12">
        <el-card>
          <template #header>
            <span>资产详情</span>
          </template>

          <div v-if="loading" class="loading-container">
            <el-icon class="is-loading" :size="40">
              <Loading />
            </el-icon>
            <p>查询中...</p>
          </div>

          <div v-else-if="currentAsset" class="asset-detail">
            <!-- 基本信息 -->
            <el-descriptions title="基本信息" :column="1" border>
              <el-descriptions-item label="资产编码">
                {{ currentAsset.assetCode }}
              </el-descriptions-item>
              <el-descriptions-item label="资产名称">
                {{ currentAsset.assetName }}
              </el-descriptions-item>
              <el-descriptions-item label="设备类型">
                {{ currentAsset.deviceType?.typeName }}
              </el-descriptions-item>
              <el-descriptions-item label="品牌">
                {{ currentAsset.brand?.brandName || '-' }}
              </el-descriptions-item>
              <el-descriptions-item label="型号">
                {{ currentAsset.model || '-' }}
              </el-descriptions-item>
              <el-descriptions-item label="序列号">
                {{ currentAsset.serialNumber || '-' }}
              </el-descriptions-item>
              <el-descriptions-item label="所属网点">
                {{ currentAsset.organization?.orgName }}
              </el-descriptions-item>
              <el-descriptions-item label="位置">
                {{ currentAsset.location || '-' }}
              </el-descriptions-item>
              <el-descriptions-item label="状态">
                <el-tag :type="getStatusType(currentAsset.status)">
                  {{ getStatusName(currentAsset.status) }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="采购价格">
                {{ currentAsset.purchasePrice ? `¥${currentAsset.purchasePrice.toFixed(2)}` : '-' }}
              </el-descriptions-item>
              <el-descriptions-item label="采购日期">
                {{ currentAsset.purchaseDate || '-' }}
              </el-descriptions-item>
              <el-descriptions-item label="保修截止">
                {{ currentAsset.warrantyExpireDate || '-' }}
              </el-descriptions-item>
            </el-descriptions>

            <!-- 动态属性 -->
            <el-divider content-position="left">动态属性</el-divider>
            <el-descriptions v-if="hasDynamicAttributes" :column="2" border>
              <el-descriptions-item
                v-for="(value, key) in currentAsset.dynamicAttributes"
                :key="key"
                :label="key"
              >
                {{ value }}
              </el-descriptions-item>
            </el-descriptions>
            <el-empty v-else description="暂无动态属性" :image-size="80" />

            <!-- 操作按钮 -->
            <div class="detail-actions">
              <el-button type="primary" @click="viewFullDetail">
                查看完整详情
              </el-button>
              <el-button @click="resetDetail">
                清空
              </el-button>
            </div>
          </div>

          <el-empty v-else description="请扫码或输入资产编码查询" />
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Camera, VideoPlay, VideoPause, Search, Loading } from '@element-plus/icons-vue'
import { getAssetByCode } from '@/api/assets'
import { ASSET_STATUS } from '@/utils/constants'
import dayjs from 'dayjs'

const router = useRouter()

const videoRef = ref<HTMLVideoElement>()
const cameraActive = ref(false)
const inputCode = ref('')
const loading = ref(false)
const currentAsset = ref<any>(null)
const scanHistory = ref<any[]>([])

// 扫码音效
const playBeep = () => {
  const audioContext = new (window.AudioContext || (window as any).webkitAudioContext)()
  const oscillator = audioContext.createOscillator()
  const gainNode = audioContext.createGain()

  oscillator.connect(gainNode)
  gainNode.connect(audioContext.destination)

  oscillator.frequency.value = 800
  oscillator.type = 'sine'
  gainNode.gain.value = 0.3

  oscillator.start()
  setTimeout(() => {
    oscillator.stop()
    audioContext.close()
  }, 100)
}

// 切换相机
const toggleCamera = async () => {
  if (cameraActive.value) {
    stopCamera()
  } else {
    await startCamera()
  }
}

// 启动相机
const startCamera = async () => {
  try {
    const stream = await navigator.mediaDevices.getUserMedia({
      video: { facingMode: 'environment' }
    })

    if (videoRef.value) {
      videoRef.value.srcObject = stream
      cameraActive.value = true

      // TODO: 在这里集成二维码识别库（如@zxing/library）
      // 这里先模拟扫码功能
      startScanning()
    }
  } catch (error) {
    console.error('启动相机失败:', error)
    ElMessage.error('无法访问相机，请检查权限设置')
  }
}

// 停止相机
const stopCamera = () => {
  if (videoRef.value && videoRef.value.srcObject) {
    const stream = videoRef.value.srcObject as MediaStream
    stream.getTracks().forEach(track => track.stop())
    videoRef.value.srcObject = null
  }
  cameraActive.value = false
}

// 模拟扫码
let scanInterval: ReturnType<typeof setInterval> | null = null
const startScanning = () => {
  // TODO: 实际应该使用二维码识别库
  // 这里只是模拟演示，每隔几秒随机"扫描"一个编码
  scanInterval = setInterval(() => {
    if (!cameraActive.value) {
      if (scanInterval) clearInterval(scanInterval)
      return
    }

    // 模拟扫码成功（实际应该解析视频中的二维码）
    // const mockCodes = ['ASSET-20250124-0001', 'ASSET-20250124-0002', 'ASSET-20250124-0003']
    // const randomCode = mockCodes[Math.floor(Math.random() * mockCodes.length)]
    // handleScanSuccess(randomCode)
  }, 3000)
}

// 扫码成功
const handleScanSuccess = async (code: string) => {
  playBeep()
  await searchAsset(code)

  // 添加到历史记录
  if (currentAsset.value) {
    addToHistory(code)
  }

  // 扫码成功后暂停1秒再继续
  stopCamera()
  setTimeout(() => {
    // 自动重启相机或等待用户手动重启
  }, 1000)
}

// 手动搜索
const handleManualSearch = async () => {
  if (!inputCode.value.trim()) {
    ElMessage.warning('请输入资产编码')
    return
  }

  await searchAsset(inputCode.value)

  if (currentAsset.value) {
    addToHistory(inputCode.value)
  }
}

// 查询资产
const searchAsset = async (code: string) => {
  loading.value = true
  try {
    const asset = await getAssetByCode(code)
    currentAsset.value = asset
    ElMessage.success('查询成功')
  } catch (error) {
    ElMessage.error('未找到该资产')
    currentAsset.value = null
  } finally {
    loading.value = false
  }
}

// 添加到历史记录
const addToHistory = (code: string) => {
  const existingIndex = scanHistory.value.findIndex(item => item.assetCode === code)
  if (existingIndex !== -1) {
    scanHistory.value.splice(existingIndex, 1)
  }

  scanHistory.value.unshift({
    assetCode: code,
    timestamp: Date.now()
  })

  // 限制历史记录数量
  if (scanHistory.value.length > 20) {
    scanHistory.value = scanHistory.value.slice(0, 20)
  }

  // 保存到本地存储
  localStorage.setItem('scan_history', JSON.stringify(scanHistory.value))
}

// 加载历史记录
const loadHistory = () => {
  const stored = localStorage.getItem('scan_history')
  if (stored) {
    try {
      scanHistory.value = JSON.parse(stored)
    } catch (error) {
      console.error('加载历史记录失败', error)
    }
  }
}

// 清空历史记录
const clearHistory = () => {
  scanHistory.value = []
  localStorage.removeItem('scan_history')
  ElMessage.success('历史记录已清空')
}

// 查看历史记录项
const viewHistoryItem = async (item: any) => {
  inputCode.value = item.assetCode
  await searchAsset(item.assetCode)
}

// 格式化时间
const formatTime = (timestamp: number) => {
  return dayjs(timestamp).format('MM-DD HH:mm')
}

// 检查是否有动态属性
const hasDynamicAttributes = computed(() => {
  return currentAsset.value?.dynamicAttributes &&
    Object.keys(currentAsset.value.dynamicAttributes).length > 0
})

// 获取状态标签类型
const getStatusType = (status: string) => {
  const item = Object.values(ASSET_STATUS).find(item => item.value === status)
  return item?.type || ''
}

// 获取状态名称
const getStatusName = (status: string) => {
  const item = Object.values(ASSET_STATUS).find(item => item.value === status)
  return item?.label || status
}

// 查看完整详情
const viewFullDetail = () => {
  // 跳转到资产详情页或打开详情对话框
  ElMessage.info('完整详情功能开发中')
}

// 重置详情
const resetDetail = () => {
  currentAsset.value = null
  inputCode.value = ''
}

// 组件挂载
onMounted(() => {
  loadHistory()
})

// 组件卸载
onUnmounted(() => {
  stopCamera()
  if (scanInterval) {
    clearInterval(scanInterval)
  }
})
</script>

<style scoped lang="scss">
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.scan-area {
  .video-container {
    position: relative;
    width: 100%;
    height: 300px;
    background: #000;
    border-radius: 4px;
    overflow: hidden;

    .scan-video {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }

    .scan-overlay {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;

      .scan-frame {
        width: 200px;
        height: 200px;
        border: 2px solid #67c23a;
        border-radius: 8px;
        position: relative;

        &::before,
        &::after {
          content: '';
          position: absolute;
          width: 20px;
          height: 20px;
          border: 3px solid #67c23a;
        }

        &::before {
          top: -2px;
          left: -2px;
          border-right: none;
          border-bottom: none;
        }

        &::after {
          bottom: -2px;
          right: -2px;
          border-left: none;
          border-top: none;
        }
      }

      .scan-tip {
        margin-top: 20px;
        color: #fff;
        font-size: 14px;
      }
    }
  }

  .scan-placeholder {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 300px;
    color: #909399;

    p {
      margin-top: 16px;
      font-size: 14px;
    }
  }
}

.history-list {
  max-height: 400px;
  overflow-y: auto;

  .history-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px;
    border-bottom: 1px solid #ebeef5;
    cursor: pointer;
    transition: background-color 0.3s;

    &:hover {
      background-color: #f5f7fa;
    }

    &:last-child {
      border-bottom: none;
    }

    .history-code {
      font-size: 14px;
      color: #303133;
      font-weight: 500;
    }

    .history-time {
      font-size: 12px;
      color: #909399;
    }
  }
}

.asset-detail {
  .detail-actions {
    margin-top: 24px;
    display: flex;
    justify-content: center;
    gap: 12px;
  }
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 0;
  color: #909399;

  p {
    margin-top: 16px;
    font-size: 14px;
  }
}
</style>
