<template>
  <div class="counsel-container">
    <div class="counsel-header">
      <span>会话<i class="ai el-icon-chat-dot-round"></i></span>
      <i class="el-icon-close cursor" @click="closeMsg"></i>
    </div>
    <div class="counsel-chats" ref="scrollRef">
      <div class="counsel-left flex" v-if="nowType == 'selectLand'">
        <div class="header-img">
          <img src="/static/images/aiModel/kefu.png" />
        </div>
        <div class="content">
          <span>Hi,有问题您可以这样问我:</span>
          <span class="high" @click="sendDefault">{{ defaultMsg }}</span>
        </div>
      </div>
      <!--会话内容-->
      <div v-for="(item, index) in questionList" :key="index">
        <!--右侧-->
        <div class="counsel-right flex" v-if="item.type == 0">
          <i class="el-icon-loading" v-if="item.mstatus == 0"></i>
          <i
            class="el-icon-warning cursor"
            v-else-if="item.mstatus == 1"
            @click="sendToBackend(item.content, index)"
          ></i>
          <div class="content">
            <!-- autoplay -->
            <audio v-if="item.mp3url" controls :src="item.mp3url"></audio>
            <div v-if="item.content">
              <span>{{ item.content }}</span>
              <i class="el-icon-document-copy" @click="copy(item)"></i>
            </div>
          </div>
          <div class="header-img">
            <img src="/static/images/aiModel/default.png" />
          </div>
        </div>
        <!--左侧-->
        <div class="counsel-left flex" v-else>
          <div class="header-img">
            <img src="/static/images/aiModel/kefu.png" />
          </div>
          <div class="content">
            <!-- breaks：是否将连续的换行符转换为<br>标签，默认值为false。
            typographer：是否启用智能引号和破折号等Typographer功能，默认值为false。
            linkify：是否将URL转换为链接，默认值为false。
            highlight：是否启用代码高亮，默认值为true。 -->
            <VueMarkdown
              v-if="item.type == 'answer'"
              class="markdowm"
              :source="item.content"
              :breaks="true"
              :linkify="true"
              :highlight="false"
            ></VueMarkdown>
            <div v-else>
              <span v-if="item.data" class="tit">参考意见</span>
              <span :class="{ high: item.type }" @click="onClick(item)">
                {{ item.content }}
              </span>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="consel-types">
      <div
        v-for="(titem, i) in types"
        :key="i"
        class="typeitem cursor"
        :class="{ heigType: nowType == titem.value }"
        @click="nowType = titem.value"
      >
        <i :class="titem.icon"></i>
        {{ titem.label }}
      </div>
    </div>
    <div class="voice" v-if="spdisabled">
      <div>正在识别</div>
      <div class="noise"></div>
    </div>
    <div class="searchBtom">
      <div
        class="icon"
        :class="
          spdisabled ? 'el-icon-turn-off-microphone' : 'el-icon-microphone'
        "
        title="按住说话"
        :disabled="spdisabled"
        @click="voice"
      ></div>
      <el-input
        clearable
        v-model="sendContent"
        @input="change_witch"
        @keyup.enter.native="send"
        class="search"
        placeholder="请输入问题"
      ></el-input>
      <div
        class="el-icon-s-promotion icon sendIcon"
        :class="sendContent ? 'ok' : 'no'"
        @click="send"
      ></div>
    </div>
  </div>
</template>
<script>
import { AddFzxz } from "../../api/ghss/ghxz.js";
import { GetMsg, uploadAudio, closeMsg } from "../../api/aiModel.js";
import record from "./record.js";
import VueMarkdown from "vue-markdown";
let recognition = null;
export default {
  props: {},
  components: {
    VueMarkdown,
  },
  data() {
    return {
      questionList: [],
      defaultMsg:
        "我要在抱坡区进行选址，用地面积30到50亩,选择居住用地,距离幼儿园200米，距离医院300米，距离火葬场大于5000米",
      sendContent: "",
      spdisabled: false,
      nowType: "selectLand",
      types: [
        { label: "智能选址", value: "selectLand", icon: "el-icon-s-home" },
        { label: "知识问答", value: "answer", icon: "el-icon-chat-line-round" },
      ],
    };
  },
  created() {},
  mounted() {},

  methods: {
    initSpeech() {
      // 检查浏览器是否支持SpeechRecognition
      const SpeechRecognition =
        window.SpeechRecognition || window.webkitSpeechRecognition;
      if (!SpeechRecognition) {
        alert(
          "你的浏览器不支持语音识别功能，请使用支持的浏览器，例如Google Chrome。"
        );
      } else {
        recognition = new SpeechRecognition();
        recognition.lang = "zh-CN"; // 设置识别语言为中文
        recognition.interimResults = false; // 不返回临时结果
        recognition.maxAlternatives = 1; // 返回的识别结果数量

        recognition.onstart = () => {
          this.$message.success("开始语音识别...");
          this.spdisabled = true;
        };
        recognition.onresult = (event) => {
          this.sendContent = event.results[0][0].transcript;
          // this.send(); // 将识别结果发送到后台
        };
        recognition.onerror = (event) => {
          this.$message.warning("语音识别出错: " + event.error);
        };
        recognition.onend = () => {
          // this.$message.success("语音识别结束:");
          console.log("语音识别结束");
          this.spdisabled = false;
        };
      }
    },
    /**初始化 */
    init() {
      let _this = this;
      record.getPermission(function (permiss) {
        if (permiss.status == "fail") {
          _this.$message.warning("语音识别出错: " + permiss.data);
        } else {
          record.startRecorder();
          _this.$message.success("开始语音识别...");
          _this.spdisabled = true;
        }
      });
    },
    /**结束录音 */
    stop() {
      let _this = this;
      record.stopRecorder(function (res) {
        _this.upload(res);
      });
      this.spdisabled = false;
    },
    copy(item) {
      this.sendContent = item.content;
    },
    sendDefault() {
      this.sendContent = this.defaultMsg;
      // this.send();
    },
    send() {
      // 咨询问题
      if (this.sendContent) {
        this.questionList.push({
          type: 0,
          content: this.sendContent,
          mstatus: 0,
        });
        this.sendToBackend(this.sendContent, this.questionList.length - 1);
        this.sendContent = "";
      }
    },
    voice() {
      console.log("---this.spdisabled-", this.spdisabled);
      if (!this.spdisabled) {
        // if (!recognition) this.initSpeech();
        // recognition.start(); // 开始语音识别
        this.init();
      } else {
        this.stop();
      }
    },
    upload({ blob, formData }) {
      this.questionList.push({
        type: 0,
        mp3url: (window.URL || webkitURL).createObjectURL(blob),
        mstatus: 0,
      });
      let mindex = this.questionList.length - 1;
      /**处理 */
      uploadAudio(formData)
        .then((ares) => {
          if (ares.status == 200) {
            this.questionList[mindex].content = ares.data.voiceMsg;
            this.sendToBackend(ares.data.voiceMsg, mindex);
          } else {
            this.$message.error(ares.data.msg);
          }
        })
        .catch(() => {});
    },
    sendToBackend(msg, mindex) {
      this.questionList[mindex].mstatus = 0;
      GetMsg({ msg, type: this.nowType })
        .then((mres) => {
          if (mres.status == 200) {
            this.questionList[mindex].mstatus = 2;
            if (mres.data.code == 200 && mres.data.data) {
              if (mres.data.type == "selectLand") {
                this.questionList.push({
                  type: mres.data.type,
                  content: "分析中...请稍等",
                });
                this.AddFzxz(mres.data.data, mres.data.type);
              } else {
                this.questionList.push({
                  type: mres.data.type,
                  content: mres.data.data,
                });
              }
            } else {
              this.questionList.push({
                content: mres.data.data || "抱歉！缺少分析数据",
              });
            }
          } else {
            this.questionList[mindex].mstatus = 1;
            // this.$message.error("发送到后台时发生错误:");
          }
        })
        .catch(() => {
          this.questionList[mindex].mstatus = 1;
          // this.$message.error("发送到后台时发生错误:");
        });
    },
    AddFzxz(xzdata, type) {
      const loading = this.$loading({
        lock: true,
        text: "分析中",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      AddFzxz(xzdata)
        .then((res) => {
          console.log("xuanz", res);
          loading.close();
          this.questionList.push({
            type,
            content: "查看智能选址结果",
            data: res.data,
          });
          this.$message({
            message: res.message,
            type: res.success ? "success" : "warning",
          });
        })
        .catch((error) => {
          loading.close();
          this.$message.error(error);
        });
    },
    onClick(item) {
      if (item.data) return;
      if (item.type == "selectLand") {
        this.$router.push({
          path: "/siteselection",
          query: { rwbsm: item.data.rwbsm },
        });
        this.$emit("close");
      }
    },
    closeMsg() {
      this.$emit("close");
      closeMsg().then((ares) => {
        if (ares.status == 200) {
          this.questionList[mindex].content = ares.data.voiceMsg;
          this.sendToBackend(ares.data.voiceMsg, mindex);
        } else {
          this.$message.error(ares.data.msg);
        }
      });
    },
  },
  watch: {
    questionList() {
      this.$nextTick(() => {
        this.$refs.scrollRef.scrollTop = this.$refs.scrollRef.scrollHeight;
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.flex {
  display: flex;
}
//智能咨询
.counsel-container {
  padding: 15px;
  width: 100%;
  height: 100%;
  position: absolute;
  background: #222;
  .counsel-header {
    display: flex;
    align-items: center;
    padding: 10px 20px;
    font-size: 16px;
    color: #fff;
    border-bottom: 1px solid #1f4099;
    margin-bottom: 10px;
    position: relative;
  }

  .time {
    display: block;
    text-align: center;
    margin-bottom: 20px;
    color: #999999;
    line-height: 40px;
  }

  .counsel-chats {
    height: calc(100% - 190px);
    overflow-x: hidden;
    overflow-y: auto;
    .header-img {
      // flex: 0 0 50px;
      margin-left: 10px;
      width: 50px;
      height: 50px;
      border-radius: 50px;
      display: block;
      overflow: hidden;

      img {
        width: 50px;
        height: 50px;
        border-radius: 50px;
        object-fit: cover;
      }
    }
    .high {
      color: #b6e0ff !important;
      cursor: pointer;
      display: block;
    }
    .cursor {
      cursor: pointer;
    }
    .content {
      // flex: 1;
      margin-left: 10px;
      max-width: calc(100% - 100px);
      padding: 5px 20px;
      border-radius: 8px;
      background: #40a0ff6c;

      .tit {
        display: block;
        color: #f99f2b;
        margin-bottom: 10px;
      }

      span {
        color: #ffffff;
        line-height: 20px;
      }
      .markdowm {
        width: 100%;
        word-break: break-word; /* 超出容器宽度时自动换行 */
        white-space: pre-wrap; /* 保持空白符序列，但是正常地换行 */
        // overflow-wrap: break-word;
        /deep/ pre {
          white-space: pre-wrap;
        }
      }
    }
    .counsel-left {
      margin-bottom: 30px;
      align-items: flex-start;
      .content {
        background: #b6e1ff3b;
      }
    }
    .counsel-right {
      margin-bottom: 30px;
      justify-content: flex-end;
      align-items: flex-start;
      width: 100%;
      i {
        font-size: 20px;
      }
      .el-icon-warning {
        color: #ff6666;
      }
    }
  }
  audio {
    height: 40px;
  }
  audio::-webkit-media-controls-enclosure {
    // background-color: #40a0ff6c;
    // color: #fff;
  }
}
.consel-types {
  position: absolute;
  bottom: 100px;
  width: calc(100% - 20px);
  display: flex;
  .typeitem {
    border: 1px solid #ffffff;
    border-radius: 8px;
    padding: 5px 10px;
    margin-right: 20px;
  }
  .heigType {
    border-color: #f0c472;
    color: #f0c472;
  }
}
.voice {
  width: 75%;
  // height: 100px;
  position: absolute;
  left: 15%;
  bottom: 92px;
  text-align: center;
  border-radius: 8px;
  background: #40a0ff6c;
  padding: 5px 20px;
  .noise {
    width: 110px;
    height: 40px;
    background-image: url("/static/images/aiModel/noise.png");
    background-size: 100% 100%;
    margin: 10px auto;
  }
}

.searchBtom {
  position: absolute;
  bottom: 20px;
  width: calc(100% - 20px);
  height: 70px;
  background: #44444e !important;
  border: 1px solid rgba(0, 0, 0, 0.12);
  box-shadow: #0003 0 0 10px;
  border-radius: 8px;
  display: flex;
  padding-top: 15px;
  .search {
    width: calc(100% - 120px);
    margin: 0 10px;
  }
  .icon {
    width: 40px;
    height: 40px;
    font-size: 40px;
    cursor: pointer;
  }
  .no {
    color: #2f2f39;
  }
  .ok {
    color: #0f7ac8;
  }
}
/deep/ .el-icon-close:before {
  position: absolute;
  top: 10px;
  right: 10px;
  font-size: larger;
  font-weight: bold;

  &:hover {
    color: aqua;
  }
}
</style>
