<template>
  <Dialog v-model="dialogVisible" title="选择设备路线" style="width: 1300px; min-height: 600px">
    <ContentWrap>
      <el-form
        class="-mb-15px"
        :model="queryParams"
        ref="queryFormRef"
        :inline="true"
        label-width="68px"
      >
        <el-form-item label="设备名称" prop="deviceName">
          <el-input
            v-model="queryParams.deviceName"
            placeholder="请输入设备名称"
            clearable
            @keyup.enter="handleQuery"
            class="!w-200px"
          />
        </el-form-item>
        <el-form-item label="创建时间" prop="createTime">
          <el-date-picker
            v-model="queryParams.createTime"
            value-format="YYYY-MM-DD HH:mm:ss"
            type="daterange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
            class="!w-240px"
          />
        </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 @click="handleConfirm" type="danger"
            ><Icon icon="ep:check" class="mr-5px" /> 确认选择</el-button
          >
          <el-button @click="toggleAll" type="primary"
            ><Icon icon="ep:refresh" class="mr-5px" />全选</el-button
          >
          <el-button @click="invertSelection" type="info"
            ><Icon icon="ep:refresh" class="mr-5px" />取消全选</el-button
          >
        </el-form-item>
      </el-form>
    </ContentWrap>
    <ContentWrap>
      <el-table
        ref="tableRef"
        v-loading="loading"
        :data="list"
        :stripe="true"
        :show-overflow-tooltip="true"
        row-key="id"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          :reserve-selection="false"
          :selectable="(row) => !row.disabled"
        />
        <el-table-column label="设备名称" align="center" prop="deviceName" />
        <el-table-column label="路线名称" align="center" prop="routeName" />
        <el-table-column
          label="创建时间"
          align="center"
          prop="createTime"
          width="180"
          :formatter="dateFormatter"
        />
        <el-table-column label="操作" align="center">
          <template #default="scope">
            <el-button link type="primary" @click="viewRoute(scope.row.itemJson)">
              查看路线
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <Pagination
        :total="total"
        v-model:page="queryParams.pageNo"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
      <RouteInspectItemDrawer
        ref="showDrawer"
        :model-value="drawerVisible"
        @update:model-value="(val) => (drawerVisible = val)"
      />
    </ContentWrap>
  </Dialog>
</template>

<script setup lang="ts">
import { IotDeviceVO } from '@/api/pms/device'
import { dateFormatter } from '@/utils/formatTime'
import { CACHE_KEY, useCache } from '@/hooks/web/useCache'
import { IotInspectRouteApi } from '@/api/pms/inspect/route'
import { IotInspectItemVO } from '@/api/pms/inspect/item'
import RouteInspectItemDrawer from "@/views/pms/inspect/plan/RouteInspectItemDrawer.vue";
import {ref} from "vue";

const emit = defineEmits(['choose']) // 定义 success 事件，用于操作成功后的回调
const dialogVisible = ref(false) // 弹窗的是否展示
const loading = ref(true) // 列表的加载中
const queryFormRef = ref() // 搜索的表单
const list = ref<IotDeviceVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const drawerVisible = ref<boolean>(false)
const showDrawer = ref()
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  label: '',
  status: undefined,
  deptId: undefined,
  assetClass: undefined,
  createTime: undefined,
  deviceName: undefined,
})

const handleConfirm = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请至少选择一个')
    return
  }

  emit(
    'choose',
    selectedRows.value.map((row) => ({
      ...row,
      // 确保返回必要字段
      code: row.item,
      name: row.standard
    }))
  )
  dialogVisible.value = false
  handleClose()
}

// 关闭时清空选择
const handleClose = () => {
  tableRef.value?.clearSelection()
  selectedRows.value = []
  emit('close')
}


const viewRoute = (itemJson) => {
  drawerVisible.value = true
  showDrawer.value.openDrawer(itemJson)
}
const toggleAll = () => {
  list.value.forEach((row) => {
    tableRef.value.toggleRowSelection(row, true)
  })
}
const handleSelectionChange = (val) => {
  selectedRows.value = val
}
const invertSelection = () => {
  selectedRows.value.forEach((row) => {
    tableRef.value.toggleRowSelection(row, false)
    selectedRows.value.splice(row)
  })
}
const selectedRows = ref<IotInspectItemVO[]>([]) // 多选数据（存储所有选中行的数组）
const tableRef = ref()

// 多选 切换行选中状态
const toggleRow = (row) => {
  const includes = selectedRows.value.includes(row)
  if (includes) {
    selectedRows.value.splice(row)
  } else {
    selectedRows.value.push(row) // 选中
  }
  tableRef.value.toggleRowSelection(row, !includes)
}

// 点击整行选中
const handleRowClick = (row) => {
  toggleRow(row)
}

const open = async (classify) => {
  dialogVisible.value = true
  queryParams.assetClass = classify
  queryParams.deviceName = undefined
  queryParams.createTime = undefined
  await getList()
  selectedRows.value = []
}
defineExpose({ open })
const { wsCache } = useCache()
const getList = async () => {
  loading.value = true
  try {
    // const user = wsCache.get(CACHE_KEY.USER)
    // queryParams.deptId = user.user.deptId
    const data = await IotInspectRouteApi.getIotInspectRoutePage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}
const choose = (row: DictDataVO) => {
  emit('choose', row)
  dialogVisible.value = false
}
/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}
</script>
<style lang="scss">
.no-label-radio .el-radio__label {
  display: none;
}
.no-label-radio .el-radio__inner {
  margin-right: 0;
}
</style>
