<template>
  <chat-box
    ref="chatbox"
    :group="group"
    :is-show="isShow"
    :tree-data="treeData"
    :conversition-id="conversitionId"
    :current-member-list="currentMemberList"
    :chat-content-list="chatContentList"
    :script-tip="scriptTip"
    :is-start-record="isStartRecord"
    :invite-user-name="inviteUserName"
    :is-quit-show="isQuitShow"
    @setScriptTip="setScriptTip"
    @resetCoversition="resetCoversition"
  />
</template>
<script>
import ChatBox from '../chatView/chatBox.vue';
import ConstConfig from '@/scripts/ConstConfig';
import Cookies from 'js-cookie';
import {getAllConversition} from '@/api/chat';
import { getSimulationMemberList} from '@/api/simulation';
export default {
    name:'ScriptChat',
    components:{
        ChatBox
    },
    props: {
        group: {
            type: String,
            required: true
        },
        userRole: {
            type: String,
            required: true
        }
    },
    data() {
        return {
            scriptTip:'',
            isHasCoversition:false,
            conversitionId:'',
            currentMemberList:[],
            memberData:{},
            chatContentList:[],
            activeTrainList:[],
            isStartRecord:false,
            inviteUserName:'',
            inviteUser:{},
            isQuitShow:false,
            treeData:[],
            driverList:[]
        };
    },
    computed:{
        isShow() {
            return this.userRole != '' &&
             this.userRole != 'ADMIN' && this.userRole != 'AUDIENCE' &&
            !this.isHasCoversition;
        }
    },
    watch:{
        '$store.state.map.mapViewLoadedCount': function (val) { // 地图视图加载完成标识 开始获取仿真成员
            getSimulationMemberList(this.group).then(resp => {
                let lastData = JSON.stringify(resp.data);
                const roleTypeList = ConstConfig.ConstSelect.roleTypeNew;
                roleTypeList.forEach(function(element) {
                    const rolename = element.value;
                    if (Cookies.get('user_lang') == 'en') {
                        lastData = lastData.replace(new RegExp(rolename, 'g'), element.enLabel);
                    } else {
                        lastData = lastData.replace(new RegExp(rolename, 'g'), element.label);
                    }
                });
                lastData = JSON.parse(lastData);
                const lastMemberList = [];
                const dispatcherList = [];
                // const electricDispatcherList = [];
                const depotDispatcherList = [];
                const stationSupervisorList = [];
                this.driverList = [];
                const maintainerList = [];
                const driverList = [];
                this.treeData = [];
                lastData.forEach((member, index)=>{
                    if (member.type != '观众') {
                        if (!member.userId) {
                            member.userId = '';
                            member.disabled = false;
                        } else {
                            member.disabled = true;
                        }
                        const name = member.name == undefined ? '' : '-' + member.name;
                        if (member.deviceCode) {
                            const device = this.$store.getters['map/getDeviceByCode'](member.deviceCode);
                            if (device) {
                                if (device._type == 'Train') {
                                    member.label = member.type + device.groupNumber + name;
                                    member.deviceName = member.deviceCode;
                                    lastMemberList.push(member);
                                    if (this.activeTrainList.length > 0) {
                                        if (this.activeTrainList.includes(member.deviceCode)) {
                                            driverList.push(member);
                                        }
                                    } else {
                                        this.driverList.push(member);
                                    }
                                } else {
                                    member.deviceName = device.name;
                                    member.label = member.type + device.name + name;
                                    lastMemberList.push(member);
                                    if (device._type == 'Station') {
                                        stationSupervisorList.push(member);
                                    }
                                }
                            } else {
                                member.deviceName = member.deviceCode;
                                member.label = member.type + member.deviceCode + name;
                                lastMemberList.push(member);
                            }
                        } else {
                            member.label = member.type + name;
                            if (member.type == '行调') {
                                dispatcherList.push(member);
                            } else if (member.type == '通号') {
                                maintainerList.push(member);
                            } else if (member.type == '车辆段调度') {
                                depotDispatcherList.push(member);
                            }
                            lastMemberList.push(member);
                        }
                    }
                });
                this.treeData = [{
                    label: '行调',
                    id: 'dispatcher',
                    type: 'role',
                    children: dispatcherList
                }, {
                    label: '车站值班员',
                    id: 'stationSupervisor',
                    type: 'role',
                    children: stationSupervisorList
                }, {
                    label: '司机',
                    id: 'driver',
                    type: 'role',
                    children: driverList
                }, {
                    label: '通号',
                    id: 'maintainer',
                    type: 'role',
                    children: maintainerList
                }, {
                    label: '车辆段',
                    id: 'depotDispatcher',
                    type: 'role',
                    children: depotDispatcherList
                }];
                this.memberData = lastMemberList;
            }).catch(() => {
                this.$messageBox('获取仿真成员列表失败！');
            });
        },
        'userRole':function(val, oldval) {
            // 切换对象
            this.changeRole(oldval, val);
        },
        '$store.state.scriptRecord.updateRoleStatus':function(val) {
            // 切换对象
            this.changeRole(this.$store.state.scriptRecord.userRole, this.$store.state.scriptRecord.userRole);
        },
        // 按计划行车的列车列表更新(更新司机列表)
        '$store.state.map.activeTrainListChange': function (val) {
            const activeTrainList = this.$store.state.map.activeTrainList;
            if (this.driverList.length > 0) {
                const driverList = [];
                if (activeTrainList && activeTrainList.length) {
                    activeTrainList.forEach(groupNumber => {
                        const drivers = this.driverList.find(driver=>{
                            return driver.deviceCode == groupNumber;
                        });
                        if (drivers) {
                            driverList.push(drivers);
                        }
                    });
                }
                this.treeData[2].children = driverList;
            } else {
                this.activeTrainList = activeTrainList;
            }
        },
        // 创建会话
        '$store.state.socket.createConversition':function(val) {
            if (this.memberData.length > 0) {
                const member = this.memberData.find(member=>{ return member.id == val.creatorId; });
                if (member && member.userId == this.$store.state.user.id) {
                    // 当前用户创建的会话
                    this.isHasCoversition = true;
                    this.isStartRecord = true;
                    this.isQuitShow = true;
                    this.conversitionId = val.id;
                    const memberList = [];
                    val.memberIds.forEach(id=>{
                        if (val.creatorId == id) {
                            member.connect = true;
                            memberList.push(member);
                        } else {
                            const member = this.memberData.find(member=>{ return member.id == id; });
                            member.connect = false;
                            member && memberList.push(member);
                        }
                    });
                    this.currentMemberList = memberList;
                } else {
                    // 如果是观众看所有人的会话
                    if (this.userRole == 'AUDIENCE') {
                        this.isHasCoversition = true;
                        this.currentMemberList = this.memberData;
                    }
                }
            }
        },
        // 用户接受会话
        '$store.state.socket.acceptConversionInvite':function(val) {
            this.conversitionId = val.id;
            if (this.conversitionId) {
                // 更改成员列表里面的成员状态
                const memberList = this.currentMemberList.map(member => {
                    if (member.id == val.memberId) {
                        member.connect = true;
                    }
                    return member;
                });
                this.currentMemberList = memberList;
            }
        },
        // 会话聊天消息
        '$store.state.socket.conversationInfo':function (val, old) { //  仿真聊天
            const simulationText = this.$store.state.socket.conversationInfo;
            if (val.messageType == 'MESSAGE' && (this.conversitionId == val.id || this.userRole == 'AUDIENCE')) {
                this.chatContentList.push(this.addContent(simulationText.message));
            }
        },
        '$store.state.scriptRecord.updateCoversitionStatus':function(val) {
            // 更改会话信息
            this.getAllConversition();
        }
    },
    methods:{
        setScriptTip(scriptTip) {
            this.scriptTip = scriptTip;
        },
        addContent(simulationText) {
            const text = {};
            const member = this.currentMemberList.find(member=>{
                return member.id == simulationText.memberId;
            });
            if (member) {
                text.self = (this.$store.state.user.id == member.userId);
                text.member = member;
                text.chatTime = simulationText.time;
                text.src = simulationText.audioPath;
                text.message = simulationText.content;
            }
            return text;
        },
        resetCoversition() {
            this.conversitionId = '';
            this.scriptTip = '';
            this.isHasCoversition = false;
            this.currentMemberList = [];
            this.chatContentList = [];
            this.isStartRecord = false;
            this.inviteUserName = '';
            this.inviteUser = {};
            this.isQuitShow = false;
        },
        changeRole(oldval, val) {
            const userList = ['DISPATCHER', 'STATION_SUPERVISOR', 'DRIVER', 'MAINTAINER', 'DEPOT_DISPATCHER'];
            // 切换对象   待优化
            this.getAllConversition();
            const oldIndex = userList.indexOf(oldval);
            if (oldIndex >= 0) {
                this.treeData[oldIndex].children.forEach(child=>{
                    if (child.userId) {
                        child.userId = '';
                        child.disabled = false;
                        child.label = child.type + (child.deviceName ? child.deviceName : '');
                    }
                });
            }
            const index = userList.indexOf(val);
            if (index >= 0) {
                this.treeData[index].children.forEach(child=>{
                    if (child.id == this.$store.state.scriptRecord.updateRoleId) {
                        child.userId = this.$store.state.user.id;
                        child.disabled = true;
                        child.label = child.label + '-' + this.$store.state.user.nickname;
                    }
                });
            }
        },
        getAllConversition() {
            // 获取会话列表
            getAllConversition(this.$route.query.group).then(resp=>{
                let isHasCoversition = false;
                let isQuitShow = false;
                if (resp.data && resp.data.length && resp.data.length > 0) {
                    const coversitionList = resp.data;
                    let memberList = [];
                    let messageList = [];
                    coversitionList.forEach(coversition=>{
                        // 会话是否结束
                        if (!coversition.over) {
                            coversition.memberList.forEach(member=>{
                                if (member.memberId == this.$store.state.scriptRecord.updateRoleId) {
                                    if (member.memberId == coversition.creatorId) {
                                        isQuitShow = true;
                                    }
                                    isHasCoversition = true;
                                    memberList = coversition.memberList;
                                    messageList = coversition.messageList;
                                    this.conversitionId = coversition.id;
                                    this.isStartRecord = true;
                                }
                            });
                        }
                    });
                    this.currentMemberList = [];
                    memberList.forEach(memberSimple=>{
                        const member = this.memberData.find(member=>{ return member.id == memberSimple.memberId; });
                        member.connect = memberSimple.connect;
                        member && this.currentMemberList.push(member);
                    });
                    this.chatContentList = [];
                    messageList.forEach(message=>{
                        this.chatContentList.push(this.addContent(message));
                    });
                }
                this.isHasCoversition = isHasCoversition;
                this.isQuitShow = isQuitShow;
            });
        }
    }
};
</script>
