<template>
  <div class="container-tree" ref="container">
    <el-row>
      <div class="left-tree" :style="{ width: leftWidth + 'px' }">
        <ContentWrapNoBottom>
          <FileTree @node-click="handleFileNodeClick" @success="successList" :deviceId="id" />
        </ContentWrapNoBottom>
      </div>
      <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="设备名称" align="center" prop="deviceId" />-->
            <!--          <el-table-column label="资料分类" align="center" prop="classId" />-->
            <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="t('file.operation')" align="center" width="160">
              <template #default="scope">
                <div class="flex items-center justify-center">
                  <el-button type="primary" link @click="openForm('update', scope.row.id)">
                    <Icon icon="ep:edit" />
                    {{ t('iotDevice.update') }}
                  </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" /> {{ t('action.more') }}</el-button>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item command="handleDelete">
                          <Icon icon="ep:delete" />{{ t('iotDevice.delete') }}
                        </el-dropdown-item>
                        <!--                        <el-dropdown-item command="fileView">-->
                        <!--                          <Icon icon="ep:view" />预览-->
                        <!--                        </el-dropdown-item>-->
                        <el-dropdown-item command="fileDownload" v-hasPermi="['rq:iot-info:download']">
                          <Icon icon="ep:view" />
                          {{ t('file.dow') }}
                        </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>
  <IotInfoForm
    ref="formRef"
    type="device"
    @success="getList"
    :deviceId="deviceId"
    :classId="queryParams.classId"
  />
</template>
<script lang="ts" setup>
import { IotDeviceVO } from '@/api/pms/device'
import FileTree from '@/views/pms/device/FileTree.vue'
import { dateFormatter } from '@/utils/formatTime'
import IotInfoForm from '@/views/pms/iotinfo/IotInfoForm.vue'
import * as IotInfoApi from '@/api/pms/iotinfo'
import { IotInfoVO } from '@/api/pms/iotinfo'
import { onMounted, ref } from 'vue'
import {DICT_TYPE} from "@/utils/dict";

defineOptions({ name: 'DeviceUpload' })
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 container = ref(null)
const leftWidth = ref(350) // 初始左侧宽度
const rightWidth = ref(window.innerWidth * 0.69)
let isDragging = false
const openWeb = (url) => {
  window.open(
    'http://1.94.244.160:8012/onlinePreview?url=' + encodeURIComponent(Base64.encode(url))
  )
}
const startDrag = (e) => {
  isDragging = true
  document.addEventListener('mousemove', onDrag)
  document.addEventListener('mouseup', stopDrag)
}

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 queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  filename: null,
  createTime: [],
  deviceId: null,
  classId: null
})
// 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('请选择左侧资料分类')
    return
  }
  formRef.value.open(type, id)
}
const deviceId = ref('')
const handleFileNodeClick = async (row) => {
  queryParams.classId = 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.getIotInfoPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    formLoading.value = false
  }
}
const successList = async (id) => {
  queryParams.classId = id
  await getList()
  // queryParams.classId = ''
}
/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}
/** 初始化 */
onMounted(async () => {
  // await getDetail()
  //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>
