<template>
  <div class="ai-chat-container">
    <!-- 左侧历史对话列表 -->
    <div class="history-body">
      <div class="leftBody" v-if="isUnfold">
        <img src="~@/assets/img/ai.png" alt="" @click="isUnfold = !isUnfold" class="logo"/>
        <el-tooltip class="item" effect="dark" content="打开边栏" placement="top-start">
          <i class="el-icon-s-fold unfold" @click="isUnfold = !isUnfold"></i>
        </el-tooltip>
      </div>
      <transition name="slide">
        <div class="history-panel" v-if="!isUnfold">
          <div class="fold">
<!--            <div style="display: flex;align-items: center;">-->
              <img src="~@/assets/img/ai.png" alt="" class="leftLogo"/>
<!--              <div style="color: #f5f5f5;font-weight: bold;font-size: 20px">智小助</div>-->
<!--            </div>-->
            <i class="el-icon-s-fold leftFold" @click="isUnfold = !isUnfold"></i>
          </div>
          <div class="history-header">
            <button @click="createNewChat">新建对话</button>
          </div>
          <ul class="history-list">
            <li
              v-for="(item, index) in chatHistory"
              :key="index"
              :class="{ active: session_id === item.id }"
              @click="switchChat(item)"
            >
              <div class="history-item">
                <el-tooltip class="item" effect="dark" :content="item.name" placement="top-start">
                  <div class="history-main">{{ item.name }}</div>
                </el-tooltip>
                <el-popover
                  placement="right"
                  trigger="hover">
                  <ul>
                    <li class="popover-style" @click="renameChange(item)">
                      <i class="el-icon-edit"></i>
                      <div>重命名</div>
                    </li>
                    <li class="popover-style" @click="deleteChange(item)">
                      <i class="el-icon-delete"></i>
                      <div>删除</div>
                    </li>
                  </ul>
                  <div class="history-time" slot="reference"><i class="el-icon-more"></i></div>
                </el-popover>
              </div>
            </li>
          </ul>
        </div>
      </transition>
    </div>

    <!-- 右侧聊天窗口 -->
    <div class="chat-panel">

      <div v-show="session_id !== ''" class="chat-body" >
        <div class="chat-title">{{name}}</div>
        <div class="chat-messages" ref="messagesContainer">
          <div
            v-for="(message, index) in currentChat"
            :key="index"
            :class="['message', message.role]"
          >
            <div class="chat-flex">
              <img src="~@/assets/img/ai.png" alt="" class="chat-avater-left" v-if="message.role==='assistant'"/>
              <div class="message-content">
                <div  class="message-text" v-if="message.loading">搜索中...</div>
                <div class="message-text" v-else v-html="message.content"></div>
                <!--              <div class="message-time">{{ formatTime(message.timestamp) }}</div>-->
              </div>
              <img src="~@/assets/img/homePage/avater.png" alt="" class="chat-avater-right"  v-if="message.role==='user'"/>
            </div>
          </div>
        </div>
      </div>
      <div class="ai-right" v-show="session_id === ''">
        <div class="flex" style="justify-content: center;">
          <img src="@/assets/img/homePage/a1.png" alt="" class="ai-icon">
          <div class="title-body">
            <div class="title">HI,我是您的AI助力-<span class="title" style="color: #2C53E8">智小助</span></div>
            <div class="dialogue">简单对话，成为您“问策、查数、帮文”的智慧伙伴</div>
          </div>
        </div>
        <div class="flex">
          <div class="countUp-body">
            <div class="countUp-title">查数</div>
            <img src="@/assets/img/homePage/a2.png" alt="" class="countUp">
          </div>
          <div class="askAdvice-body">
            <div class="askAdvice-h">问策</div>
            <div class="askAdvice-t">问策|政策都知道</div>
            <img src="@/assets/img/homePage/a3.png" alt="" class="askAdvice">
          </div>
          <div class="helpWriting-body">
            <div class="helpWriting-t">帮文</div>
            <img src="@/assets/img/homePage/a4.png" alt="" class="helpWriting">
          </div>
        </div>
      </div>


      <div class="chat-input">
        <textarea
          v-model="inputMessage"
          @keydown.enter.exact.prevent="sendMessage"
          placeholder="请输入您想了解的内容..."
        ></textarea>
        <div class="chat-button">
          <el-button type="primary" round plain>联网搜索</el-button>
          <el-button type="primary" @click="sendMessage" :loading="toLoadIng">发送</el-button>
        </div>
      </div>
    </div>

    <!--  重命名  -->
    <super-dialog
      v-bind="$attrs"
      v-model="dialogFormVisible"
      width="30%"
      title="重命名"
      :modal="false"
      top="20vh"
    >
      <el-form :model="form" :rules="rules" label-width="60px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="renameThePopup">确 定</el-button>
      </div>
    </super-dialog>
  </div>
</template>

<script>
import axios from 'axios';
import SuperDialog from '@/components/SuperDialog/index.vue'
window.aiAdress = 'http://183.64.175.153:35063'
window.aiToken = 'ragflow-IwZmIzZmYwZjRlYzExZWY4NTVkMDI0Mm'
export default {
  components: {SuperDialog},
  data() {
    return {
      inputMessage: '',
      toLoadIng:false,
      isUnfold:false,
      chatHistory: [],
      showActice:'',
      chatId:'',
      session_id:'',
      name:'',
      currentChat: [],
      isTexarea: false,
      dialogFormVisible:false,
      form:{
        name:'',
      },
      rules: {
        name: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
        ],
      },
    };
  },

  created() {
    this.chatAssistant()
  },

  methods: {
    // 获取聊天助手
    chatAssistant(){
      axios.get(`${window.aiAdress}/api/v1/chats`, {
        headers: {
          'Authorization': `Bearer ${window.aiToken}`,
          'Content-Type': 'application/json'
        }
      })
        .then(response => {
          this.chatId = response.data.data[2].id
          this.getSessionHistory()
        })
        .catch(error => {});
    },

    //获取会话历史
    getSessionHistory(){
      axios.get(`${window.aiAdress}/api/v1/chats/${this.chatId}/sessions`, {
        headers: {
          'Authorization': `Bearer ${window.aiToken}`,
          'Content-Type': 'application/json'
        }
      })
        .then(response => {
          this.chatHistory = response.data.data;
        })
        .catch(error => {});
    },

    // 创建会话
    createASession(){
      const now = new Date();
      const year = now.getFullYear();
      const month = now.getMonth() + 1;
      const day = now.getDate();
      const formattedDate = `新建会话 ${year}/${String(month).padStart(2, '0')}/${String(day).padStart(2, '0')}`;
      axios.post(`${window.aiAdress}/api/v1/chats/${this.chatId}/sessions`,{
        name:formattedDate
      }, {
        headers: {
          'Authorization': `Bearer ${window.aiToken}`,
          'Content-Type': 'application/json'
        },
      })
        .then(response => {
          this.chatHistory.push(response.data.data);
          this.session_id = response.data.data.id;
          this.name = response.data.data.name;
          this.currentChat =  response.data.data.messages;

          if(this.isTexarea){
            this.currentChat.push({content: this.inputMessage, role: 'user'});
            this.getByValueChange()
            this.isTexarea = false
          }
        })
        .catch(error => {});
    },

    createNewChat() {
      this.createASession()
    },

    switchChat(item) {
      this.session_id = item.id;
      this.name = item.name;
      this.currentChat = item.messages;
      this.scrollToBottom();
    },

    // 发送
    async sendMessage() {
      if (!/^\s+$/.test(this.inputMessage) && this.inputMessage !== "") {
        if(this.session_id === ''){
          this.isTexarea = true
          await this.createASession()
        }else{
          this.currentChat.push({content: this.inputMessage, role: 'user'});
          await this.getByValueChange()
        }
      } else {
        this.$message.warning("不能发送空白消息");
      }
    },

    async getByValueChange(){
      let inputMessageBack = JSON.parse(JSON.stringify(this.inputMessage));
      this.inputMessage = ''
      this.toLoadIng = true
      let obj = {
        content: '',
        role:'assistant',
        loading:true,
      }
      this.currentChat.push(obj)
      this.scrollToBottom()
      try{
        let response = await fetch(`${window.aiAdress}/api/v1/chats/${this.chatId}/completions`,{
          method: 'POST',
          headers: {
            'Authorization': `Bearer ${window.aiToken}`,
            'Content-Type': 'application/json;charset=UTF-8',
            'responseType': 'stream'
          },
          body: JSON.stringify({
            question:inputMessageBack,
            session_id:this.session_id,
          })
        });
        if (!response.ok) {
          throw new Error('Network response was not ok');
        }
        const reader = response.body.getReader();
        const decoder = new TextDecoder();
        let result = true;

        while (result) {
          const { done, value } = await reader.read();

          if (done) {
            result = false;
            break;
          }

          const chunkText = decoder.decode(value, {stream: true});
          const jsonString = chunkText.replace(/^data:/, '')
          if(JSON.parse(jsonString).data.answer){
            this.currentChat[this.currentChat.length-1].content = JSON.parse(jsonString).data.answer;
            this.currentChat[this.currentChat.length-1].loading = false
            this.toLoadIng = false
          }else{
            this.getSessionHistory()
          }
          this.scrollToBottom()
        }
      }catch (err){
        // console.log(err)
      }
    },

    // 重命名点击事件
    renameChange(item){
      this.dialogFormVisible = true
      this.session_id = item.id;
      this.form.name = item.name
    },

    // 重命名弹窗
    renameThePopup(){
      axios.put(`${window.aiAdress}/api/v1/chats/${this.chatId}/sessions/${this.session_id}`,{
        name:this.form.name,
      }, {
        headers: {
          'Authorization': `Bearer ${window.aiToken}`,
          'Content-Type': 'application/json'
        },
      })
        .then(response => {
          this.dialogFormVisible = false
          this.getSessionHistory()
        })
        .catch(error => {});
    },

    deleteChange(item){
      this.$confirm('确定删除选中的对话吗？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          axios.delete(`${window.aiAdress}/api/v1/chats/${this.chatId}/sessions`,{
              headers: {
                'Authorization': `Bearer ${window.aiToken}`,
                'Content-Type': 'application/json'
              },
              data: { ids: [item.id] }
            })
            .then(response => {
              this.session_id = ''
              this.$message.success('删除成功');
              this.getSessionHistory()
            })
            .catch(error => {});
        })
        .catch((_) => _)
    },

    scrollToBottom() {
      this.$nextTick(() => {
        const container = this.$refs.messagesContainer;
        container.scrollTop = container.scrollHeight + 100;
      });
    }
  }
};
</script>

<style>
.el-popover{
  min-width: 90px !important;
  padding: 0 !important;
}
</style>
<style scoped lang="scss">
.chat-body{
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}
.ai-right{
  flex: 1;
  padding: 80px 0 30px 0;
  position: relative;
  top: 0;
  left:0;
  .ai-icon{
    width: 100px;
    margin-right: 20px;
  }
  .title-body{
    display: flex;
    flex-direction: column;
    .title{
      font-size: 34px;
      font-weight: 700;
      color: #f5f5f5;
    }
    .dialogue{
      font-size: 25px;
      color: #f5f5f5;
      margin-top: 10px;
    }
  }
}
.countUp-body{
  display: flex;
  flex-direction: column;
  align-items: center;
  position: absolute;
  left: 280px;
  top: 260px;
  .countUp-title{
    font-size: 25px;
    color: #f5f5f5;
    font-weight: 700;
    margin-bottom: 20px;
  }
  .countUp{
    width: 150px;
  }
}
.askAdvice-body{
  position: absolute;
  left: 570px;
  top: 300px;
  display: flex;
  flex-direction: column;
  align-items: center;
  .askAdvice-h{
    font-size: 35px;
    color: #2C53E8;
    font-weight: 700;
    margin-bottom: 20px;
  }
  .askAdvice-t{
    font-size: 20px;
    color: #f5f5f5;
  }
  .askAdvice{
    width: 175px;
  }
}
.helpWriting-body{
  position: absolute;
  right: 260px;
  top: 260px;
  display: flex;
  flex-direction: column;
  align-items: center;
  .helpWriting-t{
    font-size: 25px;
    color: #f5f5f5;
    font-weight: 700;
    margin-bottom: 20px;
  }
  .helpWriting{
    width: 150px;
  }
}

.popover-style{
  display: flex;
  align-items: center;
  cursor: pointer;
  padding: 10px 16px;
  border-bottom: 1px solid #f5f5f5;
  div{
    font-size: 14px;
    margin-left: 10px;
  }
}
.popover-style:last-child{
  border: none;
}
.popover-style:hover{
  background: rgba(16, 73, 97, 0.56);
}
.ai-chat-container {
  display: flex;
  height: 100vh;
  background: #f5f5f5;
}

.leftBody{
  width: 100px;
  height: 100%;
  background: #212327;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 0 20px 20px 20px;
  box-sizing: border-box;
}

.logo{
  width: 60px;
  margin-top: 40px;
  cursor: pointer;
}

.history-body{
  background: #292A2D;
  width: 300px;
}

.history-panel {
  padding: 0 20px 20px 20px;
  box-sizing: border-box;
  width: 300px;
  height: 100%;
  background: #212327;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.unfold{
  font-size: 34px;
  color: #ABB2BD;
  cursor: pointer;
  margin-top: 60px;
}

.fold{
  width: 100%;
  display: flex;
  align-items: center;
  margin-top: 40px;
  justify-content: space-between;
  .leftLogo{
    width: 60px;
  }
  .leftFold{
    font-size: 34px;
    color: #ABB2BD;
    cursor: pointer;
  }
}

.history-header {
  color: rgb(228,228,231);
  padding: 16px;
}

.history-header button {
  margin-top: 10px;
  padding: 8px 20px;
  background: #43A1FF;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.history-list {
  flex: 1;
  overflow-y: auto;
  list-style: none;
  padding: 0;
  margin: 0;
  width: 100%;
}

.history-list li {
  padding: 12px 16px;
  cursor: pointer;
  margin-top: 12px;
}

.history-list li.active {
  background: #494949;
  border-radius: 10px;
}

.history-list li:hover {
  background: #494949;
  border-radius: 10px;
}

.history-item {
  height: 20px;
  border-radius: 10px;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
}
.history-main{
  color: #E4E4E7;
  font-size: 18px;
  display: -webkit-box; /* 使用 flexbox */
  -webkit-box-orient: vertical; /* 垂直排列子元素 */
  -webkit-line-clamp: 1; /* 限制显示的行数为 2 */
  overflow: hidden; /* 隐藏超出部分 */
  text-overflow: ellipsis;
}
.history-time{
  color: #E4E4E7;
  background: #292A2D;
  font-size: 14px;
  padding: 5px;
  border-radius: 10px;
  box-sizing: border-box;
}

.chat-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: #292A2D;
  padding: 0 200px 0 100px;
}

.chat-title{
  color: #FFFFFF;
  font-size: 25px;
  font-weight: bold;
  text-align: center;
  margin: 40px 0 20px 0;
}

.chat-messages {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
}

.chat-flex{
  display: flex;
  align-items: center;
}

.chat-avater-left{
  width: 50px;
  border-radius: 50%;
  margin-right: 10px;
}

.chat-avater-right{
  width: 50px;
  border-radius: 50%;
  margin-left: 10px;
}

.message {
  margin: 20px 0;
  display: flex;
}

.message.user {
  justify-content: flex-end;
}
.user .chat-flex {
  justify-content: flex-end;
}

.message .assistant {
  justify-content: flex-start;
}
.assistant .chat-flex {
  justify-content: flex-start;
}

.message-content {
  max-width: 70%;
  padding: 12px 16px;
  border-radius: 8px;
}

.user .message-content {
  background: #1890ff;
  color: white;
}

.assistant .message-content {
  background: white;
  border: 1px solid #e0e0e0;
}

.message-text{
 word-wrap:break-word;
}

.message-time {
  font-size: 0.8em;
  color: #666;
  margin-top: 4px;
}

.chat-input {
  padding: 20px;
  background: #404045;
  border-radius: 30px;
  margin-bottom: 40px;
}

.chat-input textarea {
  background: transparent;
  padding: 12px;
  border: none;
  border-radius: 8px;
  resize: none;
  height: 80px;
  outline: none;
  color: white;
  font-size: 20px;
  width: 100%;
}

.chat-input .chat-button {
  display: flex;
  justify-content: space-between;
  cursor: pointer;
}
</style>
