<template>
  <!-- 搜索工作栏 -->
  <ContentWrap>
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="设备名称" prop="name">
        <el-input
          v-model="queryParams.devicename"
          placeholder="请输入设备名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="设备状态" prop="status">
        <el-select
          v-model="queryParams.devicestatus"
          placeholder="请选择设备状态"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.IOT_DEVICE_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <!-- 设备类型 --> 
      <el-form-item label="设备类型" prop="type">
        <el-select
          v-model="queryParams.devicetype"
          placeholder="请选择设备类型"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.IOT_DEVICE_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 设备卡片展示区域 -->
  <ContentWrap>
    <div class="device-cards-container">
      <device-card
        v-for="device in deviceList"
        :key="device.id"
        :device-info="device"
        @action="handleDeviceAction"
      />
    </div>
    <!-- 分页组件 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="handleQuery"
    />
  </ContentWrap>

  <!-- 设备表单 -->
  <DeviceForm ref="deviceFormRef" @success="handleQuery" />
  <DetailsForm ref="detailsFormRef" @success="handleQuery" />
  <!-- 心电数据组件 -->
  <ECG_datas ref="ecgDataRef" />
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElForm, ElFormItem, ElInput, ElSelect, ElOption, ElButton } from 'element-plus'
import { getIntDictOptions,getStrDictOptions } from '@/utils/dict'
import { DICT_TYPE } from '@/utils/dict'
import DeviceCard from '../devices/devices_cards.vue'
import DeviceForm from './DevFrom.vue'
import DetailsForm from './DetailsForm.vue'
import { DeviceApi } from '@/api/device'
import { DeviceuserApi } from '@/api/deviceuser'
import { getUserProfile } from '@/api/system/user/profile'
import ECG_datas from './Device_Data_Components/ECG_datas.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
// 查询参数
interface QueryParams {
  devicename: string
  devicestatus: number | undefined
  devicetype: string | undefined
  pageNo: number
  pageSize: number
  orgid: number
}

const queryParams = reactive<QueryParams>({
  devicename: '',
  devicestatus: undefined,
  devicetype: '',
  pageNo: 1,
  pageSize: 10,
  orgid: 0
})
const message = useMessage() // 消息弹窗
// 总数据量
const total = ref(0)
// 用户信息
const userProfile = ref()
// 设备列表数据
const deviceList = ref([])
// 查询表单引用
const queryFormRef = ref()
// 设备表单引用
const deviceFormRef = ref()
// 设备详情表单引用
const detailsFormRef = ref()
// 心电数据组件引用
const ecgDataRef = ref()

// 查询方法
const handleQuery = async () => {
  try {
    //指定查询当前登录用户的机构ID
    queryParams.orgid = userProfile.value.dept.id
    const res = await DeviceApi.getDevicePage(queryParams)
    deviceList.value = res.list
    total.value = res.total
  } catch (error) {
    console.error('获取设备列表失败：', error)
  }
}

// 重置查询
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  queryParams.devicename = ''
  queryParams.devicestatus = undefined
  queryParams.devicetype = ''
  queryParams.pageNo = 1
  handleQuery()
}

// 打开表单
const openForm = (type: string) => {
  deviceFormRef.value?.open(type)
}

// 处理设备操作
const handleDeviceAction = async (action: any) => {
  if (action.action === 'details') {
    // 打开表单并加载设备数据
    detailsFormRef.value?.open(action.deviceId)
  } else if (action.action === 'openECGData') {
    // 打开心电数据组件
    const band = await DeviceuserApi.getDevCount(action.deviceId)
    if (band > 0) {
      ecgDataRef.value?.open(action.deviceId, action.deviceName)
    } else {
      ElMessageBox.alert('该设备无绑定人员，无法查看心电数据！', '提示', {
        confirmButtonText: '确定',
        type: 'warning'
      })
    }
  } else if (action.action === 'delete') {
    // 删除设备
    const res = await DeviceuserApi.getDevCount(action.deviceId)
    if (res> 0) {
      ElMessageBox.alert('该设备有绑定人员，无法删除！', '提示', {
        confirmButtonText: '确定',
        type: 'warning'
      })
    }else{
    ElMessageBox.confirm('是否删除该设备？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
      const res2 = await DeviceApi.deleteDeviceCode(action.deviceId)
   if (res2) {
    message.success('删除成功')
    handleQuery()
   }
  })
  }
  }
}

// 页面加载时获取数据
onMounted(async () => {
 // 首先获取用户信息
    userProfile.value = await getUserProfile()
  handleQuery()
})
</script>

<style scoped>
.device-cards-container {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  padding: 20px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style>
