<template>
  <el-row :gutter="20">
    <!-- 左侧部门树 -->
    <DeptTree @node-click="handleDeptNodeClick" v-model:collapsed="isLeftContentCollapsed" />
    <el-col :xs="24" :span="isLeftContentCollapsed ? 24 : 20">
      <ContentWrap v-loading="loading" style="border: none">
        <div style="border: none" class="px-2 py-3 rounded-sm bg-white">
          <!-- 搜索工作栏 -->
          <el-form class="-mb-15px" :model="queryParams" ref="queryFormRef" :inline="true">
            <el-form-item
              :label="t('monitor.deviceName')"
              prop="deviceName"
              style="margin-left: 20px">
              <el-input
                v-model="queryParams.deviceName"
                :placeholder="t('monitor.nameHolder')"
                clearable
                @keyup.enter="handleQuery"
                class="!w-240px" />
            </el-form-item>
            <el-form-item :label="t('monitor.deviceCode')" prop="deviceCode">
              <el-input
                v-model="queryParams.deviceCode"
                :placeholder="t('monitor.codeHolder')"
                clearable
                @keyup.enter="handleQuery"
                class="!w-240px" />
            </el-form-item>
            <el-form-item :label="t('monitor.ifInline')" prop="ifInline">
              <el-select
                v-model="queryParams.ifInline"
                :placeholder="t('monitor.ifInlineHolder')"
                clearable
                class="!w-240px">
                <el-option
                  v-for="dict in getStrDictOptions(DICT_TYPE.IOT_DEVICE_STATUS)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="数采查询" prop="source">
              <el-select
                v-model="queryParams.source"
                placeholder="请选择数采来源"
                clearable
                class="!w-240px">
                <el-option label="全部" value="all" />
                <el-option label="网关设备" value="gateway" />
                <el-option label="中行北斗" value="zhbd" />
              </el-select>
            </el-form-item>
            <el-form-item class="float-right !mr-0 !mb-0">
              <el-button-group>
                <el-button
                  :type="viewMode === 'card' ? 'primary' : 'default'"
                  @click="viewMode = 'card'">
                  <Icon icon="ep:grid" />
                </el-button>
                <el-button
                  :type="viewMode === 'list' ? 'primary' : 'default'"
                  @click="viewMode = 'list'">
                  <Icon icon="ep:list" />
                </el-button>
              </el-button-group>
            </el-form-item>
            <el-form-item>
              <el-button @click="handleQuery">
                <Icon icon="ep:search" class="mr-5px" />
                {{ t('monitor.search') }}
              </el-button>
              <el-button @click="resetQuery">
                <Icon icon="ep:refresh" class="mr-5px" />
                {{ t('monitor.reset') }}
              </el-button>
              <el-button
                type="success"
                plain
                @click="handleExport"
                :loading="exportLoading"
                v-hasPermi="['iot:device:export']">
                <Icon icon="ep:download" class="mr-5px" /> 导出
              </el-button>
            </el-form-item>
          </el-form>
        </div>

        <!-- 列表 -->
        <ContentWrap style="border: none">
          <template v-if="viewMode === 'card'">
            <el-row :gutter="16">
              <el-col
                v-for="item in list"
                :key="item.id"
                :xs="24"
                :sm="12"
                :md="12"
                :lg="6"
                class="mb-4">
                <el-card
                  class="h-full transition-colors relative overflow-hidden custom-card"
                  :body-style="{ padding: '0' }">
                  <!-- 添加渐变背景层 -->
                  <div
                    class="absolute top-0 left-0 right-0 h-[50px] pointer-events-none"
                    :class="[
                      item.ifInline === 3
                        ? 'bg-gradient-to-b from-[#eefaff] to-transparent'
                        : 'bg-gradient-to-b from-[#fff1f1] to-transparent'
                    ]">
                  </div>
                  <div class="p-4 relative">
                    <!-- 标题区域 -->
                    <div class="flex items-center mb-3" style="height: 38px">
                      <div class="mr-2.5 flex items-center">
                        <img src="@/assets/svgs/iot/card-fill.svg" class="w-[18px] h-[18px]" />
                      </div>
                      <div class="text-[16px] font-600 flex-1">{{
                        item.deviceCode + '/' + item.deviceName
                      }}</div>
                      <!-- 添加设备状态标签 -->
                      <div class="inline-flex items-center">
                        <div
                          class="w-1 h-1 rounded-full mr-1.5"
                          :class="
                            item.ifInline === 3
                              ? 'bg-[var(--el-color-success)]'
                              : 'bg-[var(--el-color-danger)]'
                          ">
                        </div>
                        <el-text
                          class="!text-xs font-bold"
                          :type="item.ifInline === 3 ? 'success' : 'danger'">
                          {{ getDictLabel(DICT_TYPE.IOT_DEVICE_STATUS, item.ifInline) }}
                        </el-text>
                      </div>
                    </div>

                    <!-- 信息区域 -->
                    <div class="flex items-center text-[14px]">
                      <div class="flex-1">
                        <div class="mb-2.5 last:mb-0">
                          <span class="text-[#717c8e] mr-2.5">{{ t('monitor.deviceCode') }}</span>
                          <span class="text-[#0070ff]">
                            {{ item.deviceCode }}
                          </span>
                        </div>
                        <div class="mb-2.5 last:mb-0">
                          <span class="text-[#717c8e] mr-2.5">{{ t('monitor.category') }}</span>
                          <span class="text-[#0070ff]">
                            {{ item.assetClassName }}
                          </span>
                        </div>
                        <div class="mb-2.5 last:mb-0">
                          <span class="text-[#717c8e] mr-2.5">{{
                            t('monitor.latestDataTime')
                          }}</span>
                          <span class="text-[#0070ff]">
                            {{ item.lastInlineTime }}
                          </span>
                        </div>
                      </div>
                      <div class="w-[100px] h-[100px]">
                        <img
                          v-if="!item.carId"
                          src="@/assets/imgs/iot/device.png"
                          class="w-full h-full" />
                        <img v-if="item.carId" src="@/assets/imgs/iot/car.png" class="mt-4 ml-4" />
                      </div>
                    </div>

                    <!-- 分隔线 -->
                    <el-divider class="!my-3" />

                    <!-- 按钮 -->
                    <div class="flex items-center px-0">
                      <el-button
                        class="flex-1 !px-2 !h-[32px] text-[13px]"
                        type="warning"
                        plain
                        @click="
                          openDetail(
                            item.id,
                            item.ifInline,
                            item.lastInlineTime,
                            item.deviceName,
                            item.deviceCode,
                            item.deptName,
                            item.vehicleName,
                            item.carOnline ?? ''
                          )
                        ">
                        <Icon icon="ep:view" class="mr-1" />
                        {{ t('monitor.details') }}
                      </el-button>
                      <!--                  <div class="mx-[10px] h-[20px] w-[1px] bg-[#dcdfe6]"></div>-->
                    </div>
                  </div>
                </el-card>
              </el-col>
            </el-row>
          </template>

          <!-- 列表视图 -->
          <zm-table
            v-else
            :loading="loading"
            :data="list"
            :stripe="true"
            height="60vh"
            :show-overflow-tooltip="true">
            <zm-table-column :label="t('monitor.serial')" width="60" align="center">
              <template #default="scope">
                {{ scope.$index + 1 }}
              </template>
            </zm-table-column>
            <zm-table-column :label="t('monitor.deviceName')" align="center" prop="deviceName">
              <template #default="scope">
                <el-link @click="openDetail(scope.row.id)">{{ scope.row.deviceName }}</el-link>
              </template>
            </zm-table-column>
            <zm-table-column :label="t('monitor.deviceCode')" align="center" prop="deviceCode" />

            <zm-table-column :label="t('monitor.category')" align="center" prop="assetClassName" />
            <zm-table-column :label="t('monitor.status')" align="center" prop="deviceStatus">
              <template #default="scope">
                <dict-tag :type="DICT_TYPE.PMS_DEVICE_STATUS" :value="scope.row.deviceStatus" />
              </template>
            </zm-table-column>
            <zm-table-column :label="t('monitor.online')" align="center" prop="ifInline">
              <template #default="scope">
                <dict-tag :type="DICT_TYPE.IOT_DEVICE_STATUS" :value="scope.row.ifInline" />
              </template>
            </zm-table-column>
            <zm-table-column
              :label="t('monitor.latestDataTime')"
              align="center"
              prop="lastInlineTime"
              :formatter="dateFormatter"
              width="180px" />
            <zm-table-column
              :label="t('monitor.operation')"
              align="center"
              min-width="120px"
              action>
              <template #default="scope">
                <el-button
                  link
                  type="primary"
                  @click="
                    openDetail(
                      scope.row.id,
                      scope.row.ifInline,
                      scope.row.lastInlineTime,
                      scope.row.deviceName,
                      scope.row.deviceCode,
                      scope.row.deptName,
                      scope.row.vehicleName,
                      scope.row.carOnline ?? ''
                    )
                  ">
                  {{ t('monitor.check') }}
                </el-button>
              </template>
            </zm-table-column>
          </zm-table>

          <!-- 分页 -->
          <Pagination
            :total="total"
            v-model:page="queryParams.pageNo"
            v-model:limit="queryParams.pageSize"
            @pagination="getList" />
        </ContentWrap>
      </ContentWrap>
    </el-col>
  </el-row>
</template>

<script setup lang="ts">
import { DICT_TYPE, getDictLabel, getStrDictOptions } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import { DeviceApi, DeviceVO } from '@/api/iot/device/device'
import download from '@/utils/download'
import DeptTree from '@/views/system/user/DeptTree2.vue'
import { IotDeviceApi } from '@/api/pms/device'
/** IoT 设备列表 */
defineOptions({ name: 'IoTDeviceMonitor' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表加载中
const list = ref<DeviceVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
let isLeftContentCollapsed = ref(false)
const queryParams = reactive({
  pageNo: 1,
  pageSize: 12,
  deviceCode: undefined,
  deviceName: undefined,
  brand: undefined,
  model: undefined,
  deptId: undefined,
  deviceStatus: undefined,
  assetProperty: undefined,
  picUrl: undefined,
  remark: undefined,
  manufacturerId: undefined,
  supplierId: undefined,
  manDate: [],
  nameplate: undefined,
  expires: undefined,
  plPrice: undefined,
  plDate: [],
  plYear: undefined,
  plStartDate: [],
  plMonthed: undefined,
  plAmounted: undefined,
  remainAmount: undefined,
  infoId: undefined,
  infoType: undefined,
  infoName: undefined,
  infoRemark: undefined,
  infoUrl: undefined,
  templateJson: undefined,
  creator: undefined,
  ifInline: undefined,
  source: 'gateway'
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出加载状态
const products = ref<ProductVO[]>([]) // 产品列表
const selectedIds = ref<number[]>([]) // 选中的设备编号数组
const viewMode = ref<'card' | 'list'>('card') // 视图模式状态

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await IotDeviceApi.getIotDeviceTdPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  selectedIds.value = [] // 清空选择
  handleQuery()
}

// /** 添加/修改操作 */
// const formRef = ref()
// const openForm = (type: string, id?: number) => {
//   formRef.value.open(type, id)
// }

/** 打开详情 */
const { push } = useRouter()
const openDetail = (
  id: number,
  ifInline: string,
  time: string,
  name: string,
  code: string,
  dept: string,
  vehicle: string,
  carOnline: string
) => {
  if (time === null || time === undefined) {
    message.warning('没有数采数据')
    return
  }
  push({
    name: 'TdDeviceDetail',
    query: { id, ifInline, carOnline, time, name, code, dept, vehicle }
  })
}

/** 导出方法 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await DeviceApi.exportDeviceExcel(queryParams)
    download.excel(data, '物联网设备.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: DeviceVO[]) => {
  selectedIds.value = selection.map((item) => item.id)
}

//
// /** 添加到分组操作 */
// const groupFormRef = ref()
// const openGroupForm = () => {
//   groupFormRef.value.open(selectedIds.value)
// }
//
// /** 打开物模型数据 */
// const openModel = (id: number) => {
//   push({ name: 'IoTDeviceDetail', params: { id }, query: { tab: 'model' } })
// }
//
// /** 设备导入 */
// const importFormRef = ref()
// const handleImport = () => {
//   importFormRef.value.open()
// }

/** 初始化 **/
onMounted(async () => {
  await getList()
})
/** 处理部门被点击 */
const handleDeptNodeClick = async (row) => {
  queryParams.deptId = row.id
  await getList()
}
</script>
<style scoped>
.custom-card {
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
  transform: scale(1); /* 原始大小 */

  /* 关键：添加过渡动画，让变化更平滑 */
  transition: all 0.3s ease;
}
.custom-card:hover {
  /* 增强阴影效果，增加立体感 */
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.12);

  /* 轻微放大（1.03倍是比较合适的比例） */
  transform: scale(1.03);
}
</style>
