<template>
    <div class='box' v-if="showBox">
        <div class="chatContent">
            <div class="left" v-if="isLeft">
                <div class="topContent">
                    <img class="icon" :src="userInfo.icon+'?x-oss-process=image/resize,m_fill,h_40,w_40'" alt="">
                    <span>{{userInfo.nickname}}</span>
                </div>
                <div class='leftList' v-if="conversationList.length>0">

                    <div class="left-item" v-for="(item,index) in conversationList" @click="readAll(item)">
                        <img class="icon" :src="item.storeInfo.icon+'?x-oss-process=image/resize,m_fill,h_40,w_40'" alt="">
                        <div class="content">
                            <div class="name">{{item.storeInfo.storeName}}</div>
                            <div class="subtitle" v-if="item.chatInfo">{{item.chatInfo.content}}</div>
                        </div>
                        <div class="time" v-if="item.amount">
                            <el-badge :value="item.amount" :hidden='item.amount?false:true' class='item'>
                            </el-badge>
                            <span>{{forNow(item.updateTime)}}</span>
                        </div>
                        <div class="close" @click.stop='del(item,index)'>
                            <i class="el-icon-error"></i>
                        </div>

                    </div>

                </div>

                <div class="nothing" v-else>
                    还没有聊天记录哦，快去咨询店铺吧~
                </div>

            </div>

            <div class="right" v-else>
                <div class="topContent">
                    <el-button v-if='canBack' style="color:#fff;font-size:20px;margin-right:10px" @click="isLeft=true,storeId=0,chatList=[]" icon="el-icon-back" type="text" circle></el-button>
                    <img class="icon" :src="storeInfo.icon+'?x-oss-process=image/resize,m_fill,h_40,w_40'" alt="">
                    <span>{{storeInfo.storeName}}</span>
                    <span style="font-size:14px;margin-left:20px;">{{storeInfo.citye}}</span>
                </div>
                <div class="chatList" ref='chatList' @scroll='scrollChat'>
                    <div class="chat-item" v-for="item in orderedHistory" :style="{flexDirection:item.typeFlag?'row':'row-reverse'}">
                        <img class="icon" :src="(item.typeFlag?storeInfo.icon:userInfo.icon)+'?x-oss-process=image/resize,m_fill,h_40,w_40'" alt="">
                        <div class="chatInfo">{{item.content}}</div>
                    </div>
                </div>
                <div class="inputContent">
                    <el-input type="textarea" @keydown="keyDownEvent" maxlength="200" resize='none' :autosize="{ minRows:6}" placeholder="请输入内容" v-model="textarea3">
                    </el-input>

                    <el-button type="primary" class="submit" @click="send">发送</el-button>
                </div>
            </div>

            <div class="floatRight">

                <el-button @click="showBox=false" style="color:#fff;font-size:30px" icon="el-icon-close" type="text" circle></el-button>
            </div>
        </div>
    </div>

</template>

<script>
import { mapState } from 'vuex'
import eventBus from '../eventBus'
export default {
    created() {
        eventBus.$on('receiveMessage', this.onReceiveMessage)
        // if (this.$route.name == 'shop') {
        //     this.storeId = this.$route.query.id
        //     this.getChatInfo(this.storeId)
        //     this.canBack = false
        // }
        // else if (this.$route.name == 'product') {
        //     this.storeId = this.$route.query.storeId
        //     this.getChatInfo(this.storeId)
        //     this.canBack = false
        // }
        // else {

        // }
        this.isLeft = true
        this.storeId = 0
        this.canBack = true
    },
    name: 'chatContent',
    data() {
        return {
            storeId: 0,
            chatList: [],
            storeInfo: {},
            textarea3: '',
            customerList: [],
            currentPage: 1,
            isLeft: true,
            showBox: false,
            canBack: true,
            chatFlag: false
        }
    },
    computed: {
        ...mapState(['userInfo', 'conversationList']),
        orderedHistory() {
            return this.chatList.sort((a, b) => {
                return a.time - b.time
            })
        },
        coventIndex() {
            var index = -1
            if (this.storeId) {
                this.conversationList.forEach((item, i) => {
                    if (item.storeId == this.storeId && item.userId == this.userInfo.id) {
                        index = i
                    }
                });
            }
            return index
        }
    },
    watch: {
        // $route() {
        //     console.log(this.$route.name)
        //     if (this.$route.name == 'shop') {
        //         this.storeId = this.$route.query.id
        //         this.getChatInfo(this.storeId)
        //         this.canBack = false
        //     }
        //     else if (this.$route.name == 'product') {
        //         this.storeId = this.$route.query.storeId
        //         this.getChatInfo(this.storeId)
        //         this.canBack = false
        //     }
        //     else {
        //         this.isLeft = true
        //         this.storeId = 0
        //         this.canBack = true
        //     }
        // },
        isLeft() {
            if (!this.isLeft) {
                this.goBottom()
            }
        },
        showBox() {
            if (this.showBox) {
                this.goBottom()
            }
        }
    },
    beforeDestroy() {
        eventBus.$off('receiveMessage', this.onReceiveMessage)
    },
    methods: {
        readAll(item, type) {
            this.$http.get({
                url: '/chatInfo/readAll',
                data: {
                    storeId: item.storeId,
                    userId: item.userId,
                    typeFlag: 1
                }
            })
            if (type) {
                return
            }
            this.storeId = item.storeId
            this.getChatInfo(item.storeId)
        },
        getChatInfo(id) {
            this.isLeft = false
            this.chatList = []
            this.storeInfo = {}
            this.customerList = []
            this.$http.get({
                url: '/storeInfo/getOne',
                data: {
                    id: id,
                }
            }).then(res => {
                if (res.success) {
                    this.storeInfo = res.data




                }
            }).catch(e => {
                console.log(e)
            })
            this.$http.get({
                url: '/customerService/recently',
                data: {
                    storeId: id,
                }
            }).then(res => {
                if (res.success) {
                    res.data.forEach((item, index) => {
                        if (item.checkOnlineResult.status == '1') {
                            res.data.splice(0, 0, item)
                        }
                    })
                    console.log(res.data)
                    this.customerList = res.data
                    console.log(this.customerList)

                }
            }).catch(e => {
                console.log(e)
            })

            this.currentPage = 1
            this.getPageChat()


        },
        getPageChat() {
            this.chatFlag = false
            this.$http.get({
                url: '/chatInfo/page',
                data: {
                    currentPage: this.currentPage,
                    pageNumber: 10,
                    storeId: this.storeId,
                    userId: this.userInfo.id
                }
            }).then(res => {
                if (res.success) {
                    res.data.pp.forEach(item => {
                        this.chatList.push(item)
                    });

                    if (res.data.currentPage < res.data.totalPage) {
                        this.chatFlag = true
                    }

                    if (this.chatList.length == 0) {
                        setTimeout(() => {
                            // this.$IM.newConversation({
                            //     userId: this.userInfo.id,
                            //     type: 0,
                            //     storeId: this.storeId,
                            //     success: (res) => {

                            //     }
                            // })

                            // this.$IM.newConversation({
                            //     userId: this.userInfo.id,
                            //     type: 1,
                            //     storeId: this.storeId,
                            //     success: (res) => {

                            //     }
                            // })
                            this.$http.post({
                                url: '/chatInfo/save',
                                data: {
                                    'content': '您好，感谢您对' + this.storeInfo.storeName + '的关注，我们会尽快回复您的咨询。',
                                    'contentType': 0,
                                    'state': 1,
                                    'storeId': this.storeId,
                                    'userId': this.userInfo.id,
                                    'typeFlag': 1
                                }
                            }).then(res2 => {
                                if (res2.success) {
                                    this.chatList.push(res2.data)
                                }
                            })
                        }, 1000)
                    }




                    // this.chatList = res.data.pp

                }
            }).catch(e => {
                console.log(e)
            })
        },
        goBottom() {
            setTimeout(() => {
                if (this.$refs.chatList) {
                    this.$refs.chatList.scrollTop = this.$refs.chatList.scrollHeight
                }

            }, 50)

        },
        send() {
            if(!this.textarea3){
                return
            }


            var customer = ''
            if (this.customerList.length > 0) {
                customer = this.customerList[0].username
            }
            this.$IM.sendMessage({
                target: this.storeId,
                content: {
                    content: this.textarea3,
                    extra: {
                        storeId: this.storeId,
                        typeFlag: "0",
                        userId: this.userInfo.id.toString()
                    }
                },
                userId: this.userInfo.id,
                typeFlag: 0,
                customer: customer,
                success: (res) => {
                    this.textarea3 = ''
                    console.log(res)
                    this.chatList.push(res)
                    this.goBottom()
                }
            })
        },
        onReceiveMessage(message) {
            if (!this.isLeft && message.storeId == this.storeId) {
                this.chatList.push(message)
                console.log('收到啦' + JSON.stringify(message))
                this.goBottom()
                this.readAll({
                    storeId: this.storeId,
                    userId: this.userInfo.userId,
                }, 1)
            }
        },
        del(item, index) {
            console.log(item)


            this.$http.post({
                url: '/usersSession/del',
                data: {
                    id: item.id
                }
            }).then(res => {
                if (res.success) {
                    var list = [...this.conversationList]
                    list.splice(index, 1)
                    this.$store.commit('updateConversationList', list);
                }
            })
        },
        scrollChat() {
            if (this.$refs.chatList.scrollTop == 0 && this.chatFlag) {
                this.getChatInfo()
            }
        },
        keyDownEvent(e) {
            console.log(e)
        }
    }
}
</script>

<style lang="less" scoped>
.box {
    background-color: rgba(0, 0, 0, 0.3);
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 600;

    .chatContent {
        display: flex;
        background: rgba(254, 254, 254, 1);
        box-shadow: 0px 2px 4px 0px rgba(0, 0, 0, 0.5);
        border-radius: 4px;
        position: absolute;
        top: 20vh;
        left: 50%;
        transform: translateX(-50%);
        height: 60vh;
        min-height: 360px;
    }

    .topContent {
        background: linear-gradient(151deg, rgba(27, 184, 172, 1) 0%, rgba(0, 142, 205, 1) 100%);
        box-shadow: 0px 1px 3px 0px rgba(0, 0, 0, 0.2);
        height: 55px;
        padding: 0 15px;
        line-height: 55px;
        .icon {
            border-radius: 100%;
            vertical-align: middle;
        }
        span {
            font-size: 22px;
            font-weight: 400;
            color: rgba(255, 255, 255, 1);
            vertical-align: middle;
            margin-left: 8px;
        }
    }

    .leftList {
        padding: 0 15px;
        // height: 583px;
        overflow: auto;
    }

    .left {
        width: 300px;
        min-height: 583px;

        .item {
            display: block;
            width: 100%;
        }

        .left-item {
            padding: 10px 0;
            display: flex;
            align-items: center;
            cursor: pointer;

            .icon {
                border-radius: 100%;
                min-width: 40px;
            }

            .content {
                flex-grow: 1;
                margin-left: 5px;
                overflow: hidden;
                .name {
                    font-size: 16px;
                    color: #333;
                    overflow: hidden;
                    text-overflow: ellipsis;
                    white-space: nowrap;
                }

                .subtitle {
                    font-size: 12px;
                    color: #999;
                    margin-top: 5px;
                    overflow: hidden;
                    text-overflow: ellipsis;
                    white-space: nowrap;
                }
            }

            .time {
                font-size: 12px;
                color: #999;
                display: flex;
                flex-direction: column;
                text-align: right;
                min-width: 60px;
            }

            &:not(:last-child) {
                border-bottom: 1px solid #ebebeb;
            }

            .close {
                color: #999;
                display: none;
            }

            &:hover {
                .close {
                    display: block;
                }
            }
        }

        .nothing {
            text-align: center;
            padding: 30px;
            color: #999;
            font-size: 18px;
        }
    }

    .right {
        width: 800px;
        display: -webkit-box;
        display: -webkit-flex;
        display: -ms-flexbox;
        display: flex;
        -webkit-box-orient: column;
        -webkit-flex-direction: column;
        -ms-flex-direction: column;
        flex-direction: column;

        .chatList {
            // height: 425px;
            overflow: auto;
            // border-bottom: 1px solid #ebebeb;
            padding-bottom: 20px;
            -webkit-box-flex: 1;
            -webkit-flex: 1;
            -ms-flex: 1;
            flex: 1;
        }
        .inputContent {
            position: relative;
            .submit {
                position: absolute;
                bottom: 16px;
                right: 23px;
                width: 93px;
            }
        }
        .chat-item {
            display: flex;
            align-items: flex-start;
            margin-top: 10px;
            padding: 0 15px;
            .icon {
                min-width: 40px;
                margin: 0 20px;
                border-radius: 100%;
            }

            .chatInfo {
                // flex-grow: 1;

                padding: 10px 20px;
                font-size: 14px;
                font-weight: 400;
                color: rgb(12, 4, 4);
                line-height: 20px;
                border: 1px solid #979797;
                border-radius: 4px;
                margin-top: 18px;
            }
        }
    }

    .floatRight {
        position: absolute;
        right: 0px;
        top: 0px;
    }
}
</style>
