<!-- 聊天室 -->
<template>
    <div class="ky-chat-main">
        <div class="top-bar" v-if="chatListShow">
            <img class="logo" src="../../assets/kayi-logo-white.png"/>
            <div class="img-text">
                <img class="my-avatar" :src="mySelfData.user && mySelfData.user.avatarImageUrl ? mySelfData.user.avatarImageUrl :require('../../../static/avatar.jpg')"/>
                <span>{{mySelfData.user && mySelfData.user.userName}}</span>
            </div>
        </div>
        <div class="chat-main" :style="!chatListShow ? 'height:100%':''">
        <chatList v-show="chatListShow" ref="chatList" :allUserGroups="allUserGroups"  :clickItem.sync="clickItem" :myUserId="myUserId" :pageType="pageType" @chatClick="chatClick" @changeGroupSetting="changeGroupSetting" @changeGroupDelete="changeGroupDelete" @addGroup="addVisible = true" @createGroup="createGroup('create')"></chatList>
        <div v-if="contentShow"  class="right-main flex">
            <div class="right-content">
                <div id="back-to-list" class="el-icon-arrow-left more-icon-3 cursor hide" @click="backToList"></div>
                <chatContent ref="chatContent" :clickItem.sync="clickItem" :pageType="pageType" :myUserId="myUserId" @settingClick="settingClick"></chatContent>
                <input-send ref="inputSend" :clickItem="clickItem" @sendMsgServer="sendMsgServer" @historyClick="historyClick"></input-send>
            </div>
            <history ref="history" v-show="historyShow" :myUserId="myUserId" :clickItem="clickItem" :historyShow.sync="historyShow"></history>
            <setting ref="setting" v-show="settingShow" :myUserId="myUserId" :clickItem="clickItem" :settingShow.sync="settingShow" @addPeopleGroup="addPeopleGroup"></setting>
        </div>
        <Welcome v-else class="welcome"></Welcome>
        <addGroup ref="addGroup" :addVisible.sync="addVisible" :myUserId="myUserId"></addGroup>
        <CreateGroup :createVisible.sync="createVisible" :myUserId="myUserId" :allUsers="allUserGroups.allUsers" :createParams="createParams" :clickItem="clickItem" :pageType="pageType" :peopleModalType="peopleModalType" :groupPeopleData="groupPeopleData"></CreateGroup>
        </div>
        <loading v-if="loadingShow"></loading>
    </div>
</template>

<script>
import chatList from './chat-list.vue'
import chatContent from './chat-content.vue'
import Welcome from './welcome.vue'
import InputSend from './input-send.vue'
import history from './history.vue'
import setting from './setting.vue'
import addGroup from './addGroup.vue'
import CreateGroup from './createGroup.vue'
import {batchUserData, isExistGroup, joinGroup} from '../../api/api.js'
import loading from './loading.vue'
const signalR = require('@aspnet/signalr')
const Notify = require('notifyjs')// 不是我想要的那个notify,再看看吧
const {API_ROOT} = require('../../../static/config.js')

export default {
  name: 'kyChat',
  mixins: [],
  components: { chatList, chatContent, Welcome, InputSend, history, setting, addGroup, CreateGroup, loading },
  props: {
    loginParams: {
      Object,
      default: () => {}
    }
  },
  data () {
    return {
      allUserGroups: {},
      myUserId: '',
      connection: null,
      clickItem: {},
      pageType: '1',
      contentShow: false,
      chatListShow: true,
      historyShow: false,
      settingShow: false,
      addVisible: false,
      createVisible: false,
      createId: '', // 父页面传来的创建房间的id
      peopleModalType: '',
      groupPeopleData: [], // 当前组的成员数据
      createParams: {}, // 创建ris群组的参数
      pageSize: 'large', // 页面大小
      mySelfData: {},
      loadingShow: true
    }
  },
  watch: {
    loginParams: {
      handler (val) {
        if (val.id && val.pageType) {
          this.myUserId = val.id
          this.pageType = val.pageType
          if (val.userName || val.dep) { // 带了名字或者部门就走用户同步接口后登录否则直接登录
            let params = {
              id: val.id,
              userName: val.userName,
              dep: val.dep
            }
            this.checkUserAndLogin(params)// 同步用户数据后登录
          } else {
            this.login(this.myUserId)
          }
        }
      },
      immediate: true
    }
  },
  computed: {},
  created () {
    window.onresize = this.$chatUtils.debounce(this.windowResize, 50)
    this.windowResize()
    // this.initNotify()
    this.getParentMessage()
  },
  mounted () {},
  methods: {
    login (userId) {
      // eslint-disable-next-line no-undef
      this.connection = new signalR.HubConnectionBuilder().withUrl(API_ROOT + '/hubs/chathub', { accessTokenFactory: () => userId }).build()
      this.connection.serverTimeoutInMilliseconds = 60 * 4 * 1000
      this.connection.keepAliveIntervalInMilliseconds = 60 * 2 * 1000

      this.connection.start().then(() => {
        this.loadingShow = false
      }).catch((err) => {
        return console.error(err.toString())
      })
      // 报错返回的消息
      this.connection.on('selfMsg', (message) => {
        // ws的报错信息会在这里显示
        this.$message.error(message)
        if (message === '您的账号在其他终端上登录') {
          // eslint-disable-next-line no-undef
          this.$alert(`您的账号于${this.$dayjs().format('YYYY-MM-DD HH:mm')}在另一终端登录,已被迫下线`, '提示', {
            confirmButtonText: '重新登录',
            showClose: false,
            callback: action => {
              this.login(userId)
            }
          })
        }
      })
      // 接收数据
      this.connection.on('receive', (message) => {
        console.log('message', message)
        if (message.sendUser.id === this.myUserId || (message.chatReceiveType === 0 && message.sendUser.id === this.clickItem.id) || (message.chatReceiveType === 1 && message.groupId === this.clickItem.id)) {
          this.$refs.chatContent.setChatListFunc(message, true)
          if (message.chatReceiveType === 0) {
            let id = message.groupId// 接收方id
            if (id === this.myUserId) { // 如果接收方是自己，就拿发送方的id
              id = message.sendUser.id
            }
            this.$refs.chatList.updateLastMsg('user', id, message)// 更新左侧列表显示的最新消息
            this.$refs.chatList.sortList('user', id)
          } else {
            this.$refs.chatList.updateLastMsg('group', message.groupId, message)// 更新左侧列表显示的最新消息
            this.$refs.chatList.sortList('group', message.groupId)
          }
        } else { // 其他人或组的消息--添加小红点
          if (message.chatReceiveType === 0) { // 个人未读
            let id = message.groupId// 接收方id
            if (id === this.myUserId) { // 如果接收方是自己，就拿发送方的id
              id = message.sendUser.id
            }
            this.$refs.chatList.appendCircle('user', id)// 设置未读标志
            this.$refs.chatList.updateLastMsg('user', id, message)// 更新左侧列表显示的最新消息
          } else { // 群组未读
            this.$refs.chatList.appendCircle('group', message.groupId)// 设置未读标志
            this.$refs.chatList.updateLastMsg('group', message.groupId, message)// 更新左侧列表显示的最新消息
          }
        }

      /*

        setNotifyData(message)//设置通知提示消息 */
      })
      // 获取左侧列表
      this.connection.on('allUsers', (data) => {
        console.log('allUsers', data)
        if (data) {
          this.allUserGroups = data
          this.initClick()
          this.dealAllUserForList()
          this.hasUserGroupsData = true // 是否已拿到数据
          if (this.isOpenCreate) {
            this.openCreateGroup(this.parentData)
            this.isOpenCreate = false
          }
        } else {
          console.error('error,please restart ChatHub')
        }
      })

      this.connection.on('onlineUserChange', (data) => {
        console.log('在线人数', data)
        if (data) {
          this.$refs.chatList.onlineUserChange(data)
        } else {
          console.error('error,please restart ChatHub')
        }
      })
      this.connection.on('MyGroups', (data) => {
        console.log('我的群组', data)
        this.$refs.chatList.changeGroups(data)
      })
    },
    getParentMessage () { // iframe接收父页面发来的消息
      this.$chatUtils.getMessageFromParent((event) => {
        let msg = event.data
        if (msg.type === 'create') {
          this.parentData = msg
          if (this.hasUserGroupsData) {
            this.openCreateGroup(this.parentData)
          } else {
            this.isOpenCreate = true
          }
        }
        if (msg.type === 'comment') {
          this.$refs.inputSend.sendMsg('comment', msg.data)
        }
        if (msg.type === 'login') {
          let params = {
            id: msg.data.id,
            userName: msg.data.userName,
            dep: msg.data.dep
          }
          this.myUserId = msg.data.id
          this.pageType = msg.data.pageType
          this.checkUserAndLogin(params)
        }
      })
    },
    openCreateGroup (msg) { // 判断是否有父页面传来打开弹窗或者打开聊天页的消息
      if (this.allUserGroups.allGroups) {
        let groups = this.allUserGroups.allGroups.find(res => {
          return res.groupType === 'RIS'
        })
        if (groups) {
          let item = groups.groups.find(v => {
            return v.groupId === msg.data.groupId
          })
          if (item) {
            // 打开聊天页面
            this.$nextTick(() => {
              this.$refs.chatList.getChart(1, item)
            })
          } else {
            // 打开创建群弹窗还是加入群组
            this.judgeIsCreated(msg)
          }
        } else {
          // 打开创建群弹窗还是加入群组
          this.judgeIsCreated(msg)
        }
      } else {
        // 打开创建群弹窗还是加入群组
        this.judgeIsCreated(msg)
      }
    },
    judgeIsCreated (msg) { // 打开创建群弹窗还是加入群组
      let params = {
        id: msg.data.groupId,
        type: Number(this.pageType)
      }
      isExistGroup(params).then(data => {
        if (!data) { // 群组不存在-创建
          this.createParams = msg.data
          this.createVisible = true
          this.peopleModalType = 'create'
        } else { // 群组已存在-未加入-加入
          this.$confirm('该群组已存在，是否加入群组？')
            .then(_ => {
              let params = {
                userId: this.myUserId,
                groupId: msg.data.groupId
              }
              joinGroup(params).then(data => {
                this.$message.success('加入群成功')
              })
            })
        }
      })
    },
    checkUserAndLogin (params) { // 同步用户数据后登录
      /* let params = {
        id: msg.data.id,
        userName: msg.data.userName,
        dep: msg.data.dep
      } */
      batchUserData([params]).then(data => {
        this.login(this.myUserId)
      })
    },
    initNotify () {
      // 生成消息提示实例
      // eslint-disable-next-line no-undef
      this.iN = new Notify({
        effect: 'flash',
        interval: 500,
        message: '有消息拉！',
        audio: {
          file: 'static/消息提示音.mp3'// 可以使用数组传多种格式的声音文件
        },
        notification: {
          title: '通知！',
          icon: '',
          body: '您来了一条新消息'
        }
      })
    },
    dealAllUserForList () { // 筛选出自己和其他人的数据
      this.mySelfData = {}
      this.allUserGroups.allUsers.forEach((el, i) => {
        if (el.user.id === this.myUserId) {
          this.mySelfData = el
        }
      })
    },
    settingClick () {
      this.settingShow = !this.settingShow
      this.historyShow = false
    },
    historyClick () {
      this.historyShow = !this.historyShow
      this.settingShow = false
    },
    changeGroupSetting () {
      // 判断是否开着群组页面，是否要刷新群组详情
      if (this.settingShow) {
        this.$refs.setting.getGroupDetail()
      }
    },
    changeGroupDelete () {
      this.contentShow = false
      if (this.pageSize === 'small') {
        this.chatListShow = true
      }
    },
    backToList () {
      this.changeGroupDelete()
    },
    chatClick (params) {
      this.contentShow = true
      // 调整屏幕大小
      if (this.pageSize === 'small') {
        this.chatListShow = false
      }

      this.settingShow = false
      this.historyShow = false

      // 在切换content以前，通知关闭一下ris的检查数据
      let data = {
        type: 'closeRis'
      }
      this.$chatUtils.postToParent(data)
    },
    isVisibility () {
      // 判断是否在当前页
      var hiddenProperty = 'hidden' in document ? 'hidden'
        : 'webkitHidden' in document ? 'webkitHidden'
          : 'mozHidden' in document ? 'mozHidden'
            : null
      return !document[hiddenProperty]
    },
    sendMsgServer (param) {
      this.connection.invoke('SendNew', param)
        .then(function () {

        })
        .catch(function (err) {
          return console.error(err.toString())
        })
    },
    createGroup (val) {
      this.createVisible = true
      this.peopleModalType = val
    },
    addPeopleGroup (val) {
      this.groupPeopleData = val
      this.createGroup('add')
    },
    windowResize () {
      let width = window.innerWidth
      if (width <= 663) { // 手机
        this.pageSize = 'small'
        this.chatListShow = true
        this.contentShow = false
      } else {
        this.pageSize = 'big'
        this.chatListShow = true
      }
    },
    initClick () {
      if (this.pageSize === 'big') {
        // 初始点击
        let clickItem = JSON.parse(window.localStorage.getItem('clickItem'))
        if (clickItem && clickItem.id !== this.myUserId) {
          this.$nextTick(() => {
            let obj = null
            if (clickItem.type === 0) { // 单聊
              obj = this.allUserGroups.allUsers.find(v => {
                return v.user.id === clickItem.id
              })
            } else { // 群聊
              if (this.pageType === '1') { // 普通群聊
                let item = this.allUserGroups.allGroups.find(res => {
                  return res.groupType === 'Simple'
                })
                if (item) {
                  obj = item.groups.find(v => {
                    return v.groupId === clickItem.id
                  })
                }
              } else { // RIS群聊
                if (this.pageType === '2') { // RIS群聊
                  let item = this.allUserGroups.allGroups.find(res => {
                    return res.groupType === 'RIS'
                  })
                  if (item) {
                    obj = item.groups.find(v => {
                      return v.groupId === clickItem.id
                    })
                  }
                }
              }
            }
            if (obj) {
              obj.isClick = true
              this.$refs.chatList.getChart(clickItem.type, obj)
            }
          })
        }
      }
    }
  },
  beforeDestroy () {},
  destroyed () {},
  beforeUpdate () {},
  updated () {}
}
</script>
<style scoped lang="scss">
.ky-chat-main{
    width:100%;
    height: 100%;
    min-width: 370px;//最小限制370px
    .top-bar{
        width:100%;
        height:55px;
        background: #0FC6C2;
        .logo{
            height: 36px;
            margin-left: 10px;
            margin-top: 10px;
        }
        .my-avatar{
            width:44px;
            height:44px;
        }
        .img-text{
            float: right;
            margin-top: 6px;
            margin-right: 22px;
            img{
                border-radius: 5px;
            }
            span{
                float: right;
                margin-top: 12px;
                color: #fff;
                margin-left: 10px;
            }
        }
    }
}
.chat-main{
    width:100%;
    height: calc(100% - 57px);
    display:flex;
    .right-main{
        flex:1;
        height:100%;
        background: rgba(242, 243, 245, 1);
        position: relative;
        .right-content{
            height: 100%;
            flex:1;
            position: relative;
        }
    }
    .more-icon-3{
        position: absolute;
        top: 20px;
        left: 15px;
    }
}
</style>
<style lang='scss'>
@media screen and (max-width: 1240px) and (min-width:664px){/* 平板 */

    .history,.setting{
        position: absolute!important;
        right: 0px;
        height: 100%!important;
        width: 100%!important;
    }
    #back-to-main{
        display: block!important;
    }
    .left-user{
        width: 200px!important;
        height: 100%!important;
        background: #fff;
        display: flex;
        flex-direction: column;
    }
    .name-content .time{
        display: none;
    }
    .name-content .name{
        width:100%
    }
}
@media screen and (max-width:663px){/* 手机 */
    .history,.setting{
        position: absolute!important;
        right: 0px;
        height: 100%!important;
        width: 100%!important;
    }
    #back-to-main{
        display: block!important;
    }
    #back-to-list{
        display: block!important;
    }
    .left-user{
        width: 100% !important;;
        height: 100% !important;
        background: #fff;
        display: flex;
        flex-direction: column;
    }
    .logo-div{
        display: none;
    }
    .welcome{
        display: none!important;
    }
}
</style>
<style lang="scss">
/* 滚动条样式 */
.ky-chat-main {
    /* 设置滚动条的样式 */
    ::-webkit-scrollbar {
        width:8px;
        height: 8px;
    }
    /* 滚动槽 */
    ::-webkit-scrollbar-track {
        -webkit-box-shadow:inset006pxrgba(0,0,0,0.3);
        border-radius:10px;
    }
    /* 滚动条滑块 */
    ::-webkit-scrollbar-thumb {
        border-radius:10px;
        background:rgba(0,0,0,0.1);
        -webkit-box-shadow:inset006pxrgba(0,0,0,0.5);
    }
}
.el-message-box{
    max-width: 420px;
    width:auto;
}

</style>
