<template>
  <div class="project-search" v-if="type !== 'xls'">
    <div
      style="
        width: 50%;
        height: calc(100vh - 30px);
        overflow: auto;
        position: relative;
      "
      v-if="dataList.length !== 0"
      @scroll="handleScroll"
      ref="scrollContainer"
    >
      <div v-for="item in dataList" :key="item.id" class="listClass">
        <span style="padding: 0px 10px 10px 0; cursor: pointer">{{
          item.page_number
        }}</span>
        <!--  <img
          :src="item.url"
          alt=""
          @click="openImagePreview(item.url)"
          style="
            width: 150px;
            height: 150px;
            padding: 10px 10px 10px 0;
            cursor: pointer;
          "
        />   v-html="item.content"-->
        <div
          style="margin-bottom: 20px"
          @click="scrollToPage(item.page_number, item.coordinate)"
        >
          <span v-if="item.url==''||item.url==null">{{ item.content }}</span>
          <img v-else :src="item.url" alt="" />
        </div>
      </div>
      <el-dialog
        :visible.sync="imagePreviewVisible"
        append-to-body
        :modal="false"
        :close-on-click-modal="false"
        custom-class="movable-dialog"
        :title="'图片预览'"
      >
        <img :src="previewImageUrl" style="width: 100%" alt="Preview" />
      </el-dialog>
      <!-- 分页控件 -->
      <!--  <div class="pagination">
        <el-pagination
          @current-change="handleCurrentChange"
          :current-page="queryForm.page"
          :page-size="queryForm.page_size"
          :total="total"
          layout="prev, pager, next"
        >
        </el-pagination>
      </div> -->
      <div v-if="loading" class="loading-more">加载中...</div>
    </div>
    <div
      v-else
      style="
        width: 50%;
        font-size: 25px;
        margin: 300px auto;
        color: #909399;
        text-align: center;
      "
    >
      暂无解析数据
    </div>
    <!-- <div style="width: 50%">
      <iframe :src="documentUrl" width="100%" height="822px"></iframe>
    </div> -->
    <div style="width: 50%">
      <!-- 文件预览组件 -->
      <file-preview
        :file-url="documentUrl"
        :file-type="type"
        :type="type"
        ref="filePreview"
        :pageNum="pdfPageNum"
        :coordinate="pdfCoordinate"
      />
    </div>
  </div>
  <div v-else>
    <!-- <div
      id="luckysheet"
      ref="luckysheet"
      style="width: 100%; height: 500px"
    ></div> -->
    <div v-if="excelDataList.length > 0" class="excel-table">
      <div v-for="(sheet, sheetIndex) in excelDataList" :key="sheetIndex">
        <!-- <h3>{{ sheet.title || `Sheet ${sheetIndex + 1}` }}</h3> -->
        <table>
          <thead>
            <tr>
              <th v-for="(header, index) in sheet.data[0]" :key="index">
                {{ header }}
              </th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(row, rowIndex) in sheet.data.slice(1)" :key="rowIndex">
              <td v-for="(cell, cellIndex) in row" :key="cellIndex">
                {{ cell }}
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
    <div v-else class="no-data">暂无数据</div>
  </div>
</template>
    
    <script>
import { mapGetters } from "vuex";
import { searchTaskInfo } from "@/api/knowledge";
import LuckyExcel from "luckyexcel";
import FilePreview from "@/components/FilePreview/index.vue"; // 新增文件预览组件
export default {
  components: {
    FilePreview, // 注册文件预览组件
  },
  computed: {
    ...mapGetters(["roleInfo", "authList"]),
    paginatedDataList() {
      const start = (this.queryForm.page - 1) * this.queryForm.page_size;
      const end = start + this.queryForm.page_size;
      return this.dataList.slice(start, end);
    },
  },

  data() {
    return {
      queryForm: {
        page: 1,
        page_size: 30,
        document_id: "",
      },
      dataList: [],
      conten: "",
      documentUrl: "",
      type: "",
      excelDataList: [],
      isFileViewable: false,
      supportedFileTypes: [
        "pdf",
        "doc",
        "docx",
        "xls",
        "xlsx",
        "ppt",
        "pptx",
        "txt",
        "jpg",
        "jpeg",
        "png",
        "gif",
      ],
      total: 0,
      imagePreviewVisible: false,
      previewImageUrl: "",
      pdfPageNum: "",
      pdfCoordinate: "",
      loading: false,
      hasMore: true,
      totalPages: 0,
    };
  },
  mounted() {
    this.queryForm.document_id = this.$route.query.id;
    this.type = this.$route.query.type;
    this.checkFileType();
    this.search();
    this.$nextTick(this.makeDialogDraggable);
  },
  methods: {
    makeDialogDraggable() {
      this.$nextTick(() => {
        const dialogHeaderEl = document.querySelector(
          ".movable-dialog .el-dialog__header"
        );
        const dragDom = document.querySelector(".movable-dialog");

        // 如果元素不存在则直接返回
        if (!dialogHeaderEl || !dragDom) {
          return;
        }

        dialogHeaderEl.style.cursor = "move";
        dragDom.style.position = "absolute";

        // 获取原有属性
        const sty =
          dragDom.currentStyle || window.getComputedStyle(dragDom, null);

        dialogHeaderEl.onmousedown = (e) => {
          // 鼠标按下，计算当前元素距离可视区的距离
          const disX = e.clientX - dialogHeaderEl.offsetLeft;
          const disY = e.clientY - dialogHeaderEl.offsetTop;

          // 获取到的值带px 正则匹配替换
          let styL, styT;

          // 注意在ie中 第一次获取到的值为组件自带50% 移动之后赋值为px
          if (sty.left.includes("%")) {
            styL =
              +document.body.clientWidth * (+sty.left.replace(/\%/g, "") / 100);
            styT =
              +document.body.clientHeight * (+sty.top.replace(/\%/g, "") / 100);
          } else {
            styL = +sty.left.replace(/\px/g, "");
            styT = +sty.top.replace(/\px/g, "");
          }

          document.onmousemove = function (e) {
            // 通过事件委托，计算移动的距离
            const l = e.clientX - disX;
            const t = e.clientY - disY;

            // 移动当前元素
            dragDom.style.left = `${l + styL}px`;
            dragDom.style.top = `${t + styT}px`;
          };

          document.onmouseup = function (e) {
            document.onmousemove = null;
            document.onmouseup = null;
          };
        };
      });
    },
    openImagePreview(url) {
      this.previewImageUrl = url;
      this.imagePreviewVisible = true;
      // 改为在 dialog 打开后执行
      this.$nextTick(() => {
        setTimeout(this.makeDialogDraggable, 100); // 添加小延时确保 DOM 已完全渲染
      });
    },
    /* 分页 */
    handleCurrentChange(page) {
      this.queryForm.page = page;
      this.search();
    },
    checkAuth(path) {
      if (this.roleInfo.is_admin == 1) {
        return true;
      }
      /* let auth=this.authList.filter(o=>o.type==999 && o.path==path);
            if(auth.length>0){
              return true;
            } */
      return true;
    },
    checkFileType() {
      this.isFileViewable = this.supportedFileTypes.includes(this.type);
    },

    search() {
      this.loading = true;
      this.queryForm.page = 1;
      this.hasMore = true;
      this.dataList = [];
      this.totalPages = 0;

      searchTaskInfo(this.queryForm)
        .then((res) => {
          this.dataList = res.data.tasks;
          this.total = res.data.pagination.total_count;
          this.totalPages = res.data.pagination.num_pages;

          if (this.totalPages <= 1) {
            this.hasMore = false;
          }

          if (this.isFileViewable) {
            this.documentUrl = res.data.documentUrl;
          }
        })
        .catch((error) => {
          console.error("获取数据时出错:", error);
        })
        .finally(() => {
          this.loading = false;
        });
    },

    parseExcelData(tasks) {
      return tasks
        .filter((task) => task.content)
        .map((task, index) => {
          let content = task.content;
          if (typeof content !== "string") return null;

          // Remove the title row if it exists
          const titleRowMatch = content.match(/^#.*?\n/);
          if (titleRowMatch) {
            content = content.slice(titleRowMatch[0].length);
          }

          // Split the content into rows and remove empty rows
          const rows = content
            .split("\n")
            .map((row) => row.trim())
            .filter((row) => row !== "")
            .filter((row) => !row.match(/^\|[-:]+\|[-:]+\|$/)) // Remove separator row
            .map((row) =>
              row
                .split("|")
                .map((cell) => cell.trim())
                .filter((cell) => cell !== "")
            );

          // Remove the header row if it contains "Unnamed" columns
          if (
            rows.length > 0 &&
            rows[0].some((cell) => cell.startsWith("Unnamed:"))
          ) {
            rows.shift();
          }

          return {
            title: task.title || `Sheet ${index + 1}`,
            data: rows,
          };
        })
        .filter((sheet) => sheet !== null && sheet.data.length > 0);
    },
    scrollToPage(pageNumber, coordinate) {
      if (!pageNumber) return;
      this.pdfPageNum = pageNumber;
      this.pdfCoordinate = coordinate;
      // 获取file-preview组件的引用
      const filePreviewComponent = this.$refs.filePreview;

      if (filePreviewComponent) {
        filePreviewComponent.scrollToPage(pageNumber);
      }
    },
    handleScroll() {
      const container = this.$refs.scrollContainer;
      if (!container) return;

      // 距离底部100px时触发加载
      const bottomOffset = 100;
      const scrollBottom =
        container.scrollHeight - container.scrollTop - container.clientHeight;

      if (scrollBottom < bottomOffset && !this.loading && this.hasMore) {
        this.loadMore();
      }
    },
    loadMore() {
      if (this.loading || !this.hasMore) return;

      if (this.totalPages && this.queryForm.page >= this.totalPages) {
        this.hasMore = false;
        return;
      }

      this.loading = true;
      this.queryForm.page += 1;

      searchTaskInfo(this.queryForm)
        .then((res) => {
          const newTasks = res.data.tasks;
          this.totalPages = res.data.pagination.num_pages;

          // 确保先添加新数据
          if (newTasks && newTasks.length > 0) {
            this.dataList = [...this.dataList, ...newTasks];
          }

          // 然后再判断是否是最后一页
          if (this.queryForm.page >= this.totalPages) {
            this.hasMore = false;
          }

          this.total = res.data.pagination.total_count;
        })
        .catch((error) => {
          console.error("加载更多数据时出错:", error);
          // 发生错误时重置页码
          this.queryForm.page -= 1;
        })
        .finally(() => {
          this.loading = false;
        });
    },
  },
};
</script>
    
    <style lang="scss" scoped>
.project-search {
  display: flex;
  padding: 10px;
  font-size: 12px;
}
.listClass {
  display: flex;
  justify-content: flex-start;
  align-items: center;
}
.excel-table {
  width: 100%;
  overflow-y: auto;
  table {
    border-collapse: collapse;
    width: 100%;
    margin-bottom: 20px;
  }

  th,
  td {
    border: 1px solid #ddd;
    padding: 8px;
    text-align: left;
    white-space: nowrap;
  }

  th {
    background-color: #f2f2f2;
    font-weight: bold;
    position: sticky;
    top: 0;
    z-index: 1;
  }

  tr:nth-child(even) {
    background-color: #f9f9f9;
  }
}

.no-data {
  font-size: 18px;
  color: #909399;
  text-align: center;
  margin-top: 50px;
}
.pagination {
  position: fixed;
  bottom: 0;
  right: 51%;
  /* right: 0; */
}
.movable-dialog {
  position: absolute !important;
}

::v-deep .el-dialog__header {
  cursor: move;
}
.loading-more {
  text-align: center;
  padding: 10px 0;
  color: #909399;
}
</style>
    