<template>
  <div>
    <!-- v-if="selected" -->
    <div class="chat-wrap">
      <div class="chat-title">
        test
        <!-- {{ selected.name || selected.roomname }} -->
      </div>
      <div class="record-warp">
        <el-scrollbar
          v-if="tab === 'friends'"
          style="height:95%;"
          ref="myScrollbar"
        >
          <div
            class="record-list"
            v-for="(item, i) in friend_record_list"
            :key="i"
          >
            <div
              class="record-item"
              :class="item.id !== self.id ? 'receive-record' : 'send-record'"
            >
              <div>
                <span>{{ item.msg }}</span>
              </div>
              <div>
                <span>{{ item.msg }}</span>
              </div>
              <div>
                <span>{{ item.msg }}</span>
              </div>
            </div>
          </div>
        </el-scrollbar>
        <el-scrollbar
          v-if="tab === 'groups'"
          style="height:95%"
          ref="myScrollbar"
        >
          <div
            class="record-list"
            v-for="(item, i) in room_record_list"
            :key="i"
          >
            <div class="record-item" v-if="item.id !== self.id">
              <div class="avatar">
                <el-avatar
                  shape="square"
                  src="https://img2.baidu.com/it/u=1077360284,2857506492&fm=26&fmt=auto&gp=0.jpg"
                ></el-avatar>
              </div>
              <div class="group-record-item">
                <div class="nickname">
                  {{ item.nickname }}
                </div>
                <!-- <div class="user">5asfdasdf</div> -->
                <!-- <span>{{ item.msg }}</span> -->
                <div class="message-content-text" style="margin-left:2px; margin-top: 0" v-text="_parseText(item.msg)"></div>
              </div>
            </div>
            <div v-if="item.id === self.id" class="record-item send-record">
              <!-- <div class="user">5asfdasdf</div> -->
              <!-- <span>{{ item.msg }}</span> -->
              <!-- 链接 -->
              <!-- <a class="message-content-text" href="https://img2.baidu.com/it/u=1605987499,4009355285&fm=26&fmt=auto&gp=0.jpg" target="_blank">https://img2.baidu.com/it/u=1605987499,4009355285&fm=26&fmt=auto&gp=0.jpg</a> -->
              <!-- 文本 -->
              <!-- <div class="message-content-text" v-text="_parseText(item.msg)"></div> -->
              <!-- 图片 -->
              <!-- <div class="message-content-image" :style="getImageStyle('https://img2.baidu.com/it/u=1605987499,4009355285&fm=26&fmt=auto&gp=0.jpg')">
                <viewer style="display: flex; align-items: center">
                  <img src="https://img2.baidu.com/it/u=1605987499,4009355285&fm=26&fmt=auto&gp=0.jpg" alt="" />
                </viewer>
              </div> -->
              <!-- 视频格式文件 -->
              <div class="message-content-image">
                <video style="width: 255px" src="https://media.w3.org/2010/05/sintel/trailer.mp4" controls="controls">您的浏览器不支持 video 标签。</video>
              </div>
              <!-- <div class="avatar">
                <el-avatar
                  shape="square"
                  src="https://img2.baidu.com/it/u=1077360284,2857506492&fm=26&fmt=auto&gp=0.jpg"
                ></el-avatar>
              </div> -->
            </div>
          </div>
        </el-scrollbar>
      </div>
      <div class="send-msg-wrap">
        <div class="send-header">
          <div class="tools" style="margin:10px">
            <el-upload
              ref="upload"
              class="file-uploader"
              action="/api/upload/"
              :show-file-list="false"
              :on-success="handleSuccess"
              :before-upload="beforeUpload"
              style="display: inline"
            >
              <i
                id="upload-btn"
                class="el-icon-folder-opened"
                @click="upload"
              ></i>
            </el-upload>
            <i class="el-icon-folder-add"></i>
            <i class="el-icon-folder-opened"></i>
          </div>
        </div>
        <div class="input-box">
          <textarea
            v-model="msg"
            placeholder="请输入聊天内容"
            @keyup.enter="sendMsg"
          ></textarea>
          <div class="send-footer">
            <el-button
              type="info"
              plain
              class="send-btn"
              size="small"
              @click="sendMsg"
              >发送</el-button
            >
          </div>
        </div>
      </div>
    </div>
    <div class="chat-wrap" v-if="!selected">
      <el-empty description="请选择聊天对象"></el-empty>
    </div>
  </div>
</template>

<script>
import { addCookie, getCookie } from "@/utils/setCookie.js";
import { isUrl, parseText, processReturn } from "@/utils/common";
export default {
  name: "ChatFrame",
  props: ["selected", "tab"],
  data() {
    return {
      msg: "",
      friend_record: [],
      friend_record_list: [],
      room_record: {},
      room_record_list: [],
      self: null,
      uploadProgress: false
    };
  },
  computed: {},
  watch: {
    selected(n, o) {
      if (this.friend_record[this.selected.id]) {
        this.friend_record_list = this.friend_record[this.selected.id];
      }
      if (this.room_record[this.selected.id]) {
        this.room_record_list = this.room_record[this.selected.id];
      }
      this.$nextTick(() => {
        this.$refs["myScrollbar"].wrap.scrollTop = this.$refs[
          "myScrollbar"
        ].wrap.scrollHeight;
      });
    }
  },
  methods: {
    handleSuccess(res, file) {
      console.log(`res`, res);
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeUpload(file) {
      console.log(`file`, file);
      // const isJPG = file.type === "image/jpeg";
      // const isLt2M = file.size / 1024 / 1024 < 2;

      // if (!isJPG) {
      //   this.$message.error("上传头像图片只能是 JPG 格式!");
      // }
      // if (!isLt2M) {
      //   this.$message.error("上传头像图片大小不能超过 2MB!");
      // }
      // return isJPG && isLt2M;
      this.uploadProgress = true;
      this.fileData = file;
      //  调用函数分割文件 我这里是分割成不超过20M的文件快
      this.fileDataList = this.createFileChunk(file, 1024 * 1024 * 20);
      console.log(`this.fileDataList`, this.fileDataList);
      // return new Promise((reslove, reject)=>{
      //   this.fileUpLoad(reslove, reject);
      // })
      let fd = new FormData();
      fd.append("filename", file);
      // fd.append('project_id', this.project_id)
      // fd.append('version_id', this.version_id)
      console.log(`fd`, fd);
      this.$http.post("/api/upload/", fd).then(
        res => {
          // this.importDataBtnText='导入成功';
          console.log(`res1111`, res);
          console.log("======success====");
        },
        res => {
          console.log("===========shibai====");
          //  this.importDataBtnText='导入失败';
          console.log(res);
        }
      );
      return false;
    },
    submitUpload() {
      this.$refs.upload.submit();
    },

    /**
     * 文本转译/校验
     * @params text
     */
    _parseText(text) {
      return parseText(text);
    },

    /**
     * 是否URL
     * @params text
     */
    _isUrl(text) {
      return isUrl(text);
    },

    // // 初始化上传接口的函数，再上面上传之前调用的
    // fileUpLoad(reslove, reject) {
    //   const paramsData = {
    //     multipartUpload: true, // 是否是文件分步，分块上传
    //     name: this.fileData.name,
    //     size: this.fileData.size,
    //   }
    //   initFileUpload(paramsData).then(res => {
    //     const uploadUrl = res.data.data.uploadUrl
    //     const completeMultipartUrl = res.data.data.completeMultipartUrl
    //     // 文件上传的请求地址
    //      this.uploadUrl = uploadUrl
    //     // 合并文件上传的请求地址
    //     this.completeMultipartUrl = completeMultipartUrl
    //     reslove();
    //   }).catch((err)=>{
    //     reject(err)
    //   })
    // },
    // 文件分割的方法
    createFileChunk(file, size = chunkSize) {
      const fileChunkList = [];
      let count = 0;
      let num = 1;
      while (count < file.size) {
        fileChunkList.push({
          file: file.slice(count, count + size),
          partNumber: num
        });
        count += size;
        num++;
      }
      return fileChunkList;
    },
    /**
   * 根据图片url设置图片框宽高, 注意是图片框
   */
  getImageStyle(src) {
    const arr = src.split('$');
    let width = Number(arr[2]);
    let height = Number(arr[3]);
    if (this.mobile) {
      // 如果是移动端,图片最大宽度138, 返回值加12是因为设置的是图片框的宽高要加入padding值
      if (width > 138) {
        height = (height * 138) / width;
        width = 138;
        return {
          width: `${width + 12}px`,
          height: `${height + 12}px`,
        };
      }
    }
    return {
      width: `${width + 12}px`,
      height: `${height + 12}px`,
    };
  },

    upload() {},

    sendMsg(e) {
      if (e.which === 13) {
        console.log(`e.which`, e.which);
        e.cancelBubble = true;
        e.preventDefault();
        e.stopPropagation();
      }

      if (this.msg.trim() === "") {
        this.msg = "";
        return;
      }
      if (!this.self) {
        this.self = JSON.parse(localStorage.getItem("self"));
      }
      console.log(`this.self`, this.self);
      const msgInfo = {
        id: this.$socket.id,
        msg: this.msg,
        nickname: this.self.nickname
      };
      this.msg = ""; // 输入enter后置空
      if (this.tab === "friends") {
        msgInfo.toid = this.selected.id;
        this.$socket.emit("private message", this.selected.id, msgInfo);
        if (this.friend_record[this.selected.id]) {
          this.friend_record[this.selected.id].push(msgInfo);
          this.friend_record_list = this.friend_record[this.selected.id];
        } else {
          this.friend_record[this.selected.id] = [];
          this.friend_record[this.selected.id].push(msgInfo);
          this.friend_record_list = this.friend_record[this.selected.id];
        }
        addCookie("friend_record", JSON.stringify(this.friend_record));
      } else {
        msgInfo.roomid = this.selected.id;
        this.$socket.emit("chat-room", this.selected.id, msgInfo);
        if (this.room_record[this.selected.id]) {
          this.room_record[this.selected.id].push(msgInfo);
          this.room_record_list = this.room_record[this.selected.id];
        } else {
          this.room_record[this.selected.id] = [];
          this.room_record[this.selected.id].push(msgInfo);
          this.room_record_list = this.room_record[this.selected.id];
        }
        addCookie("room_record", JSON.stringify(this.room_record));
      }
      this.$nextTick(() => {
        // 滚动到底部
        this.$refs["myScrollbar"].wrap.scrollTop = this.$refs[
          "myScrollbar"
        ].wrap.scrollHeight;
      });
    },

    closeScoket() {
      // 断开连接
      this.$socket.close();
    }
  },
  created() {
    const self_str = localStorage.getItem("self");
    const room_record_str = getCookie("room_record");
    const friend_record_str = getCookie("friend_record");
    if (self_str) {
      this.self = JSON.parse(self_str);
    }
    if (room_record_str) {
      this.room_record = JSON.parse(room_record_str);
    }
    if (friend_record_str) {
      this.friend_record = JSON.parse(friend_record_str);
    }
  },
  // mounted() {
  //   if (this.friend_record[this.selected.id]) {
  //     this.friend_record_list = this.friend_record[this.selected.id]
  //   }
  //   if (this.room_record[this.selected.id]) {
  //     this.room_record_list = this.room_record[this.selected.id]
  //   }
  // },
  sockets: {
    connect() {
      console.log("===连接成功=========");
    },
    // 发送消息
    toServer(data) {
      this.$socket.emit("toServer", data);
    },
    // 接收消息
    toClient(data) {
      console.log(`toclient data`, data);
    },
    // 断开链接回调
    disconnect() {
      console.log("disconnect：", "已经断开 socket 链接");
    },
    // 重新连接
    reconnect() {
      // 自动执行，直到链接成功
      this.$socket.emit("connect");
    },
    receiveMsg(data) {
      console.log(`receiveMsg`, data);
    },
    chat(data) {
      console.log(`private message=================`, data);
      if (this.friend_record[data.toid]) {
        this.friend_record[data.toid].push(data);
      } else {
        this.friend_record[data.toid] = [];
        this.friend_record[data.toid].push(data);
      }
      if (this.friend_record[this.selected.id]) {
        this.friend_record_list = this.friend_record[this.selected.id];
        this.$nextTick(() => {
          this.$refs["myScrollbar"].wrap.scrollTop = this.$refs[
            "myScrollbar"
          ].wrap.scrollHeight;
        });
      }
      addCookie("room_record", JSON.stringify(this.room_record));
    },
    room_msg(data) {
      console.log("======room msg===");
      console.log(`data`, data);
      if (this.room_record[data.roomid]) {
        this.room_record[data.roomid].push(data);
      } else {
        this.room_record[data.roomid] = [];
        this.room_record[data.roomid].push(data);
      }
      if (this.room_record[this.selected.id]) {
        this.room_record_list = this.room_record[this.selected.id];
        this.$nextTick(() => {
          this.$refs["myScrollbar"].wrap.scrollTop = this.$refs[
            "myScrollbar"
          ].wrap.scrollHeight;
        });
      }
      addCookie("room_record", JSON.stringify(this.room_record));
    },
    user_list(userlist) {
      console.log(`this.self`, this.self);
      console.log(`userlist`, userlist);
    },
    quit(data) {
      console.log(`quit == quit`, data);
    }
  }
};
</script>

<style scoped>
.chat-wrap {
  height: 90vh;
  border: 1px solid #ddd;
  border-radius: 2px;
}
.chat-title {
  padding: 20px;
  font-weight: 600;
}
.record-warp {
  padding: 10px;
  height: 63vh;
  background: rgb(245, 245, 245);
}
/* .record-list {
} */
.record-item {
  display: flex;
  padding: 15px 5px;
  margin: 5px;
}
.avatar {
  margin: 10px 5px;
}
.record-item > span {
  padding: 8px 12px;
  border-radius: 5px;
}
.nickname {
  padding: 4px;
  margin-bottom: 2px;
  font-size: 14px;
  color: gray;
}
.group-record-item > span {
  padding: 8px 12px;
  border-radius: 5px;
  background-color: rgb(199, 206, 200);
}
.send-record {
  position: relative;
  justify-content: flex-end;
}
.receive-record {
  width: 60%;
  justify-content: flex-start;
}
.send-record > span {
  display: inline-block;
  text-align: right;
}
.message-content-text,
.message-content-image {
  max-width: 600px;
  display: inline-block;
  margin-left: 35px;
  overflow: hidden;
  margin-top: 4px;
  padding: 6px;
  background: rgb(117, 197, 128);
  font-size: 16px;
  border-radius: 5px;
  text-align: left;
  word-break: break-word;
}
.message-content-image {
  max-height: 255px;
  max-width: 255px;
  background: rgb(204, 197, 197);
}
.message-content-image img {
  cursor: pointer;
  max-width: 225px;
  max-height: 225px;
}
.receive-record > span {
  text-align: left;
  background: rgb(199, 206, 200);
}
.input-box {
  overflow: hidden;
}
.input-box > textarea {
  /* display: block; */
  padding: 5px 0;
  resize: none;
  margin-left: 10px;
  width: 98%;
  height: 50px;
  outline: none;
  border: none;
  font-size: 17px;
}
.send-footer {
  padding: 10px;
  text-align: right;
}
</style>
