<template>
  <Dialog v-model="dialogVisible" :title="t('route.OperationDevice')" style="width: 1500px; min-height: 600px">
    <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('iotDevice.nameHolder')"
            clearable
            @keyup.enter="handleQuery"
            class="!w-220px"
          />
        </el-form-item>
        <el-form-item  :label="t('iotDevice.code')" prop="deviceCode">
          <el-input
            v-model="queryParams.deviceCode"
            :placeholder="t('iotDevice.codeHolder')"
            clearable
            @keyup.enter="handleQuery"
            class="!w-220px"
          />
        </el-form-item>
        <el-form-item :label="t('iotDevice.dept')" prop="deptId">
          <el-tree-select
            v-model="queryParams.deptId"
            :data="deptList"
            :props="defaultProps"
            check-strictly
            node-key="id"
            filterable
            placeholder="请选择部门"
            class="!w-220px"
          />
          <el-form-item  :label="t('deviceForm.category')" prop="assetClass" style="width: 15vw;margin-left: 25px" >
            <el-tree-select
              v-model="queryParams.assetClass"
              :data="productClassifyList"
              :props="defaultProps"
              check-strictly
              node-key="id"
              :placeholder="t('deviceForm.categoryHolder')"
              filterable
            />
          </el-form-item>
        </el-form-item>
        <el-form-item>
          <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> {{ t('chooseMaintain.search') }}</el-button>
          <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> {{ t('chooseMaintain.reset')  }}</el-button>
          <el-button @click="handleConfirm" type="danger"><Icon icon="ep:check" class="mr-5px" />  {{ t('chooseMaintain.confirm')  }}</el-button>
          <el-button
            type="primary"
            @click="selectAll"
            :disabled="loading || list.length === 0 || isAllSelected"
          >
            {{ t('operationFill.selectAll') }}
          </el-button>
          <el-button
            type="default"
            @click="deselectAll"
            :disabled="loading || (!isAllSelected && selectedRows.length === 0)"
            style="margin-left: 8px;"
          >
            {{ t('operationFill.deselectAll') }}
          </el-button>
<!--          <el-button @click="toggleAll" type="primary"-->
<!--            ><Icon icon="ep:refresh" class="mr-5px" />{{ t('chooseMaintain.selectAll') }}</el-button-->
<!--          >-->
<!--          <el-button @click="invertSelection" type="info"-->
<!--            ><Icon icon="ep:refresh" class="mr-5px" />{{ t('chooseMaintain.cancelAllSelection') }}</el-button-->
<!--          >-->
        </el-form-item>
      </el-form>
    </ContentWrap>
    <!-- 新增：已选物料标签区域 -->
    <ContentWrap v-if="selectedRows.length > 0"
                 style="margin: -10px 0px 10px; padding: 10px 15px; background: #f8fafc; border-radius: 4px; border: 1px solid #ebeef5;">
      <div style="display: flex; align-items: center; flex-wrap: wrap; gap: 8px;">
        <div style="font-weight: bold; color: #606266; margin-right: 10px;">已选路线设备：</div>
        <el-tag
          v-for="item in selectedRows"
          :key="item.id"
          @close="removeTag(item)"
          style="margin-bottom: 5px; position: relative; padding-right: 25px;"
        >
          {{ item.deviceCode }}
          <!-- 自定义关闭按钮 -->
          <span class="close-icon" @click.stop="removeTag(item)">
            <Icon icon="ep:close" style="font-size: 12px; position: absolute; right: 8px; top: 50%; transform: translateY(-50%);"/>
          </span>
        </el-tag>
      </div>
    </ContentWrap>
    <ContentWrap>
      <el-table
        ref="tableRef"
        v-loading="loading"
        :data="list"
        :stripe="true"
        :row-key="rowKey"
        :show-overflow-tooltip="true"
        table-layout="auto"
        @row-click="handleRowClick"
        class="full-width-table" >
        <el-table-column width="80" :label="t('workOrderMaterial.select')">
          <template #default="{ row }">
            <el-checkbox
              :model-value="selectedRows.some(item => item.id === row.id&&item.deviceCode===row.deviceCode)"
              @click.stop="selectRow(row)"
              class="no-label-radio"
            />
          </template>
        </el-table-column>
        <el-table-column :label="t('iotDevice.code')" align="center" prop="deviceCode" />
        <el-table-column :label="t('iotDevice.name')" align="center" prop="deviceName" />
        <el-table-column :label="t('iotDevice.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('iotDevice.dept')" align="center" prop="deptName" />
        <el-table-column :label="t('operationFill.operation')" align="center">
          <template #default="scope">
            <el-button link type="primary" @click="viewRoute(scope.row.itemJson)">
              {{ t('operationFill.view') }}
            </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 {IotDeviceApi, 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 { DICT_TYPE, getStrDictOptions } from '@/utils/dict'
import RouteInspectItemDrawer from "@/views/pms/inspect/plan/RouteInspectItemDrawer.vue";
import {ref} from "vue";
import {defaultProps, handleTree} from "@/utils/tree";
import * as DeptApi from "@/api/system/dept";
import * as ProductClassifyApi from "@/api/pms/productclassify";
const { t } = useI18n() // 国际化
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 deptList = ref<Tree[]>([]) // 树形结构
const drawerVisible = ref<boolean>(false)
const showDrawer = ref()
const productClassifyList = ref<Tree[]>([]) // 树形结构
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  label: '',
  status: undefined,
  deptId: undefined,
  assetClass: undefined,
  deviceName: undefined,
  deviceCode: undefined,
  routeName: undefined,
})
const message = useMessage() // 消息弹窗
// 添加全选相关状态
const isAllSelected = ref(false) // 是否全选所有数据
const totalSelectedCount = ref(0) // 总选中数量
const deselectedRows = ref([]) // 全选状态下取消选择的行
const allDataCache = ref([])
// 生成行唯一标识
const rowKey = (row: any) => {
  return `${row.id}`; // 确保行更新时重新渲染
};
const selectAll = async () => {
  try {
    // 显示加载状态
    loading.value = true;
    isAllSelected.value = true;
    deselectedRows.value = [];
    selectedRows.value = []; // 清空现有选中项
    allDataCache.value = []; // 清空缓存

    const paramsCopy = { ...queryParams };
    const originalPageNo = paramsCopy.pageNo;
    const originalPageSize = paramsCopy.pageSize;

    paramsCopy.pageNo = 1;
    paramsCopy.pageSize = 100; // 按后台限制的最大页数获取

    // 获取第一页数据
    const firstPageData = await IotDeviceApi.getIotDevicePage(paramsCopy);
    totalSelectedCount.value = firstPageData.total;
    allDataCache.value.push(...firstPageData.list);

    // 分批获取剩余数据
    if (firstPageData.total > 100) {
      const totalPages = Math.ceil(firstPageData.total / 100);
      const fetchPromises = [];

      for (let page = 2; page <= totalPages; page++) {
        fetchPromises.push(IotDeviceApi.getIotDevicePage({ ...paramsCopy, pageNo: page }));
      }

      const remainingPages = await Promise.all(fetchPromises);
      remainingPages.forEach(pageData => {
        allDataCache.value.push(...pageData.list);
      });
    }

    // 全选时，将所有数据放入selectedRows
    selectedRows.value = [...allDataCache.value];

    // 恢复原始分页参数
    queryParams.pageNo = originalPageNo;
    queryParams.pageSize = originalPageSize;

    message.success(t('operationFill.selectAll', { count: totalSelectedCount.value }));
  } catch (error) {
    console.error('全选失败', error);
    //message.error(t('operationFill.selectAllFailed'));
    isAllSelected.value = false;
    selectedRows.value = [];
  } finally {
    loading.value = false;
  }
};

// 修改取消全选方法，同步清空selectedRows
const deselectAll = () => {
  isAllSelected.value = false;
  deselectedRows.value = [];
  selectedRows.value = []; // 清空所有选中项
  allDataCache.value = []; // 清空缓存
  totalSelectedCount.value = 0;
  message.info(t('operationFill.deselectAll'));
};

// 修改单选逻辑，确保selectedRows正确更新
const selectRow = (row) => {
  if (isAllSelected.value) {
    // 全选状态下的单选操作
    const deselectedIndex = deselectedRows.value.findIndex(
      item => item.id === row.id && item.deviceCode === row.deviceCode
    );

    const selectedIndex = selectedRows.value.findIndex(
      item => item.id === row.id && item.deviceCode === row.deviceCode
    );

    if (deselectedIndex > -1) {
      // 从取消列表中移除，添加到选中列表
      deselectedRows.value.splice(deselectedIndex, 1);
      if (selectedIndex === -1) {
        selectedRows.value.push({ ...row });
      }
    } else {
      // 从选中列表中移除，添加到取消列表
      if (selectedIndex > -1) {
        selectedRows.value.splice(selectedIndex, 1);
      }
      deselectedRows.value.push({ ...row });
    }
  } else {
    // 非全选状态下的单选操作
    const index = selectedRows.value.findIndex(
      item => item.id === row.id && item.deviceCode === row.deviceCode
    );

    if (index > -1) {
      // 取消选择
      selectedRows.value.splice(index, 1);
    } else {
      // 选中
      selectedRows.value.push({ ...row });
    }
  }
};





// 修改移除标签方法，确保selectedRows同步更新
const removeTag = (route) => {
  // 从选中列表中移除
  const selectedIndex = selectedRows.value.findIndex(
    item => item.id === route.id && item.deviceCode === route.deviceCode
  );

  if (selectedIndex > -1) {
    selectedRows.value.splice(selectedIndex, 1);
  }

  // 全选状态下还要添加到取消列表
  if (isAllSelected.value) {
    const deselectedIndex = deselectedRows.value.findIndex(
      item => item.id === route.id && item.deviceCode === route.deviceCode
    );

    if (deselectedIndex === -1) {
      deselectedRows.value.push({ ...route });
    }
  }

  // 刷新表格
  list.value = [...list.value];
};
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(JSON.parse(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.deviceCode = undefined
  await getList()
  selectedRows.value = []
  deptList.value = handleTree(await DeptApi.getSimpleDeptList())
}
defineExpose({ open })
const { wsCache } = useCache()
const getList = async () => {
  loading.value = true
  list.value = []
  try {
    const data = await IotDeviceApi.getIotDevicePage(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()
}

onMounted(async () => {
  productClassifyList.value = handleTree(
    await ProductClassifyApi.IotProductClassifyApi.getSimpleProductClassifyList()
  )
})


</script>
<style lang="scss">
.no-label-radio .el-radio__label {
  display: none;
}
.no-label-radio .el-radio__inner {
  margin-right: 0;
}
</style>
