<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 filteredDevices = computed(() => {
  return deviceList.value
})

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

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

async function loadEnterpriseDevices() {
  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: 1,
      page_size: 100,
    }
    if (searchKeyword.value) {
      params.virtual_no = searchKeyword.value
    }
    const devicesData = await getEnterpriseDevices(enterpriseId.value, params)

    deviceList.value = devicesData?.items || []
  }
  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-search/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() {
  deviceList.value = []
  loadEnterpriseDevices()
}
</script>

<template>
  <view class="bg-[var(--bg-page)] min-h-screen pb-safe">
    <view v-if="loading" class="pt-20 center">
      <text class="text-14px text-[var(--text-secondary)]">加载中...</text>
    </view>

    <view v-else>
      <view class="bg-brand px-4 py-3 mx-4 mt-4 rounded-12px">
        <text class="text-11px text-white/60">企业授权设备</text>
        <text class="text-24px font-700 text-white block mt-1">{{ stats.total }}</text>
      </view>

      <view class="px-4 mt-4">
        <view class="flex items-center gap-2 mb-3">
          <input
            v-model="searchKeyword"
            class="flex-1 h-40px bg-[var(--bg-container)] rounded-full px-4 text-14px text-[var(--text-primary)]"
            placeholder="搜索设备名称 / 设备型号 / 虚拟号"
            placeholder-class="text-[var(--text-quaternary)]"
            @confirm="handleSearch"
          >
          <view
            class="px-4 h-40px bg-[var(--brand-primary)] text-white text-14px rounded-full flex items-center justify-center"
            @click="handleSearch"
          >
            搜索
          </view>
        </view>
      </view>

      <view class="px-4">
        <view v-if="filteredDevices.length > 0" class="space-y-3 pb-4">
          <view
            v-for="device in filteredDevices"
            :key="device.virtual_no"
            class="bg-[var(--bg-container)] rounded-12px p-4"
            @click="viewDeviceDetail(device)"
          >
            <view class="flex items-center justify-between">
              <view>
                <text class="text-15px font-600 text-[var(--text-primary)]">{{ device.device_name || '-' }}</text>
                <text class="text-12px text-[var(--text-tertiary)] ml-2">{{ 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="mt-3 text-12px text-[var(--text-tertiary)]">
              绑定卡数: {{ device.card_count || 0 }} 张
            </view>

            <view class="mt-3 text-13px text-[var(--text-secondary)]">
              <text class="mr-4">虚拟号: {{ device.virtual_no || '-' }}</text>
            </view>

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

        <view v-else class="pt-16 center">
          <text class="text-14px text-[var(--text-secondary)]">{{ searchKeyword ? '未找到匹配的设备' : '暂无设备数据' }}</text>
        </view>
      </view>

      <view class="h-16" />
    </view>
  </view>
</template>

<style scoped>
.center {
  display: flex;
  align-items: center;
  justify-content: center;
}

.space-y-3 > view:not(:last-child) {
  margin-bottom: 12px;
}
</style>
