<template>
  <div class="devicePage">
    <div class="searchBar">
      <a-form layout="inline" @keydown.enter="searchHandler">
        <a-form-item label="设备ID">
          <a-input
            v-model:value.trim="searchState.deviceId"
            placeholder="设备ID"
            :maxlength="12"
            show-count
            allow-clear
            @change="clearHandler"
          />
        </a-form-item>
        <a-form-item label="设备名称">
          <a-input
            v-model:value.trim="searchState.deviceName"
            placeholder="设备名称"
            :maxlength="300"
            show-count
            allow-clear
            @change="clearHandler"
          />
        </a-form-item>
        <a-form-item label="设备状态">
          <a-select
            v-model:value="searchState.deviceStatus"
            style="width: 120px"
            :options="deviceStatusOptions"
            @change="searchHandler"
          ></a-select>
        </a-form-item>
        <a-form-item label="创建日期">
          <range-picker
            v-model:start="searchState.createTimeStart"
            v-model:end="searchState.createTimeEnd"
            @change="searchHandler"
          />
        </a-form-item>

        <a-form-item>
          <a-space>
            <a-button type="primary" @click="searchHandler"> 搜索 </a-button>
            <a-button @click="resetHandler"> 重置 </a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </div>

    <div class="tableCard">
      <div class="tableCard-header">
        <div class="tableCard-header-title">设备列表</div>
        <div class="tableCard-header-extra">
          <a-space>
            <a-button @click="addDeviceHandler">添加设备</a-button>
            <a-button type="primary" @click="uploadDeviceHandler">批量上传设备</a-button>
          </a-space>
        </div>
      </div>
      <a-table
        :columns="columns"
        :data-source="deviceList"
        :loading="loading"
        :pagination="false"
        :scroll="{ x: 'max-content' }"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'online'">
            <a-tag v-if="record.online === -1" :bordered="false" color="gray">未激活</a-tag>
            <a-tag v-if="record.online === 0" :bordered="false" color="red">离线</a-tag>
            <a-tag v-if="record.online === 1" :bordered="false" color="green">在线</a-tag>
          </template>
          <template v-if="column.key === 'action'">
            <a-button type="link" @click="detailHandler(record.devId, record.clientId)"
              >查看详情</a-button
            >
          </template>
        </template>
      </a-table>

      <base-pagination
        v-if="deviceTotal > 0"
        v-model:current="current"
        v-model:pageSize="pageSize"
        :total="deviceTotal"
        @change="paginationChange"
        @showSizeChange="paginationSizeChange"
      ></base-pagination>
    </div>

    <add-device-modal
      v-model:open="addDeviceOpen"
      title="添加设备"
      :options="tenantOptions"
      @success="searchHandler"
    ></add-device-modal>

    <upload-device-modal
      v-model:open="uploadDeviceOpen"
      title="批量上传设备"
      @success="searchHandler"
    ></upload-device-modal>
  </div>
</template>

<script setup lang="ts">
import * as deviceAPI from '@/api/device'
import { ref, onActivated } from 'vue'
import type { Device } from '@/api/device/types'
import { columns, deviceStatusOptions } from './const'
import addDeviceModal from './components/addDevice/index.vue'
import uploadDeviceModal from './components/uploadDevice/index.vue'
import { useSearch } from '@/hooks/useSearch'
import { useRouter } from 'vue-router'
import * as tenantAPI from '@/api/tenant'
import type { TenantItem } from '@/api/tenant/types'

const router = useRouter()

interface SearchData {
  deviceId: string // 设备ID
  deviceName: string // 设备名称
  deviceStatus: number | null // 设备状态
  createTimeStart: string // 创建时间开始
  createTimeEnd: string // 创建时间结束
}
// 默认搜索条件
const defaultSearch: SearchData = {
  deviceId: '',
  deviceName: '',
  deviceStatus: 1,
  createTimeStart: '',
  createTimeEnd: '',
}

const [searchState, resetHandler] = useSearch(defaultSearch, { afterReset: () => searchHandler() })

defineOptions({
  name: 'DeviceList',
})

const deviceList = ref<Device[]>()
const deviceTotal = ref<number>(0)
const current = ref<number>(1)
const pageSize = ref<number>(10)

// 分页变化
const paginationChange = (current: number, pageSize: number) => {
  console.log('change', current, pageSize)
  fetchList()
}
// 分页大小变化
const paginationSizeChange = (current: number, pageSize: number) => {
  console.log('showSizeChange', current, pageSize)
}

const loading = ref(false)
// 获取设备信息
const fetchList = async () => {
  try {
    loading.value = true
    const res = await deviceAPI.getDeviceList({
      pageNo: current.value,
      pageSize: pageSize.value,
      clientId: searchState.deviceId,
      devName: searchState.deviceName,
      createTimeStart: searchState.createTimeStart,
      createTimeEnd: searchState.createTimeEnd,
      online: searchState.deviceStatus,
      // tenantId: (route?.query?.tenantId as string) || null,
    })
    console.log('✅获取到设备信息', res)
    const { rows, total } = res.data
    deviceList.value = rows
    deviceTotal.value = Number(total)
    loading.value = false
  } catch (error) {
    console.error('❌ 获取设备信息失败', error)
    loading.value = false
  }
}

const tenantOptions = ref<{ label: string; value: string }[]>([])

// 获取租户列表
const fetchTenantList = async () => {
  try {
    const res = await tenantAPI.queryTenant({
      pageNo: 1,
      pageSize: 10000,
    })
    const { rows } = res.data
    tenantOptions.value = rows.map((item: TenantItem) => ({
      label: item.tenantName,
      value: item?.tenantId as string,
    }))
  } catch (err) {
    console.log('❌ 获取数据失败', err)
  }
}

onActivated(() => {
  fetchList()
  fetchTenantList()
})

// 搜索
const searchHandler = async () => {
  console.log('searchState', searchState)
  current.value = 1
  pageSize.value = 10
  await fetchList()
}

// 搜索条件变化时清空搜索结果
const clearHandler = (e: InputEvent) => {
  console.log('clearHandler', e, e.target, e.target?.value)
  if (!e.target?.value) {
    fetchList()
  }
}

// 详情
const detailHandler = (devId: string, clientId: string) => {
  console.log('点击详情', { devId, clientId })
  router.push({
    name: 'deviceDetail',
    query: {
      devId,
      clientId,
    },
  })
}

const addDeviceOpen = ref(false)
// 添加设备
const addDeviceHandler = () => {
  console.log('添加设备')
  addDeviceOpen.value = true
}

const uploadDeviceOpen = ref(false)
// 批量上传设备
const uploadDeviceHandler = () => {
  console.log('批量上传设备')
  uploadDeviceOpen.value = true
}
</script>

<style scoped lang="less">
.devicePage {
  .searchBar {
    padding: 20px;
    background-color: #fff;
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
    .ant-form {
      flex-grow: 1;
    }
    :deep(.ant-form-inline .ant-form-item) {
      margin-bottom: 16px !important;
    }
  }

  .tableCard {
    background-color: #fff;

    &-header {
      display: flex;
      justify-content: space-between;
      padding: 20px;
      &-title {
        font-size: 18px;
        font-weight: 600;
      }
    }
  }
}
</style>
