<template>
  <div class="app-container" style="background-color: #e6e6e6">
    <el-row :gutter="20">
      <el-col :span="6">
        <div class="box_l">
          <div
            class="user_item"
            v-for="item in userList"
            :key="item.id"
            @click="active(item)"
            :class="activeId === item.id ? 'active' : ''"
          >
            <div class="user_item_l">
              <div class="el-avatar">
                <img :src="item.icon" alt="" />
              </div>
              <div class="info">
                <div class="phone">
                  {{ item.username
                  }}<el-tag
                    style="margin-left: 15px"
                    size="mini"
                    v-if="item.msgNoReadCount != 0"
                    >{{ item.msgNoReadCount }}条未读</el-tag
                  >
                </div>
                <div class="company">
                  <!-- {{ numTop }} -->
                </div>
              </div>
            </div>
            <!-- <div class="user_item_r">14:19</div> -->
          </div>
        </div>
      </el-col>
      <el-col :span="18">
        <div class="box_r">
          <div class="box" v-if="!activeId">
            <div class="famous-box">
              <img src="~@/assets/image/chat.png" width="300" />
              <p>
                不是井里没有水，而是你挖的不够深<br />
                不是成功来得慢，而是你努力的不够多<br />
                加油吧！ ......
              </p>
            </div>
          </div>
          <div class="box" v-else>
            <div id="content" class="content" @scroll="scroll">
              <div v-loading="loading">
                <div v-for="(item, index) in info" :key="index">
                  <div
                    class="info_r info_default"
                    v-if="item.type == 'leftinfo'"
                  >
                    <span class="circle circle_r el-avatar">
                      <img :src="icon" alt="" />
                    </span>
                    <div class="con_r con_text">
                      <div>{{ item.sendText }}</div>
                      <!-- <div v-for="(item2, index) in item.question" :key="index">
                      <div class="con_que">
                        <div class="czkj-question-msg">
                          {{ item2.index }}
                          {{ item2.sendText }}
                        </div>
                      </div>
                    </div> -->
                    </div>
                    <div class="time_r">{{ item.msgTime }}</div>
                  </div>

                  <div class="info_l" v-if="item.type == 'rightinfo'">
                    <div class="con_r con_text">
                      <span class="con_l">{{ item.sendText }}</span>
                      <!-- <span class="circle circle_l el-avatar">
                      <img :src="avatar" alt="" />
                    </span> -->
                    </div>
                    <div class="time_l">{{ item.msgTime }}</div>
                  </div>
                </div>
              </div>
            </div>

            <div class="setproblem">
              <textarea
                placeholder="请输入"
                style="
                  height: 100%;
                  width: 100%;
                  resize: none;
                  padding-right: 125px;
                  outline: none;
                  border-color: #ccc;
                  border-radius: 5px;
                  background-color: #f1f3f5;
                "
                id="text"
                v-model="customerText"
                @keyup.enter="sentMsg"
              ></textarea>
              <button @click="sentMsg" class="setproblems">
                <span style="vertical-align: 4px">发 送</span>
              </button>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { mapGetters } from 'vuex';
import store from '@/store';
import { getUsers, readMsg, getChatRecords, sendMsg } from '@/api/service';
export default {
  data() {
    return {
      numTop: null,
      query: {
        pageNum: 1,
        pageSize: 10
      },
      userTotal: 0,
      queryParams: {
        userId: null,
        pageNum: 1,
        pageSize: 10
      },
      msgTotal: 0,
      loading: false,
      info: [],
      icon: '', // 用户头像
      userList: [],
      activeId: '', // 当前用户ID
      customerText: '',
      path: 'ws://121.5.136.69:1919/webStock/' + this.$store.state.user.userId,
      // path: 'ws://192.168.0.125:1919/webStock/' + this.$store.state.user.userId,
      socket: ''
    };
  },
  watch: {
    activeId(newVal, oldVal) {
      this.queryParams.pageNum = 1;
      if (newVal == '' || newVal == null) return;
      const info = this.userList.find(item => {
        return item.id == newVal;
      });
      if (info.msgNoReadCount != 0) {
        // 消息改为已读
        readMsg({ userId: newVal }).then(res => {
          info.msgNoReadCount = 0;
        });
      }
      this.queryParams.userId = newVal;
      this.getMsgList();
    }
  },
  computed: {
    ...mapGetters(['avatar'])
  },
  mounted() {
    // 初始化
    this.init();
    // getUsers(this.queryParams).then(({data})=>{
    //   this.userList = data.list
    //   this.total = data.total
    // })
  },
  created() {
    this.getUserList();
  },
  methods: {
    scroll(e) {
      // console.log(e.srcElement.scrollTop);
      this.numTop = e.srcElement.scrollTop;
      if (e.srcElement.scrollTop == 0) {
        if (
          this.queryParams.pageNum * this.queryParams.pageSize >=
          this.msgTotal
        )
          return this.msgInfo('已经到顶了');
        this.queryParams.pageNum++;
        this.getMsgList();
      }
    },
    // 获取和某个好友的聊天记录
    getMsgList() {
      // let loading;
      // if (this.queryParams.pageNum != 1) {
      //   loading = this.$loading({
      //     lock: true,
      //     text: 'Loading',
      //     spinner: 'el-icon-loading',
      //     background: 'rgba(0, 0, 0, 0.7)'
      //   });
      // }

      // this.loading = true; 会引起右边内容隐藏
      getChatRecords(this.queryParams).then(({ data }) => {
        // 时间转时间戳
        data.list.map(item => {
          item.sendTime = new Date(item.sendTime).getTime();
        });
        // 时间戳排序
        data.list.sort(function(a, b) {
          return a.sendTime > b.sendTime ? 1 : -1;
        });
        console.log(data.list);
        this.info = [...data.list, ...this.info];
        this.msgTotal = data.total;
        // this.loading = false;
        // if (this.queryParams.pageNum != 1) {
        //   loading.close();
        // }

        if (this.queryParams.pageNum == 1) {
          // 消息到底
          this.$nextTick(() => {
            var contentHeight = document.getElementById('content');
            console.log(contentHeight.scrollHeight);
            contentHeight.scrollTop = contentHeight.scrollHeight;
          });
        }
      });
    },
    // 获取用户列表
    getUserList() {
      getUsers(this.query).then(({ data }) => {
        this.userList = data.list;
        this.userTotal = data.total;
      });
      setTimeout(() => {
        this.getUserList();
      }, 300000);
    },
    // 用户发送消息
    sentMsg() {
      let text = this.customerText.trim();
      if (text != '') {
        var obj = {
          msgTime: this.getTodayTime(),
          type: 'rightinfo',
          sendText: text,
          receiverUserId: this.activeId
        };
        sendMsg(obj).then(res => {
          this.info.push(obj);
          this.customerText = '';
          this.$nextTick(() => {
            var contentHeight = document.getElementById('content');
            console.log(contentHeight.scrollHeight);
            contentHeight.scrollTop = contentHeight.scrollHeight;
          });
        });
      }
    },
    getTodayTime() {
      // 获取当前时间
      var day = new Date();
      let seconds = day.getSeconds();
      if (seconds < 10) {
        seconds = '0' + seconds;
      } else {
        seconds = seconds;
      }
      let minutes = day.getMinutes();
      if (minutes < 10) {
        minutes = '0' + minutes;
      } else {
        minutes = minutes;
      }
      let time =
        day.getFullYear() +
        '-' +
        (day.getMonth() + 1) +
        '-' +
        day.getDate() +
        ' ' +
        day.getHours() +
        ':' +
        minutes +
        ':' +
        seconds;
      return time;
    },
    active(item) {
      console.log(item);
      store.commit('SET_REDNUM', 0); // 点击后把当前用户的未读数传过去减掉
      this.customerText = '';
      this.activeId = item.id;
      this.info = [];
      this.icon = item.icon;
    },
    init: function() {
      if (typeof WebSocket === 'undefined') {
        alert('您的浏览器不支持socket');
      } else {
        // 实例化socket
        this.socket = new WebSocket(this.path);
        console.log(this.socket);
        // 监听socket连接
        this.socket.onopen = this.open;
        // 监听socket错误信息
        this.socket.onerror = this.error;
        // 监听socket消息
        this.socket.onmessage = this.getMessage;
      }
    },
    open: function() {
      console.log('socket连接成功');
    },
    error: function() {
      console.log('连接错误');
    },
    msgTips() {
      let that = this;
      if (!('Notification' in window)) {
        console.log('浏览器不支持消息通知');
        return;
      }
      Notification.requestPermission(function(permission) {
        //如果不是当前页面，标题栏闪动+消息提示
        if (document.hidden) {
          var options = {
            body: '您有新的未读消息，请及时处理',
            silent: true
          };
          var notification = new Notification('消息通知', options);
          notification.onclick = function() {
            window.open(`/service`, '_blank');
          };
          //标题栏闪动
          var defaultTitle = document.title;
          if (that.isReceive) {
            return;
          } else {
            that.isReceive = true;
          }
          that.timer = setInterval(function() {
            var title = document.title;
            if (document.hidden && that.isReceive) {
              if (/你有新消息/.test(title) == false) {
                document.title = '【你有新消息】';
              } else {
                document.title = defaultTitle;
              }
            } else {
              that.isReceive = false;
              document.title = defaultTitle;
            }
          }, 500);
        }
      });
    },
    getMessage(msg) {
      const data = JSON.parse(msg.data);
      console.log(JSON.parse(msg.data));
      const msgInfo = JSON.parse(msg.data);
      this.msgTips();
      // 遍历用户列表  新消息的用户未读数量加加
      if (msgInfo.sendUserId === this.activeId) {
        this.info.push(msgInfo);
        // 消息已读
        readMsg({ userId: msgInfo.sendUserId }).then(res => {
          const info = this.userList.find(item => {
            return item.id == msgInfo.sendUserId;
          });
          info.msgNoReadCount = 0;
        });
      }
      // else if(){

      // }
      else {
        const userInfo = this.userList.find(item => {
          return item.id == data.sendUserId;
        });
        userInfo.msgNoReadCount++;
      }
    },
    send: function(params) {
      this.socket.send(params);
    },
    close: function() {
      console.log('socket已经关闭');
    }
  },
  destroyed() {
    console.log('out');
    // 销毁监听
    this.socket.onclose = this.close;
  }
};
</script>

<style lang="scss" scoped>
.app-container {
  height: calc(100vh - 84px);
  overflow: auto;
  .el-row {
    height: 100%;
    .el-col {
      height: 100%;
      overflow: auto;
      .box_l {
        // background-color: #cad5db;
        background-color: rgba(255, 255, 255, 0.2);
        padding: 10px;
        min-height: 100%;
        .user_item {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 10px 10px;
          // border-bottom: 1px solid #ccc;
          .user_item_l {
            display: flex;
            align-items: center;
            .el-avatar {
              position: relative;
              background: unset;
              img {
                width: 40px;
                height: 40px;
                border-radius: 50%;
              }
            }
            .info {
              display: flex;
              flex-direction: column;
              justify-content: space-around;
              height: 40px;
              margin-left: 10px;
              .phone {
              }
              .company {
                font-size: 12px;
              }
            }
          }
          .user_item_r {
            font-size: 12px;
          }
        }
      }
      .box_r {
        height: 100%;
        .box {
          width: 100%;
          /* width: 680px; */
          // height: 500px;
          height: 100%;
          background-color: #f8f9fb;
          position: relative;
          padding: 1.25rem;
          #content {
            height: 80%;
            overflow-y: scroll;
            font-size: 14px;
            width: 100%;
            .circle {
              display: inline-block;
              width: 34px;
              height: 34px;
              border-radius: 50%;
              background-color: #eff1f3;
            }
            .con_text {
              color: #333;
              margin-bottom: 5px;
            }
            .con_que {
              color: #1c88ff;
              height: 30px;
              line-height: 30px;
              cursor: pointer;
            }
            .info_r {
              margin: 40px 0;
              position: relative;
              .circle_r {
                position: absolute;
                left: 0%;
              }
              .pic_r {
                width: 17px;
                height: 17px;
                margin: 8px;
              }
              .con_r {
                display: inline-block;
                /* max-width: 253px; */
                min-width: 220px;
                max-width: 55%;
                min-height: 50px;
                line-height: 50px;
                /* min-height: 20px; */
                color: #fff;
                background-color: #1890ff;
                border-radius: 6px;
                padding: 0 10px;
                margin-left: 40px;
              }
              .time_r {
                margin-left: 45px;
                color: #999999;
                font-size: 12px;
              }
            }
            .info_l {
              text-align: right;
              margin: 40px 20px;
              // margin-top: 10px;

              // .circle_l {
              //   // vertical-align: -10px;
              // }
              .pic_l {
                width: 13px;
                height: 17px;
                margin: 8px 10px;
              }
              .time_l {
                margin-right: 45px;
                color: #999999;
                font-size: 12px;
                margin-top: 5px;
              }
              .con_l {
                display: inline-block;
                min-width: 220px;
                max-width: 55%;
                min-height: 51px;
                line-height: 51px;
                background-color: #1890ff;
                border-radius: 6px;
                padding: 0 10px;
                text-align: left;
                color: #fff;
                margin-right: 5px;
              }
            }
            #question {
              cursor: pointer;
            }
          }
        }
        .setproblem {
          margin-top: 30px;
          width: 100%;
          height: 17%;
          background-color: #ffffff;
          position: relative;
        }
        .setproblem textarea {
          color: #999999;
          padding: 10px;
          box-sizing: border-box;
        }
        .setproblem button {
          width: 5.875rem;
          height: 2.5rem;
          line-height: 2.5rem;
          background: #1890ff;
          opacity: 1;
          border-radius: 4px;
          font-size: 10px;
          color: #ffffff;
          position: absolute;
          right: 2%;
          top: 50%;
          cursor: pointer;
          border: none;
        }
        // display: flex;
        // flex-direction: column;
        // justify-content: space-between;
        // background-color: #fff;
        // padding: 10px 20px;
        // min-height: 100%;
        // .content {
        //   flex: 1;
        // }
        // .dialogue {
        //   height: 150px;
        //   .el-input {
        //     height: 100%;
        //     /deep/.el-input--medium .el-input__inner {
        //       height: 100%;
        //     }
        //   }
        // }
      }
    }
  }
}
.active {
  background-color: paleturquoise;
  background-color: #c5c4c4;
  color: #fff;
}
.famous-box {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  height: 100%;
  font-size: 24px;
  p {
    width: 100%;
    font-weight: 300;
    text-align: center;
    font-size: 15px;
    color: #b9b4b4;
    margin-top: -30px;
  }
}
</style>
