<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { getUserInfo } from '@/api/auth'
import { getEnterpriseDevices } from '@/api/enterprise'
import type { DeviceInfo } from '@/api/enterprise'

const enterpriseId = ref<number>(0)
const deviceList = ref<DeviceInfo[]>([])
const loading = ref(false)
const searchKeyword = ref('')
const page = ref(1)
const pageSize = 20
const hasMore = ref(true)

const stats = computed(() => {
  const total = deviceList.value.length
  return { total }
})

onMounted(() => {
  loadEnterpriseDevices()
})

async function loadEnterpriseDevices(isRefresh = false) {
  if (isRefresh) {
    page.value = 1
    hasMore.value = true
    deviceList.value = []
  }

  loading.value = true

  try {
    if (!enterpriseId.value) {
      const userInfo = uni.getStorageSync('user_info')
      if (userInfo?.enterprise_id) {
        enterpriseId.value = userInfo.enterprise_id
      } else {
        const apiUserInfo = await getUserInfo()
        if (!apiUserInfo.enterprise_id) {
          throw new Error('未找到企业ID')
        }
        enterpriseId.value = apiUserInfo.enterprise_id
      }
    }

    const params: any = {
      page: page.value,
      page_size: pageSize,
    }
    if (searchKeyword.value) {
      params.virtual_no = searchKeyword.value
    }
    const devicesData = await getEnterpriseDevices(enterpriseId.value, params)

    const items = devicesData?.items || []
    if (page.value === 1) {
      deviceList.value = items
    } else {
      deviceList.value.push(...items)
    }

    hasMore.value = items.length >= pageSize
    page.value++
  } catch (error: any) {
    console.error('加载企业设备列表失败:', error)
    if (error instanceof Error && error.message && !error.statusCode) {
      uni.$u.toast(error.message)
    }
  } finally {
    loading.value = false
  }
}

function viewDeviceDetail(device: any) {
  uni.navigateTo({
    url: `/pages/agent-system/asset-detail/index?virtual_no=${device.virtual_no}`,
  })
}

function formatAuthorizedTime(time: string) {
  if (!time) return '-'
  try {
    const date = new Date(time)
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    return `${year}-${month}-${day}`
  } catch {
    return time
  }
}

function handleSearch() {
  loadEnterpriseDevices(true)
}

function loadMore() {
  if (hasMore.value && !loading.value) {
    loadEnterpriseDevices()
  }
}

function onScroll(e: any) {
  const { scrollTop, scrollHeight, clientHeight } = e.target
  if (scrollHeight - scrollTop - clientHeight < 100) {
    loadMore()
  }
}
</script>

<template>
  <view class="bg-page min-h-screen flex flex-col">
    <!-- 搜索区域 -->
    <view class="bg-white px-4 pt-4 pb-3">
      <!-- 搜索框 -->
      <view class="relative flex items-center">
        <input
          v-model="searchKeyword"
          class="flex-1 h-10 bg-[#f1f5f9] rounded-full pl-4 pr-12 text-sm text-[#1e293b] placeholder-[#94a3b8]"
          placeholder="搜索设备名称 / 设备型号 / 虚拟号"
          @confirm="handleSearch"
        />
        <view class="absolute right-1 flex items-center">
          <view v-if="searchKeyword" class="w-8 h-8 flex items-center justify-center text-[#94a3b8]"
            @click="searchKeyword = ''">
            <i class="i-mdi-close-circle text-lg" />
          </view>
          <view class="w-8 h-8 flex items-center justify-center text-brand" @click="handleSearch">
            <i class="i-mdi-magnify text-xl" />
          </view>
        </view>
      </view>

      <!-- 统计信息 -->
      <view class="flex items-center justify-around gap-3 mt-3">
        <view class="flex items-center gap-1">
          <text class="text-12px text-[#999]">设备总数</text>
          <text class="text-14px font-700 text-brand">{{ stats.total }}</text>
        </view>
      </view>
    </view>

    <!-- 列表内容 -->
    <view class="flex-1 overflow-y-auto min-h-0" @scroll="onScroll">
      <view v-if="loading && deviceList.length === 0" class="pt-20 flex justify-center">
        <text class="text-14px text-[#64748b]">加载中...</text>
      </view>

      <view v-else-if="deviceList.length > 0" class="px-4 pb-4">
        <view
          v-for="device in deviceList"
          :key="device.virtual_no"
          class="bg-white rounded-12px p-4 mt-3"
          @click="viewDeviceDetail(device)"
        >
          <view class="flex items-center justify-between mb-2">
            <view class="flex items-center gap-2">
              <text class="text-15px font-600 text-[#212121]">{{ device.device_name || '-' }}</text>
              <text class="text-12px text-[#999]">{{ device.device_model || '-' }}</text>
            </view>
            <view class="px-3 py-1 rounded-full text-12px font-600 bg-[#e8f5e9] text-[#52c41a]">
              已授权
            </view>
          </view>

          <view class="text-12px text-[#666] mb-2">
            绑定卡数: {{ device.card_count || 0 }} 张
          </view>

          <view class="text-12px text-[#999] mb-2">
            虚拟号: {{ device.virtual_no || '-' }}
          </view>

          <view class="bg-[#f5f5f5] rounded-8px p-3">
            <view class="flex items-center justify-between">
              <text class="text-12px text-[#666]">授权时间</text>
              <text class="text-12px font-600 text-[#212121]">
                {{ formatAuthorizedTime(device.authorized_at) }}
              </text>
            </view>
          </view>
        </view>

        <view v-if="loading" class="py-4 text-center">
          <text class="text-sm text-[#64748b]">加载中...</text>
        </view>
        <view v-else-if="!hasMore" class="py-4 text-center">
          <text class="text-sm text-[#94a3b8]">没有更多了</text>
        </view>
      </view>

      <view v-else class="pt-16 flex flex-col items-center">
        <i class="i-mdi-package-variant-closed text-6xl text-[#cbd5e1] mb-3" />
        <text class="text-base text-[#64748b] mb-1">暂无数据</text>
        <text class="text-sm text-[#94a3b8]">{{ searchKeyword ? '未找到相关结果' : '暂无设备数据' }}</text>
      </view>
    </view>
  </view>
</template>

<style scoped>
</style>
