<template>
    <div class='ui-grid c-h100'>
        <div class="ui-col-0 w-350 c-border-r pb20 c-h100">
            <div class="c-border-b session-title plr15">医生会话列表</div>
            <message-list :records='messageList' :readJudge='readJudge' :dialogIndex='dialogIndex' @clickDoctor='clickDocOrPat'></message-list>
        </div>
        <div class="ui-col-1 c-h100">
             <message-content :chatMsgInfo='chatMsgInfo' 
                :msgsTit='msgsTit' 
                :userId='userId' 
                :lastFetchTime='lastFetchTime' 
                :readJudge='readJudge' 
                :msgMoreJudge='msgMoreJudge' 
                :notEndConsultId='notEndConsultId' 
                :unSendMsg='unSendMsg'  
                :sessionId='sessionId'
                @submitMsg='submitMsg'
                @getMoreMsg='getMoreMsg'></message-content>
        </div>
    </div>
</template>
<script>
import _ from 'lodash'
import messageList from '@/components/messagePage/message-list.vue'
import messageContent from '@/components/messagePage/message-content.vue'
import storage from '../assets/js/storage'
import common from '../assets/js/common'
import ajaxUrl from '../assets/js/ajaxurl'
import getSessionsService from '../assets/js/apis/api-im'
import P2PSocketService from '../assets/js/apis/api-p2psocket'

let loginDoctor = storage.getItem(storage.API_LOGIN_DOCTOR),
    userId = '',
    userName = '',
    docLevel = '',
    doctorLevel = null,
    authOperate =  null
let socket

export default {
    props: [],
    components: {
        messageList,
        messageContent,
    },
    mounted() {
        this.getSessionsDoctor()
    },
    // 发送消息通过全局传参过来的信息
    created() {
        loginDoctor = storage.getItem(storage.API_LOGIN_DOCTOR)
        userId = loginDoctor.uid
        userName = loginDoctor.name
        docLevel = loginDoctor.level
        doctorLevel = null
        authOperate = loginDoctor.currentUserRole ? loginDoctor.currentUserRole.doctorAuthOperate : null
        this.userId = userId
        this.isleader = loginDoctor.isLeader
        this.authOperate = authOperate

        this.$root.bus.$on('translateDocMSg', value => {
            // this.translateDocMsg(value)
        })
        this.$root.bus.$on('infoToMsg', value => {
            // this.judgeDocOrPatMsg(value)
        })
        this.$root.bus.$on('msgRenovate', value => {
            // if (value) {
            //     this.infoToMsgJudge = value
            //     this.activeMsgTabIndex = value
            // }
            // this.activeMessageTab(this.activeMsgTabIndex, true)
        })
        this.$root.bus.$on('followup', value => {
            // this.finshedFollowUp(value)
        })
        this.$root.bus.$on('sendArticleEvent', value => {
            // this.getParticipants(value)
        })
        this.$root.bus.$on('closeSignMsg', value => {
            // this.getNoticeMsgInfo('0')
        })
        this.$root.bus.$on('refreshMsgList', value => {
            // this.getNoticeMsgInfo('5')
        })
        this.$root.bus.$on('joinMemberInChat', value => {
            this.joinMemberInChat(value);
        })
    },
    data(){
        return {
            level: docLevel,
            isleader: loginDoctor.isLeader,
            authOperate: authOperate,
            // activeMsgTabIndex: null,
            activeMsgTabIndex: 0,
            // 格式化定义以防异步加载时提前调用数组报underfind
            
            messageList: [], // 消息-医生列表
            chatMsgInfo: [], // 会话消息
            msgsTit: null, // 消息标题
            notEndConsultId: null, // 结束咨询code
            userId: userId,
            readJudge: false, // 显示阅读消息
            unSendMsg: false, // 是否可发送消息
            lastFetchTime: null, // 获取已读的时间戳
            infoToMsgJudge: null, // 个人信息跳转至消息页判断
            sessionId: null,
            sessionName: null,
            judgeMsgCon: true, // 判断显示消息组件
            msgMoreJudge: false, // 是否可点击加载更多消息
            msgsPage: 1, // 加载的聊天记录页数
            scrollVal: null, // 消息的滚动条位置判定
            dialogIndex: null, // 会话列表指示位置
            // showMsgInfo: false, //是否显示消息详情
            frameUrl: "" //配置消息页面打开的内容
        }
    },
    methods:{
        photoSrc(str) {
            return common.setImgUrl(str)
        },
        // 获取tab栏医生消息列表
        async getSessionsDoctor(index, judge) {
            let result = await getSessionsService.Sessions.getSessionsWithDoctor(userId, 1, 2000),
                data = result.data
            console.log(result)
            let resData = []
            for (let k in data) {
                let d = data[k]
                if ((Number(d.business_type) === 1 || Number(d.business_type) === 1) && Number(d.type) !== 0 && Number(d.type) !== 1 && d.name !== '系统消息') {
                    resData.push(data[k])
                }
            }

            this.uniteGetList(result, resData, judge)
        },
        // 居民（医生）列表点击会话获得对应消息
        async getDocOrPatMsg(sessionId, user) {
            let msgs = await getSessionsService.Sessions.getMessagesBySession(sessionId, user, 1, this.msgsPage ? this.msgsPage * 20 : '')
            // this.activeMessageTab(this.activeMsgTabIndex, true)
            if (msgs.status === 200) {
                this.$loading.close()
                let msgsLen = msgs.data.length
                // 消息更多判定
                if (msgsLen === this.msgsPage * 20) {
                    if (this.msgsPage !== 1) {
                        this.$root.bus.$emit('scrollConVal', 100 / (this.msgsPage - 1))
                    }
                    this.msgMoreJudge = true
                } else {
                    if (this.msgsPage !== 1) {
                        this.$root.bus.$emit('scrollConVal', (msgsLen - (this.msgsPage - 1) * 20) * 100 / (this.msgsPage * 20))
                    }
                    this.msgMoreJudge = false
                }
                this.chatMsgInfo = msgs.data.reverse()
                // 获取会话中头像
                this.getSessionsDocImg(this.sessionId)
                this.getTalkMeMberList(sessionId)
            } else {
                // 状态码值统一处理
                common.xhrStatus.call(this, msgs)
            }
        },
         // 获取会话中成员列表，从而拿到各成员的最后读取时间，来渲染是否是已读
        async getTalkMeMberList(sessionId) {
            let result = await getSessionsService.Sessions.getParticipants(sessionId)
            if (result.status !== 200) {
                this.$toast('获取成员列表失败！')
                return
            }
            let member = result.data,
                len = member.length
            if (len === 2) { // 两人对话
                if (member[0].id === userId) {
                    this.lastFetchTime = member[1].last_fetch_time
                } else {
                    this.lastFetchTime = member[0].last_fetch_time
                }
            } else if (len === 3) {
                for (let i = 0; i < len; i++) {
                    if (member[i].is_patient === 1) {
                        this.lastFetchTime = member[i].last_fetch_time
                    }
                }
            } else {
                this.lastFetchTime = null
            }
            for(let i=0 ; i<len; i++){
                if(member[i].id == userId){
                    this.userName = member[i].name;
                    userName = member[i].name;
                    loginDoctor.name = member[i].name;
                    loginDoctor.photo = member[i].avatar;
                    storage.setItem(storage.API_LOGIN_DOCTOR, loginDoctor)
                }
            }
        },
        // 居民(医生)列表点击会话回传参数
        clickDocOrPat(info) {
            this.$loading('')
            this.unSendMsg = false
            this.msgsTit = info.name || info.session_name
            this.judgeMsgCon = true // 消息聊天框
            this.chatMsgInfo = []
            this.msgsPage = 1
            this.sessionId = info.id || info.session_id
            this.sessionName = info.name || info.session_name
            this.getDocOrPatMsg(this.sessionId, userId)
            this.createSessionId()
            this.readJudge = true
            let len = info.participantsTimeArray.length
            if (len === 2) { // p2p
                // 获取咨询code
                this.getConsultInfo()
                this.overConsult = false
            } else {
                this.overConsult = false
                if (len === 3) { // p2p中存在系统结束咨询
                    for (let i in info.participantsTimeArray) {
                        for (let j in info.participantsTimeArray[i]) {
                            if (j === 'system') {
                                this.unSendMsg = true
                                return
                            }
                        }
                    }
                }
            }
        },
        // 统一处理获取居民与医生消息列表
        uniteGetList(result, resData, judge) {
            if (result.status === 200) {
                this.messageList = []
                this.getAllDoctImg(resData || result.data, judge)
            } else {
                // 状态码值统一处理
                common.xhrStatus.call(this, result)
            }
        },
        // 获取更多聊天消息
        getMoreMsg() {
            this.msgsPage++
            this.getDocOrPatMsg(this.sessionId, userId)
        },
        // 医生消息头像设置
        setPhoto(groupPhoto, obj) {
            var images = '',
                cssArr = null
            if (groupPhoto.length >= 5) {
                cssArr = ['position: absolute;overflow:hidden;width:19px;height:19px;border-radius: 50%;top: 0;left: 10px;', 'position: absolute;overflow:hidden;width:19px;height:19px;border-radius: 50%;top: 8px;left: 2px;', 'position: absolute;overflow:hidden;width:19px;height:19px;border-radius: 50%;top: 8px;left: 18px;', 'position: absolute;overflow:hidden;width:19px;height:19px;border-radius: 50%;top: 18px;left: 4px;', 'position: absolute;overflow:hidden;width:19px;height:19px;border-radius: 50%;top: 18px;left: 17px;']
            } else if (groupPhoto.length === 4) {
                cssArr = ['position: absolute;overflow:hidden;width:19px;height:19px;border-radius: 50%;top: 0px;left: 10px;', 'position: absolute;overflow:hidden;width:19px;height:19px;border-radius: 50%;top: 10px;left: 0px;', 'position: absolute;overflow:hidden;width:19px;height:19px;border-radius: 50%;top: 20px;left: 10px;', ' position: absolute;overflow:hidden;width:19px;height:19px;border-radius: 50%;top: 10px;left: 20px;']
            } else if (groupPhoto.length === 3) {
                cssArr = ['position: absolute;overflow:hidden;width:19px;height:19px;border-radius: 50%;top: 0px;left: 10px;', 'position: absolute;overflow:hidden;width:19px;height:19px;border-radius: 50%;top: 16px;left: 2px;', 'position: absolute;overflow:hidden;width:19px;height:19px;border-radius: 50%;top: 16px;left: 18px']
            // } else if (groupPhoto.length === 2) {
            //     cssArr = ['position: absolute;overflow:hidden;width:19px;height:19px;border-radius: 50%;top: 10px;left: 0px;', 'position: absolute;overflow:hidden;width:19px;height:19px;border-radius: 50%;top: 10px;left: 20px;']
            } else if (groupPhoto.length === 2 || groupPhoto.length === 1 || groupPhoto.length === 0) {
                cssArr = ['position: absolute;width: 39px;height: 39px;border-radius: 50%;background-size: 39px;overflow: hidden;']
                if (groupPhoto.length === 2) {
                    let img = (groupPhoto[0].id === userId ? groupPhoto[1].avatar : groupPhoto[0].avatar)
                    images = '<div class="div-image" style="' + cssArr + '">' +
                                    '<img src="' + this.photoSrc(img) + '"/>' +
                                '</div>'
                }
            }
            let len = groupPhoto.length
            for (let i = 0; i < len; i++) {
                if (i > 4 || len === 2) break
                if (groupPhoto[i].avatar) {
                    images += '<div class="div-image" style="' + cssArr[i] + '">' +
                                '<img src="' + this.photoSrc(groupPhoto[i].avatar) + '"/>' +
                            '</div>'
                } else {
                    images += '<div class="div-image" style="' + cssArr[i] + '">' +
                                    '<img src=".images/d-male.png"/>' +
                                '</div>'
                }
            }
            if (len === 0) {
                images += '<div class="div-image" style="' + cssArr[0] + '">' +
                                    '<img src="./images/d-male.png"/>' +
                                '</div>'
            }
            // 将头像和会话合并
            obj.img = images
        },
        // 异步拿取各医生头像数组
        async getSessionsDocImg(sessionId, obj) {
            let msg = await getSessionsService.Sessions.getParticipantsAvatars(sessionId),
                result = msg.data
            if (msg.status === 200) {
                if (obj) {
                    this.setPhoto(result, obj)
                } else {
                    // 每条回话消息推入个人头像
                    let arr = []
                    for (let i = 0, length = this.chatMsgInfo.length; i < length; i++) {
                        let chatMsg = JSON.parse(this.chatMsgInfo[i]) ? JSON.parse(this.chatMsgInfo[i]) : this.chatMsgInfo[i]
                        if (chatMsg.content_type === 0) {
                            arr[i] = this.chatMsgInfo[i]
                        }
                        if (chatMsg.content_type === 5 || chatMsg.content_type === 7 || chatMsg.content_type === 10 || chatMsg.content_type === 13 || chatMsg.content_type === 14) {
                            arr[i] = this.chatMsgInfo[i]
                        } else {
                            for (let j = 0, len = result.length; j < len; j++) {
                                if (chatMsg.sender_id === result[j].id) {
                                    arr[i] = JSON.stringify(Object.assign(chatMsg, {'chatImg': result[j].avatar, 'name': result[j].name}))
                                }
                            }
                        }
                    }
                    this.chatMsgInfo = arr
                }
            } else {
                // 状态码值统一化处理
                common.xhrStatus.call(this, msg)
            }
        },
        // 获取所有头像组数组
        getAllDoctImg(arr, judge) {
            let obj = _.chain(arr).map(function(o) {
                o.img = ''
                return o
            }).sortBy(function(o) {
                return -o.create_date
            }).value()
            this.messageList = obj
            let i = 0,
                len = obj.length
            for (i, len; i < len; i++) {
                if (judge) { // 判断是从跳转页过来
                    let objId = obj[i].id + '',
                        sesId = this.sessionId + ''
                    if (objId === sesId) {
                        this.dialogIndex = i
                    }
                }
                this.getSessionsDocImg(this.messageList[i].id, this.messageList[i])
            }
        },
        // 异步发送消息功能
        async submit(sessionId, sendorCode, sendorName, content, contentType) {
            let msg = await getSessionsService.Sessions.sendMessage(sessionId, sendorCode, sendorName, content, contentType)
                // result = msg.data
            if (msg.status === 200) {
                this.getDocOrPatMsg(this.sessionId, userId)
                this.$root.bus.$emit('judgeSessionId', 0)
                this.$root.bus.$emit('scrollCon', true)
                if (this.activeMsgTabIndex === '1' || this.activeMsgTabIndex === '2') {
                    let ele = 'msgList' + this.activeMsgTabIndex
                    document.getElementById(ele).scrollTop = 0
                }
                // 刷新列表
                let judge = parseInt(this.activeMsgTabIndex ? this.activeMsgTabIndex : this.infoToMsgJudge)
                if (Number(judge) === 1) {
                    this.getSessionsPatient(1, this.defaultSel)
                }
                if (Number(judge) === 2) {
                    this.getSessionsDoctor(2)
                }
            } else {
                // 状态码值统一处理
                common.xhrStatus.call(this, msg)
            }
        },
        // 消息发送回传父组件
        submitMsg(arr) {
            this.$loading('')
            this.msgsPage = 1
            const self = this
            // 文本消息发送
            if (arr[1] === 1) {
                this.submit(this.sessionId, userId, userName, arr[0], arr[1])
            } else if (arr[1] === 2) {
                // 先上传
                const formData = new FormData()
                formData.append('file', arr[0])
                this.$http.post(ajaxUrl.imgUploadUrl + '/upload/chat', formData).then(function(response) {
                    // 图片发送
                    let msg = response.data
                    if (msg.status === -1) {
                        self.$loading.close()
                        self.$toast(msg.msg)
                        return
                    }
                    self.submit(self.sessionId, userId, userName, msg.urls, arr[1])
                }, function(response) {
                    this.$loading.close()
                    this.$toast('上传失败')
                })
            }
        },
        // socket实现实时聊天
        chatBySocket() {
            if (socket) {
                socket.close()
            }

            socket = P2PSocketService.loginIM(this.sessionId)
            // 实时收到消息
            socket.on('message', (data) => {
                // alert(JSON.stringify(data))
                this.getDocOrPatMsg(this.sessionId, userId)
                this.$root.bus.$emit('scrollCon', true)
            })
            // 错误提醒
            socket.on('error', function (data) {
                alert('Error')
            })
            // scoket连接成功
            socket.on('ack', function (data) {
            })
        },
        // 异步获取this.sessionId
        async createSessionId(obj) {
            // params obj 用于参考（个人详情跳转过来的）
            if (obj) {
                this.sessionId = await P2PSocketService.createSocketConnect({
                    patientCode: obj.patOrDocCode,
                    patientName: obj.name
                })
                this.getSessionsDoctor(2)
                // 会话指向
                this.$root.bus.$emit('judgeSessionId', 0)
            }
            this.getDocOrPatMsg(this.sessionId, userId)
            this.chatBySocket()
            this.$root.bus.$emit('scrollCon', true)
        },
        //创建群聊会话
        async createGroupSession(obj){
            this.sessionId = await P2PSocketService.createGroupSession({
                sessionId: '',
                sessionType: obj.type,
                sessionName: obj.sessionName,
                participants: obj.participants
            })
            if(obj.createVideoChat){
                console.log("createGroupSession");
                this.$root.bus.$emit('showChatWindow', {chatMembers: [], sessionId: this.sessionId, createChat: true})
            }
        },
        //添加成员到群聊中
        async joinMemberInChat(arr){
            var vm = this;
            console.log(arr);
            let res = await P2PSocketService.addParticipant({
                sessionId: vm.sessionId,
                participantId: arr.join(",")
            })
        },
        // 个人资料发送消息跳转处理
        judgeDocOrPatMsg(value) {
            this.msgsTit = value.name
            this.infoToMsgJudge = value.code ? 1 : 2
            this.activeMsgTabIndex = this.infoToMsgJudge
            this.msgsPage = 1
            this.judgeMsgCon = true
            // 获取与选择的聊天记录
            if (value.id) { // team id 医生团队 sessionId 居民sessionid
                this.sessionId = value.id
                this.getSessionsDoctor(this.activeMsgTabIndex, true)
                this.createSessionId()
            } else if (value.type == '4') { //创建普通群聊
                this.createGroupSession(value)
            } 
            this.unSendMsg = false
            this.readJudge = true
            this.$root.bus.$emit('scrollCon', true)
        }
    }
}
</script>

<style scoped>
    .c-h100{
        height: 100%;
    }
    .w-350{
        width: 350px;
    }
    .session-title{
        height: 40px;
        line-height: 40px;
        font-size: 16px;
    }
</style>

