<template>
  <el-row :gutter="20">
    <!-- 左侧部门树 -->
    <el-col :span="4" :xs="24">
      <ContentWrap class="h-1/1">
        <DeptTree @node-click="handleDeptNodeClick" />
      </ContentWrap>
    </el-col>
    <el-col :span="20" :xs="24">
      <ContentWrap v-loading="loading">
    <ContentWrap>
      <!-- 搜索工作栏 -->
      <el-form
        class="-mb-15px"
        :model="queryParams"
        ref="queryFormRef"
        :inline="true"
        label-width="68px"
      >
        <el-form-item :label="t('monitor.deviceName')" prop="deviceName" style="margin-left: 25px">
          <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 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>
    </ContentWrap>

    <!-- 列表 -->
    <ContentWrap>
      <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"
              :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">
                  <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 src="@/assets/imgs/iot/device.png" class="w-full h-full" />
                  </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)"
                  >
                    <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>

      <!-- 列表视图 -->
      <el-table
        v-else
        v-loading="loading"
        :data="list"
        :stripe="true"
        :show-overflow-tooltip="true"

      >
        <el-table-column :label="t('monitor.serial')" width="60" align="center">
          <template #default="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-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>
        </el-table-column>
        <el-table-column :label="t('monitor.deviceCode')"  align="center" prop="deviceCode" />

        <el-table-column :label="t('monitor.category')" align="center" prop="assetClassName" />
        <el-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>
        </el-table-column>
        <el-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>
        </el-table-column>
        <el-table-column
          :label="t('monitor.latestDataTime')"
          align="center"
          prop="lastInlineTime"
          :formatter="dateFormatter"
          width="180px"
        />
        <el-table-column :label="t('monitor.operation')" align="center" min-width="120px">
          <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)"
            >
              {{t('monitor.check')}}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

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

<!--  &lt;!&ndash; 表单弹窗：添加/修改 &ndash;&gt;-->
<!--  <DeviceForm ref="formRef" @success="getList" />-->
<!--  &lt;!&ndash; 分组表单组件 &ndash;&gt;-->
<!--  <DeviceGroupForm ref="groupFormRef" @success="getList" />-->
<!--  &lt;!&ndash; 导入表单组件 &ndash;&gt;-->
<!--  <DeviceImportForm ref="importFormRef" @success="getList" />-->
</template>

<script setup lang="ts">
import { DICT_TYPE, getDictLabel } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import { DeviceApi, DeviceVO, DeviceStateEnum } from '@/api/iot/device/device'
import download from '@/utils/download'

import DeptTree from "@/views/system/user/DeptTree.vue";
import {IotDeviceApi} from "@/api/pms/device";

/** IoT 设备列表 */
defineOptions({ name: 'IoTDevice' })

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

const loading = ref(true) // 列表加载中
const list = ref<DeviceVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
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
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出加载状态
const products = ref<ProductVO[]>([]) // 产品列表
const deviceGroups = ref<DeviceGroupVO[]>([]) // 设备分组列表
const selectedIds = ref<number[]>([]) // 选中的设备编号数组
const viewMode = ref<'card' | 'list'>('card') // 视图模式状态
const defaultPicUrl = ref('@/src/assets/imgs/iot/device.png') // 默认设备图片
const defaultIconUrl = ref('/src/assets/svgs/iot/card-fill.svg') // 默认设备图标

/** 查询列表 */
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) => {
  if (time === null||time === undefined) {
    message.warning("没有数采数据")
    return
  }
  push({ name: 'TdDeviceDetail', params: { id,ifInline, time,name,code,dept } })
}


/** 导出方法 */
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>
