<template>
  <div class="gpt-box">
    <div class="scroll-container">
      <div
        class="arco-card-body"
        :class="{ 'card-activited': item.activited }"
        @click="topListChange(index)"
        v-for="(item, index) in topList"
        :key="index"
      >
        <div class="arco-list-item-meta">
          <div class="arco-list-item-meta-avatar">
            <img class="logo" :src="item.src" />
          </div>
          <div class="arco-list-item-meta-content">
            <div class="arco-list-item-meta-title">{{ item.title }}</div>
            <div class="arco-list-item-meta-description">{{ item.content }}</div>
          </div>
        </div>
      </div>
    </div>
    <div class="chart-box" id="chart-box" ref="chartBox">
      <div class="chart-scroll" ref="chartScroll">
        <div class="chart-content" v-for="(item, index) in messageList" :key="index">
          <div class="chart-name">
            <img
              v-show="item.role == 'GPT'"
              src="../../assets/images/ai.jpg"
              class="public1"
            />
            <img
              v-show="item.role == 'USER'"
              src="../../assets/images/public1.png"
              class="public1"
            />

            <div
              class="copy-box"
              @click="copyText(item.content)"
              v-show="item.content != ''"
            >
              <i class="el-icon-document-copy"></i>复制全文
            </div>
          </div>
          <div class="chart-tips" v-show="item.content != ''">{{ item.content }}</div>
          <div class="chart-tips" v-show="item.content == ''">
            <div
              v-loading="true"
              element-loading-text="努力生成中..."
              element-loading-spinner="el-icon-loading"
              class="loadBox"
            ></div>
          </div>
        </div>
      </div>
    </div>
    <div class="send-btn">
      <el-input
        type="text"
        @keyup.enter.native="sendMsg"
        v-model="inputMsg"
        class="send-input"
      />
      <el-button
        class="send-btn-s"
        size="small"
        icon="el-icon-s-promotion"
        type="primary"
        v-loading="sendLoading"
        :disabled="sendDisabled"
        @click="sendMsg"
      ></el-button>
    </div>
  </div>
</template>

<script>
import { gptList, gptSend } from "@/api/gpt.js";
import { EventSourcePolyfill } from "event-source-polyfill";
import { getToken } from "@/utils/auth";
import Cookies from "js-cookie";

export default {
  props: {},
  data() {
    return {
      topList: [
        {
          title: "AI问答 🔥",
          content: "和GPT模型自由问答",
          activited: true,
          src: require("../../assets/images/gpt.png"),
        },
        {
          title: "直播带货脚本",
          content: "一键生成直播脚本，直播带货神器",
          activited: false,
          src: require("../../assets/images/zb.png"),
        },
        {
          title: "商品卖点",
          content: "自动生成用于主图和详情页的设计文案",
          activited: false,
          src: require("../../assets/images/sh.png"),
        },
        {
          title: "电商营销文案",
          content: "自动生成简短的卖点和价格拆解",
          activited: false,
          src: require("../../assets/images/wn.png"),
        },
      ],
      messageList: [],
      inputMsg: "",
      sendLoading: false,
      sendDisabled: false,
      pageNum: 1,
      timeHeight: null,
      scrollStatus: false,
      scrollPage: false,
      // 全面屏
      isIphoneX:
        window.devicePixelRatio &&
        window.devicePixelRatio === 3 &&
        window.screen.width >= 375 &&
        window.screen.height >= 812,
    };
  },
  mounted() {
    this.msgHistory();
    this.timeHeight = document.getElementById("chart-box");
    this.timeHeight.addEventListener("scroll", this.handleScroll, true);

    console.log(this.isIphoneX);
    // this.eventSourceStart();
  },
  beforeDestroy() {
    this.timeHeight.removeEventListener("scroll", this.handleScroll);
  },
  methods: {
    msgHistory() {
      gptList({
        pageNum: this.pageNum,
        pageSize: 10,
      }).then((res) => {
        if (res.status == 200) {
          if (
            res.data &&
            res.data.gptMessageResDTOS &&
            res.data.gptMessageResDTOS.length > 0
          ) {
            let gptMessageResDTOS = res.data.gptMessageResDTOS;
            gptMessageResDTOS.forEach((element) => {
              this.messageList.unshift({
                role: element.sendName == "GPT" ? element.sendName : "USER",
                content: element.content,
              });
            });
            if (this.pageNum == 1) {
              this.$nextTick(() => {
                this.scrollToBottom();
              });
            } else {
              //加载第二页时保持滚动距离
              const scrollElem = this.$refs.chartBox;
              const eheight = scrollElem.scrollHeight - scrollElem.scrollTop;
              this.$nextTick(() => {
                scrollElem.scrollTop = scrollElem.scrollHeight - eheight;
              });
            }
            if (this.pageNum * 10 <= res.data.total) {
              this.scrollPage = true;
              this.pageNum++;
            }
          } else {
            this.messageList = [
              {
                role: "GPT",
                content: `我是AI大模型，有什么可以帮您？`,
              },
            ];
          }
        }
      });
    },
    topListChange() {},
    sendMsg() {
      if (this.inputMsg == "") {
        this.$message({
          message: "请输入您的问题。",
          type: "warning",
          customClass: "phone-message",
          center: true,
        });
        return false;
      }
      this.sendDisabled = true;
      this.messageList.push({ role: "USER", content: this.inputMsg });
      this.messageList.push({ role: "GPT", content: "思考中..." });

      // gptSend({
      //   content: this.inputMsg,
      // })
      //   .then((res) => {
      //     if (res.status == 200) {
      //       this.messageList[this.messageList.length - 1].content = res.data.content;
      //     } else {
      //       this.messageList[this.messageList.length - 1].content = res.msg;
      //     }
      //   })
      //   .catch((_) => {
      //     this.messageList[this.messageList.length - 1].content = "系统超时，请重试";
      //   });
      this.eventSourceStart();
      this.$nextTick(() => {
        this.scrollToBottom();
      });
    },
    scrollToBottom() {
      const scrollElem = this.$refs.chartBox;
      scrollElem.scrollTop = scrollElem.scrollHeight;
      // scrollElem.scrollTo({ top: scrollElem.scrollHeight, behavior: "smooth" });
      this.scrollStatus = true;
    },
    handleScroll() {
      if (this.scrollStatus && this.scrollPage) {
        let topF = this.$refs.chartBox.scrollTop;
        if (topF == 0) {
          this.scrollPage = false;
          this.msgHistory();
        }
      }
    },
    copyText(text) {
      window.navigator.clipboard
        .writeText(text)
        .then(() => {
          // this.$message.success("复制成功");
          this.$message({
            message: "复制成功",
            type: "success",
            customClass: "phone-message",
            center: true,
          });
        })
        .catch((error) => {
          // this.$message.warning("复制失败");
          this.$message({
            message: "复制失败",
            type: "warning",
            customClass: "phone-message",
            center: true,
          });
        });
    },
    eventSourceStart() {
      const eventSource = new EventSourcePolyfill(
        `https://oco.xsbuy.cn/gpt/send?content=${this.inputMsg}&userName=${Cookies.get(
          "username"
        )}`,
        {
          headers: {
            Authorization: "Bearer " + getToken(),
          },
          withCredentials: false,
        }
      );
      let sse = null;
      eventSource.onopen = (event) => {
        // console.log("开始输出后端返回值", event.target);
        sse = event.target;
      };

      eventSource.onmessage = (event) => {
        let wordTimeout = null;
        console.log("event-data====》", event.data);
        // 返回结束标识关闭sse
        if (event.data == "the end") {
          // this.itemMessageList.push(obj);
          wordTimeout = null;
          if (sse) {
            sse.close();
            this.inputMsg = "";
            this.sendDisabled = false;
          }
          return;
        }
        // console.log(event.data);
        // if (!event.data.indexOf("<br /><br />") == 0) {
        //   let __data = JSON.parse(event.data);
        //   console.log("__data-data========>", __data);
        //   // console.log(obj, "-----------obj");
        //   if ((__data && __data.content == null) || __data.content == "null") {
        //     return;
        //   }

        if (this.messageList[this.messageList.length - 1].content == "思考中...") {
          this.messageList[this.messageList.length - 1].content = "";
        }
        wordTimeout = setTimeout(() => {
          this.messageList[this.messageList.length - 1].content += event.data; //找到\n并替换成换行标签<br />
        }, 10);
        this.$nextTick(() => {
          this.scrollToBottom();
        });
        // }
      };
      eventSource.onerror = (event) => {
        console.log(event);
        this.$message({
          message: "服务异常请重试。",
          type: "warning",
          customClass: "phone-message",
          center: true,
        });
        event.target.close();
        this.inputMsg = "";
        this.sendDisabled = false;
      };
    },
  },
};
</script>

<style scoped lang="scss">
@import "@/assets/styles/mixin.scss";
.scroll-container {
  background-color: #fff;
  position: absolute;
  width: 100%;
  display: inline-flex;
  overflow-x: scroll;
  overflow-y: hidden;
  white-space: nowrap;
  padding: 10px 0;
  height: 118px;
}

.gpt-box {
  max-width: 1080px;
  height: 100%;
  margin: 0 auto;
}
.arco-card-body {
  width: 262px;
  padding: 16px;
  background-color: rgb(243 244 246);
  border-radius: 5px;
  margin: 0 5px;
  /* cursor: pointer; */
  cursor: not-allowed;
}
.arco-list-item-meta {
  display: flex;
  align-items: center;
  padding: 4px 0;
  height: 60px;
}
.arco-list-item-meta-content {
  width: 160px;
  white-space: break-spaces;
}
.arco-list-item-meta-avatar:not(:last-child) {
  display: flex;
  margin-right: 16px;
}
.arco-list-item-meta-title {
  font-size: 17px;
  font-weight: 700;
}
.arco-list-item-meta-description {
  font-size: 12px;
  margin-top: 5px;
}
.logo {
  width: pxTorem(40);
  height: pxTorem(40);
}
.card-activited {
  background: rgb(224, 223, 241);
  cursor: pointer;
}

.chart-box {
  max-width: 1080px;
  height: calc(100vh - 84px);
  background-color: rgb(234, 237, 246);
  padding: 8px;
  padding-top: 118px;
  overflow-x: hidden;
  overflow-y: scroll;
}
.chart-content {
  padding: pxTorem(12) pxTorem(24);
  cursor: pointer;
  border-radius: 10px;
  .chart-name {
    font-weight: 700;
    font-size: 16px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .copy-box {
      font-size: 12px;
      color: #666;
      font-weight: 300;
      display: none;
      align-items: center;
      .el-icon-document-copy {
        margin-right: 4px;
      }
    }
    .copy-box:hover {
      color: #0084ff;
    }
  }
  .chart-tips {
    border-radius: 5px;
    padding: 8px 0;
    font-size: 16px;
  }
}
.chart-content:hover {
  background-color: rgb(241 245 249);
  .copy-box {
    display: flex;
  }
}

.public1 {
  width: 26px;
  height: 26px;
  object-fit: cover;
  margin-top: 3px;
}
.send-btn {
  width: 100%;
  max-width: 1080px;
  position: absolute;
  bottom: 0;
  background: rgb(243 244 246);
  padding: 24px 16px;
  display: flex;
}
.send-btn-s {
  background: linear-gradient(to right, #9993ff, #0084ff);
  border: none;
  padding: 9px 25px;
  margin-left: 12px;
  font-size: 16px;
}
.loadBox {
  width: 200px;
  height: 30px;
  ::v-deep .el-loading-mask {
    background: none;
  }
  ::v-deep .el-loading-spinner {
    display: flex;
    align-items: center;
  }
  ::v-deep .el-icon-loading {
    margin-right: 8px;
  }
}
</style>
