<template>
  <div id="index">
    <el-input v-model="customer_id" placeholder=""></el-input>
    <el-input v-model="customer_name" placeholder=""></el-input>
    <el-button type="primary" @click="toChannel()">连接</el-button>
    <el-row>
      <el-col :span="24" class="main">
        <el-col :span="4" class="left">
          <el-col :span="24" class="left_1">
            <el-input placeholder="请输入查询内容" v-model="searchName" class="input-with-select">
              <el-button slot="append" icon="el-icon-search" @click="search"></el-button>
            </el-input>
          </el-col>
          <el-col :span="24" class="left_2">
            <el-col
              :span="24"
              class="list"
              :class="`${index === activeIndex ? 'active' : ''}`"
              v-for="(item, index) in userList"
              :key="index"
              @click.native="chatBtn(item, index)"
            >
              <el-col :span="4" class="icon">
                <el-image :src="leftIcon"></el-image>
              </el-col>
              <el-col :span="20" class="info">
                <el-col :span="24" class="name textOver">
                  {{ item.client_name }}
                </el-col>
                <el-col :span="24" class="date textOver">
                  {{ getTime(item) }}
                </el-col>
              </el-col>
            </el-col>
          </el-col>
        </el-col>
        <el-col :span="20" class="right">
          <el-col :span="24" class="right_1">
            <el-col :span="1" class="icon">
              <el-image :src="leftIcon"></el-image>
            </el-col>
            <el-col :span="23" class="info">
              <el-col :span="24" class="name">
                {{ chatUserInfo.client_name }}
              </el-col>
              <el-col :span="24" class="date textOver">
                {{ getTime(chatUserInfo) }}
              </el-col>
            </el-col>
          </el-col>
          <el-col :span="24" class="right_2">
            <el-col :span="24" class="list" v-for="(item, index) in chatList" :key="index">
              <template v-if="isSender(item, index)">
                <el-col :span="24" class="list_left">
                  <el-col :span="1" class="icon">
                    <el-image :src="leftIcon"></el-image>
                  </el-col>
                  <el-col :span="23" class="info">
                    <el-col :span="24" class="name">{{ item.sender_name }}[{{ getTime(item) }}]</el-col>
                    <el-col :span="24" class="list_leftCont">
                      {{ item.content }}
                    </el-col>
                  </el-col>
                </el-col>
              </template>
              <template v-else>
                <el-col :span="24" class="list_left list_right">
                  <el-col :span="23" class="info">
                    <el-col :span="24" class="name">[{{ getTime(item) }}]{{ item.sender_name }}</el-col>
                    <el-col :span="24" class="list_leftCont">
                      {{ item.content }}
                    </el-col>
                  </el-col>
                  <el-col :span="1" class="icon">
                    <el-image :src="rightIcon"></el-image>
                  </el-col>
                </el-col>
              </template>
            </el-col>
          </el-col>
          <el-col :span="24" class="right_3">
            <el-col :span="24" class="right_3cont">
              <el-input type="textarea" placeholder="请输入内容" :autosize="{ minRows: 3, maxRows: 5 }" v-model="content"> </el-input>
            </el-col>
            <el-col :span="24" class="btn">
              <el-button type="primary" @click="send">发送</el-button>
            </el-col>
          </el-col>
        </el-col>
      </el-col>
    </el-row>
  </div>
</template>

<script>
const _ = require('lodash');
const moment = require('moment');
import { mapState, createNamespacedHelpers } from 'vuex';
const { mapActions: customer } = createNamespacedHelpers('customer');
export default {
  name: 'index',
  props: {},
  components: {},
  data: function() {
    return {
      // 查询好友
      searchName: '',
      // 客服头像
      leftIcon: require('@a/rightIcon.png'),
      // 用户头像
      rightIcon: require('@a/leftIcon.png'),
      // 用户列表
      activeIndex: '',
      userList: [],
      // 聊天列表
      chatUserInfo: {},
      chatList: [],
      content: '',
      customer_id: '5f6ad08fbe2d3b407b41a693',
      customer_name: '客服1',
    };
  },
  created() {
    // this.toOnline();
    this.getClientList();
  },
  mounted() {
    // this.channel();
  },
  methods: {
    ...customer(['online', 'record', 'createChat', 'chatRecord']),
    search() {},
    // 点击获取客户聊天列表
    async chatBtn(data, index) {
      this.$set(this, `activeIndex`, index);
      this.$set(this, `chatUserInfo`, data);
      let arr = await this.chatRecord({ client_id: data.client_id, customer_id: data.customer_id });
      if (this.$checkRes(arr)) {
        this.$set(this, `chatList`, arr.data);
        this.scrollToBottom();
      }
      this.chatChannel();
    },
    // 区分发言人
    isSender(data) {
      return data.sender_id != this.user.id;
    },
    // 查询客服列表
    channel() {
      this.$stomp({
        [`/exchange/${this._tenant}/customer.${this.user.id}`]: this.onMessage,
      });
    },
    onMessage(message) {
      // customer/5f6ad08fbe2d3b407b41a693
      console.log('receive a message: ', message.body);
      if (message.body === 'research') this.getClientList();
    },
    async getClientList() {
      const res = await this.record({ _tenant: this._tenant, customer_id: this.user.id });
      if (this.$checkRes(res)) {
        this.$set(this, `userList`, res.data);
      }
    },
    async toOnline() {
      console.log('in function:');
      const time = 5000; //1min 600000
      setInterval(() => {
        this.online({ _tenant: this._tenant, customer_id: this.customer_id, customer_name: this.customer_name });
      }, time);
    },
    getTime(item) {
      const ct = _.get(item.meta, 'createdAt');
      if (!ct) return moment().format('YYYY-MM-DD HH:mm:ss');
      return moment(ct).format('YYYY-MM-DD HH:mm:ss');
    },
    // 发言
    async send() {
      if (!this.content) {
        this.$message({
          message: '发言内容不能为空',
          type: 'warning',
        });
      } else {
        console.log(this.chatUserInfo);
        let data = {
          _tenant: this._tenant,
          client_id: this.chatUserInfo.client_id,
          customer_id: this.chatUserInfo.customer_id,
          sender_id: this.chatUserInfo.customer_id,
          sender_name: this.user.name,
          content: this.content,
        };
        let res = await this.createChat(data);
        if (this.$checkRes(res)) {
          this.$message({
            message: '消息发送成功',
            type: 'success',
          });
          this.content = '';
        }
      }
    },
    chatChannel() {
      this.$stomp({
        [`/exchange/${this._tenant}/customer.${this.chatUserInfo.client_id}.${this.chatUserInfo.customer_id}`]: this.chatMessage,
      });
    },
    chatMessage(message) {
      let body = _.get(message, 'body');
      if (body) {
        body = JSON.parse(body);
        this.chatList.push(body);
        this.scrollToBottom();
      }
    },
    scrollToBottom: function() {
      this.$nextTick(() => {
        var container = this.$el.querySelector('.right_2');
        container.scrollTop = container.scrollHeight;
      });
    },
    toChannel() {
      this.toOnline();
      this.$stomp({
        [`/exchange/${this._tenant}/customer.${this.customer_id}`]: this.onMessage,
      });
    },
  },
  computed: {
    ...mapState(['user', '_tenant']),
  },
  metaInfo() {
    return { title: this.$route.meta.title };
  },
  watch: {
    test: {
      deep: true,
      immediate: true,
      handler(val) {},
    },
  },
};
</script>

<style lang="less" scoped>
.main {
  border: 1px solid #cccccc;
  .left {
    border-right: 1px solid #cccccc;
    .left_1 {
      height: 40px;
      overflow: hidden;
      /deep/.el-input--small .el-input__inner {
        height: 40px;
        line-height: 40px;
      }
    }
    .left_2 {
      height: 700px;
      overflow-x: hidden;
      overflow-y: auto;
      .list {
        border-bottom: 1px dashed #cccccc;
        padding: 8px 5px;
        .icon {
          text-align: center;
          .el-image {
            /deep/.el-image__inner {
              width: 40px;
              height: 40px;
              border-radius: 90px;
            }
          }
        }
        .info {
          .name {
            font-size: 14px;
            font-weight: bold;
            color: #000;
            margin: 0 0 5px 0;
          }
          .date {
            font-size: 12px;
            color: #666;
          }
        }
      }
      .list:hover {
        cursor: pointer;
        background-color: #f9f9f9;
        .info {
          .name {
            color: #409eff;
          }
        }
      }
      .active {
        background-color: #f9f9f9;
        .info {
          .name {
            color: #409eff;
          }
        }
      }
    }
  }
  .right {
    height: 740px;
    overflow: hidden;
    .right_1 {
      height: 40px;
      overflow: hidden;
      background-color: #000;
      .icon {
        text-align: center;
        height: 40px;
        padding: 5px 0;
        .el-image {
          /deep/.el-image__inner {
            width: 30px;
            height: 30px;
            border-radius: 90px;
          }
        }
      }
      .info {
        color: #ffffff;
        .name {
          margin: 2px 0;
          font-size: 14px;
          font-weight: bold;
        }
        .date {
          font-size: 12px;
          color: #ccc;
        }
      }
    }
    .right_2 {
      height: 600px;
      overflow-x: hidden;
      overflow-y: auto;
      background-color: #f7f7f7;
      .list {
        padding: 5px;
        margin: 0 0 10px 0;
        .list_left {
          .icon {
            text-align: center;
            .el-image {
              /deep/.el-image__inner {
                width: 40px;
                height: 40px;
                border-radius: 90px;
              }
            }
          }
          .info {
            .name {
              font-size: 12px;
              margin: 0 0 5px 0;
            }
            .list_leftCont {
              background-color: #ffffff;
              border-radius: 5px;
              padding: 5px;
              font-size: 15px;
              color: #000000;
              line-height: 25px;
              overflow-y: unset;
            }
          }
        }
        .list_right {
          text-align: right;
          .info {
            .list_leftCont {
              background-color: #409eff;
              color: #ffffff;
            }
          }
        }
      }
    }
    .right_3 {
      height: 100px;
      border-top: 1px solid #cccccc;
      .btn {
        text-align: right;
      }
    }
  }
}
</style>
