<template>
  <div class="detail">
    <div class="detail-content">
      <div class="detail-content-left">
        <div class="detail-content-left-text">
          文件列表
          <el-tree
            v-loading="loading"
            :data="data"
            highlight-current
            :props="defaultProps"
            @node-click="handleNodeClick"
          >
            <div slot-scope="{ node, data }" style="display: flex">
              <div class="detail-content-left-text-custom">
                {{ data.label }}
              </div>
            </div>
          </el-tree>
        </div>
      </div>

      <div v-loading="showViewloading" class="detail-content-right">
        <div v-if="isShowView">
          <el-button size="small" style="ma" @click="openNewForm">
            全屏查看
          </el-button>
          <div v-if="isfile == true">
            <iframe
              id="map"
              :src="fileSrc"
              scrolling="no"
              marginwidth="0"
              marginheight="0"
              frameborder="0"
              mainview.height="0"
              mainview.wdith="0"
              style="border: none"
              class="detail-content-right-text"
            />
          </div>
          <div v-if="isfile == false">
            <img :src="fileSrc" class="detail-content-right-img" />
          </div>
        </div>
        <!-- <el-input
          v-model="title"
          placeholder="请输入标题"
          style="width: 300px;margin-top:10px;"
        /> -->
        <!-- <Vditor
          v-if="isPost"
          :input-title="title"
          :publish-type="publishType"
          :file-md5="fileMd5"
          :input-content="inputContent"
        /> -->

        <div class="list-top-item">
          <a href="#" class="top-title">
            百伦论坛知识库
            <div
          /></a>
          <div />
        </div>
        <attachment-list
          :file="attachmentFile"
          :is-paid="isPaid"
          :price="price"
          :is-paid-attachment="isPaidAttachment"
          :attachment-price="attachmentPrice"
        />
        <topic-reward-list
          :author="thread.user || {}"
          :paid-information="paidInformation"
          :can-paid="forums && forums.paycenter && forums.paycenter.wxpay_close"
          :can-reward="
            forums &&
              forums.paycenter &&
              forums.paycenter.wxpay_close &&
              thread.canBeReward
          "
          :thread-type="thread.type || 0"
          :user-lists="[
            thread.paidUsers || [],
            thread.rewardedUsers || [],
            article.likedUsers || [],
            []
          ]"
          @payOrReward="showCheckoutCounter = true"
        />
        <topic-actions
          :thread-id="threadId"
          :actions="actions || []"
          @clickAction="postCommand"
        />
        <comment v-if="renderComponent" ref="comment" :thread-id="threadId" />
      </div>
    </div>
  </div>
</template>
<script>
import axios from "@/plugins/axios.js";
import handleError from "@/mixin/handleError";
const threadInclude =
  "posts.replyUser,threadAudio,user.groups,user," +
  "user.groups.permissionWithoutCategories,posts,posts.user,posts.likedUsers,posts.images," +
  "firstPost,firstPost.likedUsers,firstPost.images,firstPost.attachments,rewardedUsers," +
  "category,threadVideo,paidUsers,question,question.beUser,question.images,onlookers";
import env from "@/utils/env";
import config from "@/config.js";
import AttachmentList from "../../components/topic/AttachmentList.vue";
export default {
  components: { AttachmentList },
  data() {
    return {
      threadId: "26",
      renderComponent: true,
      loading: false,
      showViewloading: false,
      isShowView: false,
      isfile: true,
      fileSrc: "",
      isPost: true,
      qywxUserid: "",
      publishType: "knowledge",
      fileMd5: "",
      title: "",
      inputContent: "",
      data: [],
      defaultProps: {
        children: "children",
        label: "label"
      },
      list: [],
      thread: {},
      article: {},
      question: {},
      postId: 0,
      actions: [
        {
          text: this.$t("topic.read"),
          count: 0,
          command: "",
          canOpera: false,
          icon: "book"
        },
        {
          text: this.$t("topic.getLike"),
          count: 0,
          command: "isLiked",
          canOpera: true,
          isStatus: false,
          icon: "like"
        },
        {
          text: this.$t("topic.collection"),
          command: "isFavorite",
          canOpera: true,
          isStatus: false,
          icon: "favor"
        },
        {
          text: this.$t("topic.share"),
          command: "showLink",
          canOpera: true,
          icon: "link"
        }
      ],
      paidInformation: {
        price: "0",
        paid: false,
        paidUsers: [],
        paidCount: 0,
        isPaidAttachment: false,
        attachmentPrice: "0"
      },
      payment: { wechat_qrcode: "", rewardAmount: "" },
      location: { location: "", latitude: "", longitude: "" },
      managementList: [
        {
          name: "canEdit",
          command: "toEdit",
          isStatus: false,
          canOpera: false,
          text: this.$t("topic.edit"),
          type: "0"
        },
        {
          name: "canEssence",
          command: "isEssence",
          isStatus: false,
          canOpera: false,
          text: this.$t("topic.essence"),
          type: "1"
        },
        {
          name: "canSticky",
          command: "isSticky",
          isStatus: false,
          canOpera: false,
          text: this.$t("topic.sticky"),
          type: "2"
        },
        {
          name: "canHide",
          command: "isDeleted",
          isStatus: false,
          canOpera: false,
          text: this.$t("topic.delete"),
          type: "3"
        }
      ],
      showCheckoutCounter: false,
      showPasswordInput: false,
      showWxPay: false,
      defaultLoading: false,
      articleLoading: false,
      passwordError: false,
      passwordErrorTip: "",
      findPassword: false,
      attachmentPrice: "0.00",
      attachmentFile: {
        attachment: "",
        extension: "pdf",
        fileName: "",
        filePath: "",
        fileSize: 349279,
        fileType: "",
        id: 93,
        isApproved: 1,
        isRemote: false,
        order: 0,
        thumbUrl: "",
        type: 0,
        type_id: 118,
        url: ""
      },
      isPaid: false,
      isPaidAttachment: false,
      price: "0.00"
    };
  },
  computed: {
    threadId() {
      return this.$route.params.id;
    },
    currentUser() {
      return this.$store.state.user.info.attributes || {};
    },
    forums() {
      return this.$store.state.site.info.attributes || {};
    },
    rewardOrPay() {
      const price = parseFloat(this.paidInformation.price);
      const attachmentPrice = parseFloat(this.paidInformation.attachmentPrice);
      const questionPrice =
        Object.keys(this.question).length > 0
          ? parseFloat(this.question.onlooker_unit_price)
          : 0;
      return price > 0 || attachmentPrice > 0 || questionPrice > 0
        ? "pay"
        : "reward";
    },
    payOrRewardAmount() {
      const price = parseFloat(this.paidInformation.price || "0");
      const attachmentPrice = parseFloat(
        this.paidInformation.attachmentPrice || "0"
      );
      const questionPrice =
        Object.keys(this.question).length > 0
          ? parseFloat(this.question.onlooker_unit_price)
          : 0;
      return (
        price || attachmentPrice || questionPrice || this.payment.rewardAmount
      );
    },
    payOrderType() {
      const price = parseFloat(this.paidInformation.price || "0");
      const attachmentPrice = parseFloat(
        this.paidInformation.attachmentPrice || "0"
      );
      const questionPrice =
        Object.keys(this.question).length > 0
          ? parseFloat(this.question.onlooker_unit_price)
          : 0;
      // 1：注册，2：打赏，3：付费主题，4：付费用户组，5：问答提问支付，6：问答围观付费, 7: 付费附件
      if (price > 0) {
        return 3;
      } else if (attachmentPrice > 0) {
        return 7;
      } else if (questionPrice > 0) {
        return 6;
      } else {
        return 2;
      }
    }
  },
  created() {
    this.fileSrc = "";
    this.isShowView = false;
    this.inputContent = "";
    this.title = "";
    this.qywxUserid = "";
    this.data = [];
    this.loading = true;
    // 获取知识库带过来的id
    let fildId = this.$route.query.id;
    const qywxUserid = this.$route.query.useid;
    this.qywxUserid = this.$route.query.useid;
    const fatherid = this.$route.query.fatherid;
    const appointfileid = this.$route.query.appointfileid;
    const firstfileid = this.$route.query.firstfileid;
    if (appointfileid) {
      fildId = firstfileid;
    }
    // 获取树状数据
    axios
      .get(
        `${config.WEI_PAN_URL}/weipan/getfilelisttree?userId=${qywxUserid}&fildId=${fildId}&fatherid=${fatherid}`
      )
      .then(res => {
        // this.data = res.data.result;
        this.data = this.deleteChildren(res.data.result);
        this.loading = false;
        if (this.data) {
          if (appointfileid) {
            axios
              .get(
                `${config.WEI_PAN_URL}/weipan/getfilelisttree?userId=${qywxUserid}&fildId=${appointfileid}`
              )
              .then(res => {
                const file = res.data.result;
                // 触发点击事件
                this.handleNodeClick(file[0]);
              });
          } else {
            const file = this.data.filter(item => item.file == true);
            if (file) {
              // 触发点击事件
              this.handleNodeClick(file[0]);
            }
          }
        }
      });
    if (Object.keys(this.thread).length === 0) this.getThread();
    else this.initData();
    // 监听滚动事件
    // window.addEventListener("scroll", this.onScroll, false);
    // window.onload = function() {
    //   const _iframe = document
    //     .getElementById("map")
    //     .contentWindow.document.queryselector("WACPageBorder"); // get iframe下的id
    //   _iframe.style.display = "none"; // 修改样式
    // };
  },
  methods: {
    forceRerenders() {
      this.renderComponent = false;
      this.$nextTick(() => {
        this.renderComponent = true;
      });
    },
    deleteChildren(arr) {
      const childs = arr;
      for (let i = childs.length; i--; i > 0) {
        if (childs[i].children) {
          if (childs[i].children.length) {
            this.deleteChildren(childs[i].children);
          } else {
            delete childs[i].children;
          }
        }
      }
      return arr;
    },
    openNewForm() {
      window.open(this.fileSrc, "_blank");
    },
    handleNodeClick(data) {
      self = this;
      if (data.file) {
        this.showViewloading = true;
        axios
          .get(
            `${config.WEI_PAN_URL}/weipan/GetAttchmattachmentByFileId?fileId=${data.id}`
          )
          .then(res => {
            this.attachmentFile = res.data.result;
          });
        axios
          .get(`${config.WEI_PAN_URL}/weipan/GetFileInfo?fileId=${data.id}`)
          .then(res => {
            // const ele = document.querySelector(".WACPageBorder");
            // ele.style.border = "none";
            // console.log(ele, "ele");
            this.showViewloading = false;
            if (res.data) {
              const filePath = res.data.result.qiniuUrl;
              if (filePath) {
                this.isShowView = true;
                if (/\.(gif|jpg|jpeg|png|GIF|JPG|PNG)$/.test(filePath)) {
                  this.isfile = false;
                  this.fileSrc = filePath;
                }
                if (
                  /\.(xlsx|xls|csv|doc|docx|docx|rtf|ppt|pptx|pdf|zip|rar|7z|wps|txt|js|json|css|xml|sql|cs)$/.test(
                    filePath
                  )
                ) {
                  this.isfile = true;
                  this.fileSrc = `http://ow365.cn/?i=23468&furl=${filePath}`;
                }
              }
              // 获取fileid对应得threadId
              // const threadId = res.data.result.threadId;
              this.threadId = res.data.result.threadId.toString();
              this.forceRerenders(); // 强制从新渲染函数
              console.log(this.threadId, 3232);
            }
            this.fileMd5 = data.md5;
          });
      }
    },
    changTree(index) {
      console.log(index);
    },
    getThread() {
      return this.$store
        .dispatch("jv/get", [
          `threads/${this.threadId}`,
          { params: { include: threadInclude } }
        ])
        .then(
          data => {
            if (data.isDeleted) return this.$router.replace("/error");
            this.articleLoading = false;
            this.thread = data;
            this.article = data.firstPost;
            this.postId = this.article._jv.id;
            this.initData();
          },
          e => this.handleError(e, "thread")
        );
    },
    initData() {
      console.log("thread => ", this.thread);
      this.initManagementList(this.thread);
      this.initPaidInformation(this.thread);
      this.initActions(this.thread, this.article);
      this.initLocation(this.thread);
      this.initQuestion(this.thread);
      this.filterImages();
    },
    filterImages() {
      this.article.imageSource = this.article.images; // 把原图路径记为 imageSource
      if (
        this.article.contentAttachIds &&
        this.article.contentAttachIds.length > 0 &&
        this.article.images &&
        this.article.images.length > 0
      ) {
        this.article.images = this.article.images.filter(
          image => this.article.contentAttachIds.indexOf(image._jv.id) < 0
        );
      }
    },
    initQuestion(data) {
      if (!data.question) return;
      this.question = data.question;
      this.question.onlookerState = data.onlookerState;
      console.log(this.question, "question");
    },
    initLocation(data) {
      for (const key in this.location) this.location[key] = data[key];
    },
    initPaidInformation(data) {
      for (const key in this.paidInformation) {
        this.paidInformation[key] = data[key];
      }
    },
    initManagementList(data) {
      this.managementList.forEach(item => {
        item.canOpera = data[item.name];
        if (item.name === "canEssence") {
          item.isStatus = data.isEssence;
          item.text = item.isStatus
            ? this.$t("topic.cancelEssence")
            : this.$t("topic.essence");
        } else if (item.name === "canSticky") {
          item.isStatus = data.isSticky;
          item.text = item.isStatus
            ? this.$t("topic.cancelSticky")
            : this.$t("topic.sticky");
        }
      });
      if (
        (this.thread.type === 4 || this.thread.type === 5) &&
        this.managementList.filter(item => item.name === "canEdit").length > 0
      ) {
        // 语音贴和问答帖，不支持编辑
        this.managementList.filter(
          item => item.name === "canEdit"
        )[0].canOpera = false;
      }
      this.thread.isEssence = data.isEssence;
      this.managementList = this.managementList.filter(item => item.canOpera);
    },
    initActions(data, firstPost) {
      const viewInfo = { ...this.actions[0] };
      const favorInfo = { ...this.actions[2] };
      const likeInfo = { ...this.actions[1] };
      if (data) {
        viewInfo.count = data.viewCount;
        favorInfo.isStatus = data.isFavorite;
        favorInfo.text = favorInfo.isStatus
          ? this.$t("topic.collectionAlready")
          : this.$t("topic.collection");
        favorInfo.icon = favorInfo.isStatus ? "favored" : "favor";
        favorInfo.canOpera = data.canFavorite;
      }
      if (firstPost) {
        likeInfo.count = firstPost.likeCount;
        likeInfo.isStatus = firstPost.isLiked;
        likeInfo.canOpera = firstPost.canLike;
        likeInfo.text = likeInfo.isStatus
          ? this.$t("topic.liked")
          : this.$t("topic.getLike");
        likeInfo.icon = likeInfo.isStatus ? "liked" : "like";
      }

      this.$set(this.actions, 0, viewInfo);
      this.$set(this.actions, 1, likeInfo);
      this.$set(this.actions, 2, favorInfo);
    },
    paying({ payWay, hideAvatar, rewardAmount }) {
      if (
        this.rewardOrPay === "reward" &&
        (!rewardAmount || parseFloat(rewardAmount) === 0)
      ) {
        return this.$message.error(this.$t("pay.AmountCannotBeLessThan0"));
      }
      this.payment.rewardAmount = rewardAmount;
      this.showCheckoutCounter = false;
      if (payWay === "walletPay") {
        this.showPasswordInput = true;
        this.createOrder(
          hideAvatar,
          this.payOrRewardAmount,
          this.payOrderType,
          20
        ).finally(() => {
          this.defaultLoading = false;
        });
      } else if (payWay === "wxPay") {
        if (!this.forums.paycenter.wxpay_close) {
          return this.$message.warning(this.$t("pay.wxPayClose"));
        }
        this.createOrder(
          hideAvatar,
          this.payOrRewardAmount,
          this.payOrderType,
          10
        )
          .then(() => {
            this.payOrder().then(
              wechatQrcode => {
                this.payment.wechat_qrcode = wechatQrcode;
                this.wxPayActive().then(
                  () => {
                    this.getThread();
                  },
                  () => console.log("支付失败")
                );
              },
              () => console.log("支付失败")
            );
          })
          .finally(() => {
            this.defaultLoading = false;
          });
      }
    },
    onPasswordInputCompleted(password) {
      this.payOrder(password).then(
        () => {
          this.getThread();
        },
        () => console.log("支付失败")
      );
    },
    postCommand(item) {
      if (this.defaultLoading) return;
      this.defaultLoading = true;
      const params =
        item.command === "isLiked"
          ? { _jv: { type: `posts`, id: this.postId } }
          : { _jv: { type: `threads`, id: this.threadId } };
      params[item.command] = !item.isStatus;
      return this.$store
        .dispatch("jv/patch", params)
        .then(
          data => {
            data.firstPost && this.initManagementList(data);
            data.firstPost && this.initActions(data);
            if (item.command === "isSticky") {
              return item.isStatus
                ? this.$message.success(this.$t("topic.stickySuccess"))
                : this.$message.success(this.$t("topic.cancelStickySuccess"));
            }
            if (item.command === "isLiked") {
              return this.setLikeUser(!item.isStatus, data);
            }
            if (item.command === "isDeleted") return this.afterDeleted();
          },
          e => this.handleError(e)
        )
        .finally(() => {
          this.defaultLoading = false;
        });
    },
    setLikeUser(status, data) {
      this.initActions(null, data);
      status
        ? this.article.likedUsers.unshift(this.currentUser)
        : this.article.likedUsers.forEach((item, index, array) => {
            item.id === this.currentUser.id && array.splice(index, 1);
          });
    },
    afterDeleted() {
      this.$message({
        typeInformation: "success",
        message: this.$t("topic.deleteSuccessAndJumpToBack")
      });
      setTimeout(() => {
        this.$router.push("/");
      }, 1000);
    }
  },
  head() {
    return {
      title: "知识库",
      meta: [
        {
          hid: "keywords",
          name: "keywords",
          content: (this.thread.category && this.thread.category.name) || ""
        },
        {
          hid: "description",
          name: "description",
          content:
            (this.thread.firstPost &&
              this.thread.firstPost.summaryText.slice(0, 80)) ||
            ""
        },
        {
          name: "og:video",
          content:
            (this.thread.threadVideo && this.thread.threadVideo.media_url) || ""
        }
      ]
    };
  },
  textChange() {
    alert(332);
  }

  // },
  // destroy() {
  //   // 必须移除监听器，不然当该vue组件被销毁了，监听器还在就会出错
  //   window.removeEventListener("scroll", this.onScroll);
  // }
};
</script>
<style>
/* .detail-content-left-text
  .el-tree-node__content
  .detail-content-left-text-custom {
  width: 200px;
  overflow: hidden;
} */
.el-image__inner {
  object-fit: fill !important;
}
.detail-content-left-text
  .el-tree--highlight-current
  .el-tree-node.is-current
  > .el-tree-node__content {
  color: #2e8cf0 !important;
}
.detail-content-left-text .el-tree-node:focus > .el-tree-node__content {
  background-color: transparent !important;
  color: #2e8cf0 !important;
}
.detail-content-left-text .el-tree-node.is-current > .el-tree-node__content {
  background-color: transparent !important;
}
.detail-content-left-text .el-tree-node__hover {
  color: #2e8cf0 !important;
}
</style>
<style lang="scss" scoped>
.el-image__inner {
  object-fit: fill !important;
}
@import "@/assets/css/variable/color.scss";
.iframe-box {
  position: relative;
  width: 100%;
  height: 100%;
}
.iframe-absolute {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 99;
}
.detail {
  width: 100%;
  &-content {
    width: 100%;
    display: flex;
    justify-content: space-between;
    &-left {
      background: #fff;
      width: 210px;
      padding: 10px 0 0 25px;
      &-text {
        // position: fixed;
        font-size: 12px;
        line-height: 17px;
        background: #fff;
        overflow: hidden;
        i {
          line-height: 17px;
        }
        &-custom {
          width: 100px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      }
    }
    &-right {
      width: 867px;
      background: #fff;
      margin-left: 9px;
      padding: 20px;
      position: relative;
      &-text {
        width: 100%;
        height: 700px;
      }
      iframe {
      }

      &-img {
        width: auto;
        height: 100%;
      }
      .list-top-item {
        margin: 30px 0 0 0px;
        .top-title {
          color: #000;
          width: 122px;
          height: 25px;
          overflow: hidden;
          // text-overflow:ellipsis;
          // white-space: nowrap;
          display: -webkit-box;
          -webkit-box-orient: vertical;
          -webkit-line-clamp: 1;
          border-radius: 30px;
          text-align: center;
          background: #f7f7f7;
          border: 1px solid #f7f7f7;
          color: #777;
          font-size: 12px;
          line-height: 25px;
          text-align: center;
        }
        &:hover {
          .top-title {
            color: #1878f3;
            background: #fff;
            border: 1px solid #1878f3;
          }
        }
      }
    }
  }
}
</style>
