<template>
  <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">
            <el-table-column :label="t('file.name') " align="center" prop="filename" />
            <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 link type="primary" @click="openWeb(scope.row.filePath)"> <Icon size="19" icon="ep:view"  /> </el-button>
              </template>
            </el-table-column>
<!--            <el-table-column label="备注" align="center" prop="remark" />-->
<!--            <el-table-column-->
<!--              label="创建时间"-->
<!--              align="center"-->
<!--              prop="createTime"-->
<!--              :formatter="dateFormatter"-->
<!--              width="180px"-->
<!--            />-->
            <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" 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>
<!--                  <el-dropdown-->
<!--                    @command="(command) => handleCommand(command, scope.row)"-->
<!--                    v-hasPermi="[-->
<!--                      'system:user:delete',-->
<!--                      'system:user:update-password',-->
<!--                      'system:permission:assign-user-role'-->
<!--                    ]"-->
<!--                  >-->
<!--                    <el-button type="primary" link><Icon icon="ep:d-arrow-right" /> 更多</el-button>-->
<!--                    <template #dropdown>-->
<!--                      <el-dropdown-menu>-->
<!--                        <el-dropdown-item command="handleDelete">-->
<!--                          <Icon icon="ep:delete" />删除-->
<!--                        </el-dropdown-item>-->
<!--                        <el-dropdown-item command="fileView">-->
<!--                          <Icon icon="ep:view" />预览-->
<!--                        </el-dropdown-item>-->
<!--                        <el-dropdown-item command="fileDownload">-->
<!--                          <Icon icon="ep:view" />下载-->
<!--                        </el-dropdown-item>-->
<!--                      </el-dropdown-menu>-->
<!--                    </template>-->
<!--                  </el-dropdown>-->
                </div>
              </template>
            </el-table-column>
          </el-table>
          <Pagination
            :total="total"
            v-model:page="queryParams.pageNo"
            v-model:limit="queryParams.pageSize"
            @pagination="getList"
          />
        </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";
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 successList = async (id) => {
  //queryParams.classId = 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 handleCommand = (command: string, row: IotInfoVO) => {
  switch (command) {
    case 'handleDelete':
      handleDelete(row.id)
      break
    case 'handleUpdate':
      openForm('update', row.id)
      break
    case 'fileView':
      handleFileView(row.filePath)
      break
    case 'fileDownload':
      handleDownload(row.filePath)
      break
    default:
      break
  }
}
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 (!queryParams.classId) {
    message.error(t('common.leftNode'))
    return
  }
  formRef.value.open(type, id)
}
const deviceId = ref('')
const clickNodeId = ref('')
const nodeId = ref('')
const handleFileNodeClick = async (row) => {
  queryParams.classId = row.id
  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 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 {
    // queryParams.deviceId = deviceId.value
    const data = await IotInfoApi.IotInfoApi.getIotInfoFilePage(queryParams)
    list.value = data.list
    total.value = data.total
  } 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>
.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>
