<template>
  <ContentWrap>
    <div style="display: flex; justify-content: space-between; align-items: center;">
      <el-breadcrumb separator=">" class="breadcrumb-container">
        <el-breadcrumb-item
          v-for="(item, index) in breadcrumbs"
          :key="index"
          @click="handleBreadcrumbClick(index)"
          :class="{ 'current-crumb': index === breadcrumbs.length - 1 }"
          class="custom-breadcrumb-item"
        >
          {{ item.name }}
        </el-breadcrumb-item>
      </el-breadcrumb>
      <el-input :placeholder="'在'+breadcrumbs[breadcrumbs.length - 1].name+'下搜索'" style="width: 250px;height: 30px"/>
    </div>
  </ContentWrap>
  <div class="container-tree" ref="container">
  <el-row >
    <div class="left-tree" :style="{ width: leftWidth + 'px' }">
      <ContentWrapNoBottom >
        <PmsTree @node-click="handleFileNodeClick" @success="successList" :deviceId="id" />
      </ContentWrapNoBottom>
    </div>
<!--    </el-col>-->
      <div
        class="divider-tree"
        @mousedown="startDrag"
      ></div>
      <div class="right-tree" :style="{ width: rightWidth + 'px' }">
        <ContentWrap>
          <el-form
            class="-mb-15px"
            :model="queryParams"
            ref="queryFormRef"
            :inline="true"
            label-width="68px"
          >
            <el-form-item :label="t('file.name') " prop="filename">
              <el-input
                v-model="queryParams.filename"
                :placeholder="t('file.nameHolder')"
                clearable
                @keyup.enter="handleQuery"
                class="!w-240px"
              />
            </el-form-item>
            <el-form-item>
              <el-button @click="handleQuery"><Icon icon="ep:search" />
                {{  t('file.search')}}</el-button>
              <el-button @click="resetQuery"><Icon icon="ep:refresh" />{{  t('file.reset')}}</el-button>
              <el-button type="primary" plain @click="openForm('create')">
                <Icon icon="ep:plus" /> {{  t('file.upload')}}
              </el-button>
            </el-form-item>
          </el-form>
        </ContentWrap>
        <ContentWrap>
          <el-table v-loading="formLoading" :data="list" :stripe="true" :show-overflow-tooltip="true" @row-dblclick="inContent" class="custom-table">
            <el-table-column :label="t('file.name') " align="left" prop="filename" min-width="300">
              <template #default="scope">
                <div style="display: flex; align-items: center; gap: 5px;">
                <Icon v-if="scope.row.fileType==='content'" icon="fa:folder-open"  color="orange"/>
                <Icon v-else-if="scope.row.fileType==='pic'||scope.row.fileClassify==='jpg'||scope.row.fileClassify==='png'" icon="ep:picture-filled"  color="#2183D1"/>
                <Icon v-else-if="scope.row.fileType==='file'&&scope.row.fileClassify==='pdf'" icon="fa-solid:file-pdf"  color="#E20012"/>
                <Icon v-else-if="scope.row.fileType==='file'&&(scope.row.fileClassify==='doc'||scope.row.fileClassify==='docx')" icon="fa:file-word-o"  color="blue"/>
                <Icon v-else-if="scope.row.fileType==='file'&&(scope.row.fileClassify==='xls'||scope.row.fileClassify==='xlsx')" icon="fa-solid:file-excel"  color="#107C41"/>
                <Icon v-else-if="scope.row.fileType==='file'&&(scope.row.fileClassify==='txt')" icon="fa:file-text-o" />
                  {{scope.row.filename}}
                </div>
              </template>

            </el-table-column>
            <el-table-column :label="t('file.fileType') " align="center" prop="fileType" >
              <template #default="scope">
                <dict-tag :type="DICT_TYPE.PMS_FILE_TYPE" :value="scope.row.fileType" />
              </template>
            </el-table-column>
            <el-table-column :label="t('file.fileSize') " align="center" prop="fileSize" />
<!--            <el-table-column :label="t('file.preview') " align="center" prop="filePath" >-->
<!--              <template #default="scope">-->
<!--                <el-button v-if="scope.row.fileType!=='content'" link type="primary" @click="openWeb(scope.row.filePath)"> <Icon size="19" icon="ep:view"  /> </el-button>-->
<!--              </template>-->
<!--            </el-table-column>-->
            <el-table-column :label="t('file.dept') " align="center" prop="deptName" />
            <el-table-column :label="t('file.device') " align="center" prop="deviceName" min-width="220"/> />
            <el-table-column :label="t('file.operation') " align="center" width="160">
              <template #default="scope">
                <div class="flex items-center justify-center">
                  <el-button type="primary" v-if="scope.row.fileType!=='content'" link @click="handleDownload( scope.row.filePath)" v-hasPermi="['rq:iot-info:download']">
                    <Icon icon="ep:download" />{{t('file.dow')}}
                  </el-button>
<!--                  <el-button type="primary" link @click="handleView( scope.row)">-->
<!--                    <Icon icon="ep:view" />{{t('file.preview')}}-->
<!--                  </el-button>-->
                </div>
              </template>
            </el-table-column>
          </el-table>
        </ContentWrap>
      </div>
  </el-row>
  </div>
  <IotInfoFormTree
    ref="formRef"
    @success="getList"
    :deviceId="deviceId"
    :nodeId = "nodeId"
    :classId="clickNodeId"
  />
</template>
<script lang="ts" setup>
import { IotDeviceApi, IotDeviceVO } from '@/api/pms/device'
import { dateFormatter } from '@/utils/formatTime'
import IotInfoFormTree from '@/views/pms/iotinfo/IotInfoFormTree.vue'
import * as IotInfoApi from '@/api/pms/iotinfo'
import { IotInfoVO } from '@/api/pms/iotinfo'
import { ref, onMounted, onUnmounted } from 'vue'

import PmsTree from '@/views/system/tree/PmsTree.vue'
import {CACHE_KEY, useCache} from "@/hooks/web/useCache";
import {DICT_TYPE} from "@/utils/dict";
import {IotInfoClassifyApi} from "@/api/pms/info";
import {IotTreeApi} from "@/api/system/tree";
defineOptions({ name: 'IotTree' })

const container = ref(null)
const leftWidth = ref(350) // 初始左侧宽度
const rightWidth = ref(window.innerWidth * 0.8)
let isDragging = false

const openWeb = (url) => {
  window.open('http://1.94.244.160:8012/onlinePreview?url='+encodeURIComponent(Base64.encode(url)));
}
const handleView = (row) => {
  openForm('detail', row.id)
}
const startDrag = (e) => {
  isDragging = true
  document.addEventListener('mousemove', onDrag)
  document.addEventListener('mouseup', stopDrag)
}
const topNodeId = ref('')
const successList = async (id) => {
  queryParams.classId = id
  topNodeId.value = id
  const rootItem = breadcrumbs.value.find(item => item.type === 'root');
  if (rootItem) {
    rootItem.id = id;
  }

  await getList()
  // queryParams.classId = ''
}



const onDrag = (e) => {
  if (!isDragging) return

  const containerRect = container.value.getBoundingClientRect()
  const newWidth = e.clientX - containerRect.left

  // 设置最小和最大宽度限制
  if (newWidth > 300 && newWidth < containerRect.width - 100) {
    leftWidth.value = newWidth
  }
}

const stopDrag = () => {
  isDragging = false
  document.removeEventListener('mousemove', onDrag)
  document.removeEventListener('mouseup', stopDrag)
}



const queryFormRef = ref() // 搜索的表单
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const loading = ref(true) // 列表的加载中
const { params } = useRoute() // 查询参数
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const list = ref<IotDeviceVO[]>([]) // 列表的数据
// const total = ref(0) // 列表的总页数
const id = params.id as unknown as number
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  filename: null,
  createTime: [],
  deviceId: null,
  classId: null,
  deptId: undefined
})
// SPU 表单数据
const formData = ref({
  id: undefined,
  deviceId: undefined,
  deptId: undefined,
  filename: undefined,
  fileType: undefined,
  filePath: undefined,
  remark: undefined,
  classId: undefined
})
const handleDownload = async (url) => {
  try {
    const response = await fetch(url)
    const blob = await response.blob()
    const downloadUrl = window.URL.createObjectURL(blob)

    const link = document.createElement('a')
    link.href = downloadUrl
    link.download = url.split('/').pop() // 自动获取文件名‌:ml-citation{ref="3" data="citationList"}
    link.click()

    URL.revokeObjectURL(downloadUrl)
  } catch (error) {
    console.error('下载失败:', error)
  }
}
const handleFileView = (url: string) => {
  window.open(
    'http://1.94.244.160:8012/onlinePreview?url=' + encodeURIComponent(Base64.encode(url))
  )
}
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await IotInfoApi.IotInfoApi.deleteIotInfo(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}
const formRef = ref()
const openForm = (type: string, id?: number) => {
  if (classType.value==='dept'){
    message.error(t('common.deptChoose'))
    return;
  }
  if (!queryParams.classId) {
    message.error(t('common.leftNode'))
    return
  }
  formRef.value.open(type, id)
}
const deviceId = ref('')
const clickNodeId = ref('')
const nodeId = ref('')
const classType = ref('')

const breadcrumbs = ref([
  { id: null, name: '科瑞石油技术',type:'root' } // 根节点
])

// 共享的面包屑更新逻辑
const updateBreadcrumbs = async (node) => {
  // 查找当前节点是否已在面包屑中
  const currentIndex = breadcrumbs.value.findIndex(item => item.id === node.id)

  if (currentIndex > -1) {
    // 如果已存在则截断后面的节点
    breadcrumbs.value = breadcrumbs.value.slice(0, currentIndex + 1)
  } else {
    // 新增节点到面包屑
    breadcrumbs.value.push({ id: node.id, name: node.filename || node.name })
  }

  // 更新表格数据
  queryParams.classId = node.id;
  const data = await IotInfoApi.IotInfoApi.getChildContentFile(queryParams)
  list.value = data
}

// 表格行点击事件
const inContent = async (row) => {
  debugger
  if (row.fileType!='content') {
    window.open('http://1.94.244.160:8012/onlinePreview?url='+encodeURIComponent(Base64.encode(row.filePath)));
    return
  }
  queryParams.filename = ''
  formLoading.value = true
  // 调用共享方法更新面包屑和表格
  await updateBreadcrumbs(row)
  // 可以添加其他表格行点击需要的逻辑
  queryParams.classId = row.id;
  const data = await IotInfoApi.IotInfoApi.getChildContentFile(queryParams)
  formLoading.value = false
  list.value = data
}

// 文件树节点点击事件
const handleFileNodeClick = async (row) => {
  queryParams.filename = ''
  const parentItems = await IotTreeApi.getParentIds(row.id);
  breadcrumbs.value = [];
  parentItems.forEach(item => {
    breadcrumbs.value.push({ id: item.id, name: item.name,type:'root' } );
  })

  queryParams.classId = row.id
  classType.value = row.type
  if (row.type==='device') {
    deviceId.value = row.originId
    const queryParam = {
      deviceId: row.originId,
      pageNo: 1,
      pagesize: 10,
    }
    const data = await IotInfoClassifyApi.getIotInfoClassifyPage(queryParam)
    if (data){
      const target = data.filter((item)=> item.parentId===0)
      clickNodeId.value = target[0].id
    }
  } else if (row.type === 'file'){
    clickNodeId.value = row.originId
  } else if (row.type==='dept') {
    // message.error("请选择设备及文件节点")
    // return
  }
  nodeId.value = row.id
  await getList()
}

// 面包屑点击事件
const handleBreadcrumbClick = async (index) => {
  queryParams.filename = ''
  formLoading.value = true
  // 忽略当前节点的点击
  if (index === breadcrumbs.value.length - 1) return

  // 截断面包屑到点击的节点
  const targetBreadcrumbs = breadcrumbs.value.slice(0, index + 1)
  breadcrumbs.value = targetBreadcrumbs

  // 获取对应节点的数据
  let targetId = targetBreadcrumbs[index].id
  if (!targetId){
    targetId = topNodeId.value
  }
  queryParams.classId = targetId
  const data = await IotInfoApi.IotInfoApi.getChildContentFile(queryParams)
  list.value = data
  formLoading.value = false
}


// const handleFileNodeClick = async (row) => {
//   queryParams.classId = row.id
//   classType.value = row.type
//   if (row.type==='device') {
//     deviceId.value = row.originId
//     const queryParam = {
//       deviceId: row.originId,
//       pageNo: 1,
//       pagesize: 10,
//     }
//     const data = await IotInfoClassifyApi.getIotInfoClassifyPage(queryParam)
//     debugger
//     if (data){
//       const target = data.filter((item)=> item.parentId===0)
//       clickNodeId.value = target[0].id
//     }
//   } else if (row.type === 'file'){
//     clickNodeId.value = row.originId
//   } else if (row.type==='dept') {
//     // message.error("请选择设备及文件节点")
//     // return
//   }
//   nodeId.value = row.id
//   await getList()
// }
/** 获得详情 */
// const getDetail = async () => {
//   if (id) {
//     formLoading.value = true
//     try {
//       formData.value = (await IotDeviceApi.getIotDevice(id)) as IotDeviceVO
//     } finally {
//       formLoading.value = false
//     }
//   }
// }
/** 查询列表 */
const getList = async () => {
  formLoading.value = true
  try {
    const data = await IotInfoApi.IotInfoApi.getChildContentFile(queryParams)
    list.value = data
  } finally {
    formLoading.value = false
  }
}
/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}
const { wsCache } = useCache()
/** 初始化 */
onMounted(async () => {
  // await getDetail()
  // queryParams.deptId = wsCache.get(CACHE_KEY.USER).user.deptId;
  // await getList()
  // deviceId.value = params.id as unknown as number
})
</script>
<style scoped>
::v-deep .breadcrumb-container {
  padding: 12px 16px;
  background-color: #f5f7fa;
  border-radius: 6px;
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.06);
}
::v-deep .custom-breadcrumb-item {
  font-size: 14px;
  font-weight: bold;
}

/* 面包屑文本样式 */
::v-deep .el-breadcrumb__item .el-breadcrumb__inner {
  color: #101010;
  text-decoration: none;
  padding: 2px 4px;
  border-radius: 2px;
  transition: all 0.2s ease;
}

/* 可点击项悬停效果 */
::v-deep .el-breadcrumb__item:not(:last-child) .el-breadcrumb__inner:hover {
  color: #409eff;
  background-color: rgba(64, 158, 255, 0.1);
  cursor: pointer;
}

/* 当前项样式 */
::v-deep .el-breadcrumb__item:last-child .el-breadcrumb__inner {
  color: #1890ff;
  font-weight: 500;
  cursor: default;
}

/* 分隔符样式优化 */
::v-deep .el-breadcrumb__separator {
  margin: 0 8px;
  color: #0954f6;
  font-size: 12px;
}


.custom-table {
  cursor: pointer;
  --el-table-row-hover-bg-color: #f5f7fa; /* 优化悬停背景色 */
}

.container-tree {
  display: flex;
  height: 100%;
  user-select: none; /* 防止拖动时选中文本 */
}

.left-tree {
  background: #f0f0f0;
  height: 100%;
  overflow: auto;
}

.right-tree {
  flex: 1;
  height: 100%;
  overflow: auto;
  margin-left: 15px;
}

.divider-tree {
  width: 2px;
  background: #ccc;
  cursor: col-resize;
  position: relative;
}

.divider-tree:hover {
  background: #666;
}
</style>
