import controlData from '../data/control';
import userControlData from '../data/userContral';
import messageControlData from '../data/message-control';
import verification, {VerificationType} from '$utils/verification/index';
import socket from "$utils/socket/index";
import MessageType from "$utils/socket/const/messageType";
import user from '$config/user';
import {NoticeType} from "$utils/socket/const";
import giveGift from "$utils/control/giveGift";
import personalDetail, {OpenType} from '$utils/control/personal-detail';

export default <LibMixins>{

    data(){
        return {
            controlData,
            userControlData,
            messageControlData,
            userInfo:{},
            message:'',
            messageData:[],
            loadingStatus:true,
            opacity:0
        }
    },

    provide(){
      return {
          addMessage:(message:string)=> this.addMessage(message)
      }
    },

    watch:{
      uid:{
          handler(){
            if (this.uid && this._uid !== this.uid) {



                socket.off('chat-content',NoticeType.message,{
                    userId: (this._uid || '').toString()
                });

                this._uid = this.uid;

                this.userInfo = {};

                this.opacity = 0;

                socket.on('chat-content',(item)=> this.watchMessage(item),NoticeType.message,{
                    userId: this.uid.toString()
                });

                return  this.fetch();
            }
          },
          immediate:true
      }

    },

    computed:{
        nowUserInfo(){
            if (this.userInfo.uid) {
                return this.userInfo;
            } else {
                return this.useUserInfo || {};
            }
        },
        allUserInfo(){
          let users = [this.user,this.nowUserInfo];
          let usersObject = {};
          users.map((item)=>{
              usersObject[item.uid] = item;
          });

          return usersObject;
      },
      nowUid(){
         return this.user.uid;
      }
    },

    methods:{

        goRoomInfo(){
            if (this.nowUserInfo.stay_roominfo){
                this.$emit('close');
                personalDetail.openDetail(this.nowUserInfo.stay_roominfo,OpenType.room);
            }
        },

        watchMessage(item){
            // 清楚未读消息
            this.socketUser && this.socketUser.read();
            this.messageData.push(this.getMessageItem(item));
            return this.sendMessageScroll();
        },

        fetch() {

            this.giftModal = false;

            this.loadingStatus = true;

            this.socketUser = socket.getConversation(this.uid);

            let requestUnique = +new Date() + '-'+Math.ceil(Math.random() * 10000);

            this.requestUnique = requestUnique;

            this.messageData = [];

            // 加载历史记录
            this.statusFetch(true,{
                unique:requestUnique
            });

            return this.getUserInfo(requestUnique);

        },

        // 获取历史消息
        getMessages(obj){

            this.socketUser.getMessages({
                timestamp: this.lastTime,
                count:obj.data.pageSize
            }).then((data)=>{
                if (obj.data.unique === this.requestUnique) {
                    data.list = data.list || [];

                    // 最后的时间
                    this.lastTime = data.list[data.list.length - 1] &&  data.list[data.list.length - 1].receivedTime;

                    data.list = data.list.map((item)=>{
                        return this.getMessageItem(item);
                    });

                    this.messageData.unshift(...data.list);

                    this.scrollToEnd(true);
                }


            }).catch(()=>{
                obj.fail();
                this.opacity = 1;
            });
        },

        // 设置消息
        getMessageItem(item){

            let uid = item.senderUserId == user.uid() ? user.uid() : this.nowUserInfo.uid;
            let toUserId = item.senderUserId == user.uid() ? this.nowUserInfo.uid : user.uid();

            return {
                ...item.content,
                type:item.messageType,
                toUserId: toUserId.toString(),
                uid: uid.toString(),
            }
        },

        sendGift(gift,number,userInfo){

            if (gift && number && userInfo && userInfo.uid === this.nowUserInfo.uid) {
                this.messageData.push({
                    gift,
                    number,
                    type:MessageType.gift,
                    uid:user.uid(),
                    toUserId: userInfo.uid
                });
                this.sendMessageScroll();
            }

        },

        addMessage(useMessage:string){
            let message = this.message + useMessage;

            if (this.message !== message) {
                this.message = message;
            }
        },

        sendMessage(){

            if (this.message && verification.trigger[VerificationType.empty](this.message)) {

                this.messageData.push({
                    message:this.message,
                    type:MessageType.text,
                    uid:user.uid(),
                    toUserId: this.nowUserInfo.uid
                });

                this.sendMessageScroll();
                this.sendText(this.message);

                this.message = '';


            }

        },

        sendText(message){
            if (this.socketUser) {
                this.socketUser.send({
                    messageType: MessageType.text, // 'RC:TxtMsg'
                    content:socket.addUser({
                        message:message,
                    },this.nowUserInfo)
                });
            }
        }
    },

    created(){
        this.lastTime = +new Date();
        giveGift.content = this;
    },

    beforeUnmount() {
        socket.off('chat-content',NoticeType.message,{
            userId: (this._uid || '').toString()
        });
        giveGift.content = undefined;
    }
}

