<template>
  <div class="chat-container">
    <div class="chat-box" ref="chatBox">
      <div v-for="(message, index) in messages" :key="index" :class="[
          'chat-message',
          message.isUser ? 'user-message' : 'incoming-message',
        ]">
        <div class="header-user" v-if="message.isUser">
          <div class="avatar-wrapper" :class="message.isUser ? 'user-avatar' : ''">
            <img src="@/assets/logo/logo.png" alt="avatar" class="avatar" />
          </div>
          <div class="user-name">用户</div>
        </div>
        <div class="header" v-else>
          <div class="avatar-wrapper" :class="message.isUser ? 'user-avatar' : ''">
            <img src="@/assets/logo/logo.png" alt="avatar" class="avatar" />
          </div>
          <div class="user-name">系统</div>
        </div>
        <div class="message-table" v-if="message.isTable">
          <div v-if="message.isTable" class="message-table-box">
            <div v-for="(device, index) in message.tableData" :key="index" v-if="message.tableData.length > 0">
              <div class="flex-title">
                <el-link class="name" title="点击下载文件" :underline="false" @click="downloadFile(device.fileUrl)">{{
                    getFileNameBeforeLastUnderscore(device.fileName)
                  }}</el-link>
                <div>
                  <el-link type="primary" class="link" :underline="false" @click="openFile(device.fileUrl)">预览&nbsp;
                  </el-link>

                  <el-link type="primary" class="link" style="margin-left:5px" :underline="false"
                    @click="handleDetail(device)">详情</el-link>
                </div>
              </div>
              <el-link type="primary" :underline="false" class="link">[{{
                  device.belongType === "tech"? "技术资料" : device.belongType === "fault"? "故障记录": "故障案例"
                }}]</el-link>
              <div class="content" v-html="device.attachment.content"
                :style="{ maxHeight: '60px', overflowY: 'hidden' }"></div>
            </div>
            <div v-if="message.tableData == null">无对应数据，请重新查询</div>
          </div>
          <div v-if="message.time" class="message-time">{{ message.time }}</div>
        </div>
        <div class="message-content" v-else>
          <div class="message-text">
            <span>{{ message.displayedText }}</span>
          </div>
          <div v-if="message.time" class="message-time">{{ message.time }}</div>
        </div>
      </div>
    </div>

    <div class="input-box">
      <input type="text" v-model="inputMessage" @keyup.enter="sendMessage" placeholder="输入您的消息..." />
      <el-button @click="sendMessage" :disabled="loading" class="send-btn">
        <i class="el-icon-s-promotion"></i>发送
      </el-button>
    </div>
    <TechDialog ref="techDialog" :showFlag="teachShowFlag" @close="handleDialogClose" :belongId="belongId" />
    <FaultDialog :showFlag="faultShowFlag" @close="handleFaultClose" :belongId="belongId" />
    <FaultCaseDialog :showFlag="caseShowFlag" @close="handleCaseClose" :belongId="belongId" />
    <!-- 文件预览对话框 -->
    <el-dialog title="文件预览" :visible.sync="open" width="70%" append-to-body :before-close="handleBeforeClose">
      <div style="max-height: 70vh; overflow: auto ;">
        <FilePreview :fileUrl="fileUrl" />
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getSearchData, getWarning } from "@/api/search";
import {
  listFaultSetting,
  getFaultSetting,
  delFaultSetting,
  addFaultSetting,
  updateFaultSetting,
} from "@/api/fault/faultSetting";

import TechDialog from './comp/techDialog.vue'
import FaultDialog from './comp/faultDialog.vue'
import FaultCaseDialog from './comp/faultCaseDialog.vue'
import FilePreview from "@/components/Preview/index.vue";

export default {
  name: 'ChatComponent',
  components: {
    TechDialog,
    FaultDialog,
    FaultCaseDialog,
    FilePreview
  },
  data() {
    return {
      inputMessage: "",
      messages: [], // 消息列表
      teachShowFlag: false,
      caseShowFlag: false,
      recordShowFlag: false,
      faultShowFlag: false,
      belongId: '',
      loading: false,
      url: '',
      open: false, // 是否显示预览弹窗
      fileUrl: '' // 预览文件路径
    };
  },
  created() {
    // 可以通过props控制是否初始化时获取警告信息
    if (this.autoLoadWarning) {
      this.getWarning();
    }
  },
  props: {
    // 是否自动加载警告信息
    autoLoadWarning: {
      type: Boolean,
      default: true
    }
  },
  methods: {
    getWarning() {
      getFaultSetting(1).then((response) => {
        var setting = response.data;
        // 三月未处理故障
        if (setting.threeMonthOpen == "true") {
          var index = 0;
          getWarning().then((response) => {
            index = response.data;
            if (index > 0) {
              this.$notify({
                title: "监控提示",
                message: "有 " + index + " 条故障监控未处理，请及时处理！",
                type: "warning",
              });
            }
          });
        }
      });
    },
    handleDetail(device) {
      this.belongId = device.belongId
      if (device.belongType == "tech") {
        this.teachShowFlag = true
      } else if (device.belongType == 'case') {
        this.caseShowFlag = true
      } else {
        this.faultShowFlag = true
      }
    },
    handleDialogClose() {
      this.teachShowFlag = false;
    },
    handleCaseClose() {
      this.caseShowFlag = false;
    },
    handleFaultClose() {
      this.faultShowFlag = false;
    },
    handleRecordDialogClose() {
      this.recordShowFlag = false;
    },
    downloadFile(fileUrl) {
      const baseUrl = process.env.VUE_APP_BASE_API;
      const fullUrl = baseUrl + fileUrl;
      this.createloadFile(fullUrl);
    },
    openFile(fileUrl) {
      this.open = false; // 关闭弹窗
      this.fileUrl = ""; // 清空旧的 fileUrl
      this.$nextTick(() => {
        const baseUrl = process.env.VUE_APP_BASE_API;
        const fullUrl = new URL(fileUrl, baseUrl).toString(); // 合并URL
        this.fileUrl = fullUrl; // 设置新的 fileUrl
        this.open = true; // 打开弹窗
        console.log("打开文件路径:", this.fileUrl);
      });
    },
    handleBeforeClose(done) {
      this.fileUrl = "";
      this.open = false;
    },
    cancel() {
      this.fileUrl = "";
      this.open = false;
    },
    createloadFile(fileUrl) {
      // 创建一个隐藏的 <a> 标签
      fetch(fileUrl)
        .then((response) => {
          if (!response.ok) {
            throw new Error("Network response was not ok");
          }
          return response.blob();
        })
        .then((blob) => {
          const link = document.createElement("a");
          link.href = URL.createObjectURL(blob);
          link.download = decodeURIComponent(fileUrl.split("/").pop());
          link.click();
          URL.revokeObjectURL(link.href);
        })
        .catch((error) => {
          console.error("文件下载失败:", error);
        });
    },
    getFileNameBeforeLastUnderscore(fileName) {
      const lastUnderscoreIndex = fileName.lastIndexOf("_");
      if (lastUnderscoreIndex === -1) {
        return fileName;
      }
      return fileName.slice(0, lastUnderscoreIndex);
    },
    // 获取设备信息并合并为一条表格消息
    getList() {
      this.loading = true;
      const params = {
        keyword: this.inputMessage,
      };

      getSearchData(params).then((response) => {
        let deviceInfoList = response.data;

        // 确保每个item都有attachment和content字段
        deviceInfoList.forEach(item => {
          if (!item.hasOwnProperty('attachment')) {
            item.attachment = {};
          }
          if (!item.attachment.hasOwnProperty('content')) {
            item.attachment.content = '该文件是空文件';
          }
        });

        this.inputMessage = "";

        // 构造表格数据的消息对象
        const tableMessage = {
          isUser: false,
          isTable: true,
          tableData: this.textLines(deviceInfoList),
          time: new Date().toLocaleTimeString(),
        };
        this.loading = false;

        // 将表格消息添加到消息列表
        this.messages.push(tableMessage);
        this.scrollToBottom();
      }).catch(() => {
        const tableMessage = {
          isUser: false,
          isTable: true,
          tableData: this.textLines([]),
          time: new Date().toLocaleTimeString(),
        };
        this.messages.push(tableMessage);
        this.loading = false;
      });
    },
    textLines(dataArray) {
      if (dataArray == "") {
        return [];
      } else {
        return dataArray.map((item) => {
          if (item.attachment && item.attachment.content) {
            // 替换换行符为<br>标签
            item.attachment.content = item.attachment.content.replace(
              /\r?\n/g,
              "<br>"
            );
          }
          return item;
        });
      }
    },
    // 发送消息
    sendMessage() {
      if (this.inputMessage.trim() !== "") {
        const currentTime = new Date().toLocaleTimeString();

        // 添加用户消息
        this.messages.push({
          text: this.inputMessage,
          isUser: true,
          time: currentTime,
          displayedText: this.inputMessage,
        });

        this.scrollToBottom();

        // 调用getList获取并展示设备信息
        this.getList();
      }
    },
    // 滚动到底部
    scrollToBottom() {
      this.$nextTick(() => {
        const chatBox = this.$refs.chatBox;
        chatBox.scrollTop = chatBox.scrollHeight;
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.chat-container {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
  display: flex;
  flex-direction: column;
  position: relative;
  font-family: Arial, sans-serif;
}

.chat-box {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background-color: #ffffff;
  display: flex;
  flex-direction: column;
  margin-bottom: 100px;
  border-radius: 10px;
}

.chat-message {
  margin-bottom: 20px;
  display: flex;
  max-width: 70%;
  flex-direction: column;
}

.user-message {
  align-self: flex-end;
  flex-direction: column;
}

.incoming-message {
  align-self: flex-start;
}

.avatar-wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: linear-gradient(135deg,
      #f09433,
      #e6683c,
      #dc2743,
      #cc2366,
      #bc1888,
      #e1306c);
  padding: 3px;
  margin-bottom: 5px;
}

.user-avatar {
  align-self: flex-end;
  margin-right: 0;
  margin-top: 5px;
}

.avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background-color: #fff;
}

.message-content {
  background-color: #e0e0e0;
  padding: 12px;
  border-radius: 12px;
  max-width: 100%;
  word-wrap: break-word;
  position: relative;
  margin-top: 5px;
}

.user-message .message-content {
  background-color: #007bff;
  color: white;
}

.message-time {
  font-size: 12px;
  color: #aaa;
  margin-top: 5px;
  text-align: right;
}

.message-table {
  margin-top: 5px;
  background: #fff;
  border: 3px solid #f1efef;
  border-radius: 12px;
  padding: 24px;
  background: #f0f0f0;

  .message-table-box>div {
    background: #fff;
    margin-bottom: 24px;
    padding: 12px 24px;
    overflow: hidden;

    .name {
      margin-bottom: 6px;
      font-size: 18px;
    }

    .link {
      margin-bottom: 10px;
      font-size: 14px;
    }

    .content {
      font-size: 12px;
      color: #868585;
    }
  }
}

.input-box {
  position: fixed;
  bottom: 3%;
  left: 55%;
  transform: translateX(-50%);
  width: 60%;
  display: flex;
  align-items: center;
  padding: 30px;
  height: 100px;
  background-color: #ffffff;
  box-shadow: 0 -2px 15px rgba(0, 0, 0, 0.1);
  border-radius: 30px;
}

input[type="text"] {
  flex: 1;
  padding: 12px;
  font-size: 14px;
  border: none;
  border-radius: 20px;
  margin-right: 10px;
  background-color: #f0f0f0;
}

.send-btn {
  padding: 10px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 15%;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
}

.send-btn:hover {
  background-color: #0056b3;
}

.header {
  display: flex;
  align-items: center;

  .user-name {
    margin-left: 10px;
    font-size: 14px;
    color: #313131;
  }
}

.header-user {
  display: flex;
  align-items: center;

  .user-name {
    margin-left: 10px;
    font-size: 14px;
    color: #313131;
  }
}

.flex-title {
  display: flex;
  justify-content: space-between;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>
