<template>
  <div class="problem">
    <el-row>
      <el-col :span="24">
        <div class="problem_form">
          <el-form
            :inline="true"
            ref="form"
            :model="dataForm"
            label-width="60px"
          >
            <el-form-item label="关键字:">
              <el-input
                v-model="dataForm.keyword"
                placeholder="请输入搜索关键字"
                style="width: 400px"
                class="filter-item"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="success" @click="onSubmit">查询</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-col>
    </el-row>
    <div class="problem_container">
      <div
        class="problem_left"
        v-infinite-scroll="load"
        :infinite-scroll-immediate="false"
        style="overflow: auto; padding: 10px"
      >
        <div
          @click="handleQacityl(item.city_id)"
          class="btn"
          v-for="item in getQaCityList"
        >
          {{ item.city_name }}
        </div>
      </div>
      <div class="problem_right">
        <ul
          class="infinite-list"
          v-infinite-scroll="load"
          :infinite-scroll-immediate="false"
          style="overflow: auto"
        >
          <li class="problem_right_container" v-for="item in getQaLists">
            <div class="title">
              <span v-html="handleprant(item.title)"></span>
              <!-- <el-button @click="handleZip(item.img_zip)" type="primary">下载图片</el-button>
              <el-button @click="handleZip(item.trip_zip)" type="primary">下载行程</el-button> -->
              <el-button @click="showImgDialog(item.img_zip)" type="primary"
                >下载图片</el-button
              >
              <el-button
                @click="showFileList(item.trip_zip)"
                type="primary"
                style="margin-left: 10px"
                >下载行程</el-button
              >
            </div>
            <div class="desc_container" v-for="list in item.qaQuestions">
              <span
                style="font-weight: 700; color: #46a6ff"
                class="desc"
                v-html="handleprant(list.title)"
              >
              </span>
              <el-button
                @click="copyToClipboard(list.content)"
                type="primary"
                size="mini"
                style="margin-left: 10px"
                >复制</el-button
              >

              <div class="desc" v-html="handleprantHtml(list.content)"></div>
            </div>
          </li>
        </ul>
      </div>
    </div>

    <el-dialog title="图片列表" :visible.sync="dialogImage" width="80%">
      <!-- 图片列表展示 -->
      <div class="image-list">
        <el-card
          v-for="(image, index) in imageList"
          :key="index"
          class="image-card"
          :body-style="{ padding: '10px' }"
        >
          <div style="text-align: center">{{ image.desc }}</div>
          <img :src="image.file" class="image-preview" />
          <div class="image-footer">
            <el-button @click="handlePreview(image.file)" size="mini"
              >查看</el-button
            >
            <el-button
              @click="handleDownload(image.file)"
              type="success"
              size="mini"
              >下载</el-button
            >
          </div>
        </el-card>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogImage = false">关闭</el-button>
      </div>
    </el-dialog>

    <el-dialog title="文件列表" :visible.sync="dialogFile" width="80%">
      <!-- 文件列表展示 -->
      <div class="file-list-horizontal">
        <el-card
          v-for="(file, index) in fileList"
          :key="index"
          class="file-card"
          :body-style="{ padding: '10px' }"
        >
        <div class="file-info">
            <el-icon class="file-icon">
              <i :class="getFileIcon(file.file)"></i>
            </el-icon>
            <span class="file-name" style="display: block;">{{ getFileName(file.file) }}</span>
          </div>
          <div class="file-info">
            <span class="file-name">{{ file.desc }}</span>
          </div>
          <div class="file-footer">
            <el-button
              @click="handleDownload(file.file)"
              type="success"
              size="mini"
              >下载</el-button
            >
          </div>
        </el-card>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFile = false">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 图片预览对话框 -->
    <el-dialog :visible.sync="previewVisible" :title="previewTitle" width="60%">
      <img :src="previewImageUrl" class="image-preview-full" />
      <div slot="footer" class="dialog-footer">
        <el-button @click="previewVisible = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getQaCityList, getQaList } from "@/api/qa";

export default {
  data() {
    return {
      getQaCityList: [],
      getQaLists: [],
      dataForm: {
        keyword: "",
        city_id: "",
      },
      dialogImage: false, // 控制图片列表对话框的显示
      previewVisible: false, // 控制图片预览对话框的显示
      previewImageUrl: "", // 预览图片的 URL
      previewTitle: "", // 预览图片的标题
      imageList: [
        // 示例图片列表
      ],
      fileList: [
        // 示例图片列表
      ],
      dialogFile: false,
    };
  },
  created() {
    getQaCityList().then((res) => {
      this.getQaCityList = res.data;
    });
  },
  watch: {
    "dataForm.keyword": function (newVal) {
      if (newVal) {
        this.onSubmit();
      }
    },
  },
  methods: {
    // 显示文件列表对话框
    showFileList(fileUrl) {
      if (fileUrl.length) {
        this.fileList = fileUrl;
      }
      this.dialogFile = true;
    },
    // 根据文件 URL 获取文件图标
    getFileIcon(url) {
      const ext = url.split(".").pop().toLowerCase();
      console.log('ext:' + ext);
      switch (ext) {
        case "pdf":
          return "el-icon-file-pdf";
        case "docx":
          return "el-icon-file-word";
        case "pptx":
          return "el-icon-file-ppt";
        case "xlsx":
          return "el-icon-file-excel";
        default:
          return "el-icon-file";
      }
    },
    // 根据文件 URL 获取文件图标
    getFileName(url) {
      return url.substring(url.lastIndexOf("/") + 1);
    },
    handleQacityl(val) {
      getQaList({ city_id: val }).then((res) => {
        this.getQaLists = res.data.data;
      });
    },
    handleZip(url) {
      if (url) {
        // window.open(url)
        fetch(url)
          .then((response) => response.blob())
          .then((blob) => {
            const link = document.createElement("a");
            const objectUrl = URL.createObjectURL(blob);
            link.href = objectUrl;
            link.download = url.split("/").pop(); // Extract filename from URL
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            URL.revokeObjectURL(objectUrl);
          })
          .catch((error) => {
            this.$message({
              showClose: true,
              message: "下载失败",
              type: "error",
            });
            console.error("Download error:", error);
          });
      } else {
        this.$message({
          showClose: true,
          message: "暂无下载链接",
          type: "warning",
        });
      }
    },
    load() {
      console.log("load");
    },
    handleprant(val) {
      if (!val) return ""; // 处理空值情况，避免返回 undefined 或其他非字符串值

      let replaceReg = new RegExp(this.dataForm.keyword, "ig");
      let replaceString = `<span style="color: #fff;background-color: #FC0421FF;">${this.dataForm.keyword}</span>`;
      return val.replace(replaceReg, replaceString);
    },
    handleprantHtml(val) {
      if (!val) return "";

      let p = this.dataForm.keyword;
      let regexp = new RegExp(p, "g");
      let replacedHtml = val.replace(/(?<=>)[^>]+(?=<[/]?\w+.*>)/g, (v) => {
        return v.replace(
          regexp,
          `<span style='color: #fff;background-color: #FC0421FF;'>${p}</span>`
        );
      });
      // 检查是否有替换发生
      if (replacedHtml === val) {
        // 如果没有替换发生，则调用handleprant
        return this.handleprant(val);
      }
      return replacedHtml;
    },
    onSubmit() {
      getQaList(this.dataForm).then((res) => {
        this.getQaLists = res.data.data;
      });
    },
    copyToClipboard(html) {
      const text = this.stripHtml(html);
      const input = document.createElement("textarea");
      input.value = text;
      document.body.appendChild(input);
      input.select();
      document.execCommand("copy");
      document.body.removeChild(input);
      this.$message({
        showClose: true,
        message: "内容已复制",
      });
    },
    stripHtml(html) {
      const div = document.createElement("div");
      div.innerHTML = html;
      return div.textContent || div.innerText || "";
    },
    showImgDialog(imagesUrls) {
      if (imagesUrls.length) {
        this.imageList = imagesUrls;
      }

      this.dialogImage = true;
    },
    // 处理图片预览
    handlePreview(url) {
      this.previewImageUrl = url;
      this.previewTitle = "图片预览";
      this.previewVisible = true;
    },
    // 处理图片删除
    handleRemove(index) {
      this.imageList.splice(index, 1);
    },
    // 处理图片下载
    handleDownload(url) {
      if (url) {
        // window.open(url)
        fetch(url)
          .then((response) => response.blob())
          .then((blob) => {
            const link = document.createElement("a");
            const objectUrl = URL.createObjectURL(blob);
            link.href = objectUrl;
            link.download = url.split("/").pop(); // Extract filename from URL
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            URL.revokeObjectURL(objectUrl);
          })
          .catch((error) => {
            this.$message({
              showClose: true,
              message: "下载失败",
              type: "error",
            });
            console.error("Download error:", error);
          });
      } else {
        this.$message({
          showClose: true,
          message: "暂无下载链接",
          type: "warning",
        });
      }
    },
  },
};
</script>

<style lang="scss" scoped>
@import "~@/assets/fonts/font.css";
body {
  font-family: PingFang !important;
}
.infinite-list {
  list-style-type: none;
  height: calc(100vh - 154px);
  padding: 0;
  margin: 0;
}
.desc_container {
  & + .desc_container {
    margin-top: 10px;
    padding-top: 10px;
  }
  .desc_title {
    font-size: 18px;
    font-weight: 500;
    color: #333333;
    line-height: 25px;
    margin-bottom: 10px;
  }
  .desc_content {
    font-size: 14px;
    font-weight: 300;
  }
}
.problem {
  .problem_form {
    margin-top: 10px;
    display: flex;
    justify-content: center;
  }
  .problem_container {
    display: flex;
    .problem_left {
      font-family: PingFang, sans-serif;
      font-weight: 300;
      width: 18%;
      background: #fff;
      padding: 0 20px;
      border-right: 2px solid #46a6ff;
      height: calc(100vh - 154px);
      .btn {
        color: #fff;
        padding: 10px 20px;
        cursor: pointer;
        text-align: center;
        background: #46a6ff;
        border-radius: 10px;
        & + .btn {
          margin-top: 10px;
        }
      }
    }
    .problem_right {
      width: 100%;
      background: #fff;
      padding: 0 20px;
      .problem_right_container {
        & + .problem_right_container {
          margin-top: 20px;
        }
        .title {
          font-size: 20px;
          font-weight: 600;
          margin-bottom: 10px;
          color: #46a6ff;
          & > :nth-child(1) {
            margin-right: 40px;
          }
        }
        .desc {
          font-size: 14px;
          color: #666;
          line-height: 24px;

          .copy-button {
            margin-left: 300px;
          }
        }
      }
    }
  }
}

.image-list-horizontal {
  display: flex;
  overflow-x: auto;
  white-space: nowrap;
  padding: 10px 0;
}
.image-card {
  display: inline-block;
  width: 150px;
  margin-right: 10px;
}
.image-preview {
  width: 100%;
  height: 100px;
  object-fit: cover;
}
.image-preview-full {
  width: 100%;
  max-height: 600px;
}
.image-footer {
  display: flex;
  justify-content: space-between;
}
.file-list-horizontal {
  display: flex;
  overflow-x: auto;
  white-space: nowrap;
  padding: 10px 0;
}
.file-card {
  display: inline-block;
  width: 400px; /* 扩大宽度以显示完整文件名 */
  margin-right: 10px;
}
.file-info {
  display: flex;
  align-items: center;
  overflow: hidden;
}
.file-icon {
  font-size: 24px;
  margin-right: 10px;
}
.file-name {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  max-width: calc(100% - 40px); /* 计算最大宽度以适应图标 */
}
.file-footer {
  display: flex;
  justify-content: flex-end;
}
</style>
