<template>
  <div class="box">
    <div class="relation" :style="{ width: widthLeft +'px' }">
      <drap-left :width-left="widthLeft" :max="300" :min="180" :width="6" :is-save="false" @drapWidth="drapWidth" />
      <el-scrollbar wrap-class="scrollbar-wrapper" :style="{ height: '290px' }">
        <el-tree
          ref="personTree"
          :data="treeData"
          :props="defaultProps"
          node-key="nodeId"
          :default-expanded-keys="keyIdList"
          @node-click="chatClick"
          @node-contextmenu="showContextMenu"
        >
          <!-- <span slot-scope="{ node, data }">
                        <div style="height: 20px;" v-show="data.show">
                            <el-badge is-dot class="item-point">
                                <span style="font-size: 14px; color: #606266; cursor: pointer;">
                                    {{ formatName(data) }}
                                </span>
                            </el-badge>
                        </div>
                        <div v-show="!data.show">
                            <span style="font-size: 14px; color: #606266; cursor: pointer;">
                                {{ formatName(data) }}
                            </span>
                        </div>
                    </span> -->
        </el-tree>
      </el-scrollbar>
    </div>
    <operate-menu
      ref="operateMenu"
      :group="group"
      :point="point"
      :selected="selected"
      :driver-list="driverList"
      :driver-map-dict="driverMapDict"
    />
  </div>
</template>

<script>
import Vue from 'vue';
import ChartWindow from './chatWindow';
import DrapLeft from '@/views/components/drapLeft/index';
import OperateMenu from './menuDraft/operateMenu';
import ModelType from '@/jmap/constant/deviceType';
import { mapGetters } from 'vuex';
import { DeviceMenu } from '@/scripts/ConstDic';
import { getHistoryVoice, getJointTrainRoomUserList, getUserRoles, putUserRoles } from '@/api/chat';
import { EventBus } from '@/scripts/event-bus';

export default {
	name: 'ChartView',
	components: {
		ChartWindow,
		DrapLeft,
		OperateMenu
	},
	props: {
		group: {
			type: String
		},
		stationList: {
			type: Array
		}
	},
	data() {
		return {
			widthLeft: 180,
			userId: '',
			code: '',
			label: '',
			selected: {},
			message: {},
			data: {}, // 数据内容
			userRole: '', // 个人权限
			userList: [], // 观众列表
			driverList: [], // 司机列表
			treeData: [ // 角色列表 顺序定死
				{
					children: [],
					name: '管理员',
					nodeId: 'admin01',
					type: 'select',
					show: false
				},
				{
					children: [],
					name: '教员',
					nodeId: 'admin02',
					type: 'select',
					show: false
				},
				{
					children: [],
					name: '调度员',
					nodeId: 'admin03',
					type: 'select',
					show: false
				},
				{
					children: [],
					name: '车站值班员',
					nodeId: 'admin04',
					type: 'select',
					show: false
				},
				{
					children: [],
					name: '列车',
					nodeId: 'admin05',
					type: 'select',
					show: false
				},
				{
					children: [],
					name: '通号',
					nodeId: 'admin06',
					type: 'select',
					show: false
				}
			],
			defaultProps: {
				children: 'children',
				label: this.formatName
			},
			driverMapDict: {},
			keyIdList: [],
			messageList: [],
			point: {
				x: 0,
				y: 0
			}
		};
	},
	watch: {
		'stationList': async function (val) { // 执行一次 以后不会有变化
			if (val) {
				await this.getUserList();
				this.initMenu(val);
			}
		},
		'$store.state.socket.roleInfo': function (val) { //  仿真聊天
			val.forEach(item => {
				this.treeData[4].children.forEach(elem => {
					if (elem.driver && item.userRole == 'Driver' && elem.driver.id == item.id) {
						this.selected = elem;
					}
				});
			});
		},
		'$store.state.training.simulationGroupCount': async function () {
			await this.loadRunData();
		}
	},
	created() {
		EventBus.$on('trainView', this.updateTrainList);
	},
	beforeDestroy() {
		EventBus.$off('trainView');
	},
	methods: {
		async loadRunData() {
			await this.getUserList();

			EventBus.$on('trainView', this.updateTrainList);

			this.getUserRole();
		},
		formatName(data, node) {
			let name = data.name ? data.name : data.groupNumber;
			if (data.driver) {
				name = `${name}(${data.driver.nickName})`;
			}

			return name;
		},
		drapWidth(width) {
			this.widthLeft = Number(width);
		},
		// 获取设备集中站
		initMenu(list) {
			this.treeData[3].children = [];
			list.forEach(station => {
				if (station.centralized) {
					const param = {
						name: station.name,
						code: station.code,
						id: '',
						nodeId: station.code,
						children: null,
						show: false,
						index: 3
					};
					this.treeData[3].children.push(param);
				}
			});

			this.userList.forEach(item => {
				if (item.userRole == 'Attendant') {
					this.treeData[3].children.forEach(nor => {
						if (nor.code == item.stationCode) {
							nor.name = `${nor.name}【${item.nickName}】`;
							nor.id = item.id;
							nor.nodeId = item.id;
						}
					});
				}
			});
		},
		// 获取人成员列表
		async getUserList() {
			const rest = await getJointTrainRoomUserList(this.group);
			this.userList = rest.data;
			this.treeData[0].children = [];
			this.treeData[1].children = [];
			this.treeData[2].children = [];
			this.treeData[5].children = [];
			this.driverMapDict = {};
			this.driverList = [];

			this.userList.forEach(item => {
				const param = {
					name: item.nickName,
					id: item.id,
					nodeId: item.id,
					children: null,
					show: false,
					index: ''
				};

				if (item.userRole == 'Admin') {
					param.index = 0;
					this.treeData[0].children.push(param);
				} else if (item.userRole == 'Instructor') {
					param.index = 1;
					this.treeData[1].children.push(param);
				} else if (item.userRole == 'Dispatcher') {
					param.index = 2;
					this.treeData[2].children.push(param);
				} else if (item.userRole == 'Driver') {
					param.index = 4;
					this.driverList.push(param);
				} else if (item.userRole == 'Repair') {
					param.index = 5;
					this.treeData[5].children.push(param);
				}
			});

			this.updateDriverInfo(this.userList);
		},
		// 点击左侧人员并选择
		async chatClick(obj) {
			if (obj.type && obj.type == 'select') {
				obj.show = false;
				this.$emit('showChatNone');
			} else {
				if (obj.show) {
					let data = {};
					this.messageList.forEach((item, index) => {
						if (item.member.id == obj.id) {
							data = item;
							this.messageList.splice(index, 1);
						}
					});

					this.$emit('showChatSpeak', data);
					this.treeData[obj.index].show = false;
					obj.show = false;
				} else {
					this.updateConversationId(obj);
				}
			}
		},
		// 获取个人权限
		async getUserRole() {
			const res = await getUserRoles(this.group);
			this.userRole = res.data.userRole;
			if (this.userRole != 'Audience' && this.userRole != '') {
				await this.getUserList();
				this.initMenu(this.stationList);
			}
		},
		// 更新聊天的回话Id
		updateConversationId(obj) {
			let id = obj.id;
			const code = obj.code || obj._code;
			if (obj.driver) {
				id = obj.driver.id;
			}

			if (code || id) {
				this.$emit('showChat', { code: code, id: id });
			}
		},
		// 更新列车列表
		updateTrainList() {
			const list = this.$store.getters['training/viewTrainList']();
			if (this.treeData[4].children.length != list.length) {
				this.treeData[4].children = [];
				if (list && list.length) {
					list.sort((a, b) => {
						return Number(a.groupNumber) - Number(b.groupNumber);
					});

					list.forEach(item => {
						item.driver = this.driverMapDict[item._code];
						item.nodeId = item._code;
						item.show = false;
						item.index = 4;
						this.treeData[4].children.push(item);
					});

					this.$refs.personTree.updateKeyChildren('admin05', this.treeData[4].children.slice());
				}
			}
		},
		// 更新司机信息
		updateDriverInfo(list) {
			this.updateConversationId(this.selected);
			list.forEach(item => {
				if (item.userRole == 'Driver') {
					if (item.trainCode) {
						// 添加司机
						this.driverMapDict[item.trainCode] = item;
					} else {
						// 取消司机
						Object.keys(this.driverMapDict).forEach(key => {
							const oDriver = this.driverMapDict[key];
							const nDriver = this.selected.driver;
							if (oDriver && nDriver && oDriver.id == nDriver.id) {
								delete this.driverMapDict[key];
							}
						});
					}
				}
			});

			this.treeData[4].children = [];
			this.updateTrainList();
		},
		// 右键显示设置司机菜单
		showContextMenu(e, obj, node, vueElem) {
			if (this.$store.state.map.roles == 'Admin') {
				e.preventDefault();
				this.point = {
					x: e.clientX,
					y: e.clientY
				};

				if (obj._type == ModelType.Train) {
					this.selected = obj;
					this.$store.dispatch('menuOperation/setPopMenu', { position: this.point, menu: DeviceMenu.SetDriver });
				}
			}
		},
		select(id) {
			this.keyIdList = [];
			this.$refs.personTree.setCurrentKey(null);
			if (id) {
				this.keyIdList = [id];
				this.$refs.personTree.setCurrentKey(id);
				const node = this.$refs.personTree.getCurrentNode();
				if (node) {
					node.show = false;
					this.treeData[node.index].show = false;
				}
			}
		},
		hintInfo(data) {
			switch (data.member.role) {
			case '01': {
				this.treeData[0].show = true;
				this.treeData[0].children.forEach(nor => {
					if (nor.id == data.member.id) {
						nor.show = true;
					}
				});
			} break;
			case '02': {
				this.treeData[1].show = true;
				this.treeData[1].children.forEach(nor => {
					if (nor.id == data.member.id) {
						nor.show = true;
					}
				});
			} break;
			case '03': {
				this.treeData[2].show = true;
				this.treeData[2].children.forEach(nor => {
					if (nor.id == data.member.id) {
						nor.show = true;
					}
				});
			} break;
			case '04': {
				this.treeData[3].show = true;
				this.treeData[3].children.forEach(nor => {
					if (nor.id == data.member.id) {
						nor.show = true;
					}
				});
			} break;
			case '05': {
				this.treeData[4].show = true;
			} break;
			case '06': {
				this.treeData[4].show = true;
				this.treeData[4].children.forEach(nor => {
					if (nor.driver && nor.driver.id == data.member.id) {
						nor.show = true;
					}
				});
			} break;
			case '07': {
				this.treeData[5].show = true;
				this.treeData[5].children.forEach(nor => {
					if (nor.id == data.member.id) {
						nor.show = true;
					}
				});
			} break;
			}
			this.messageList.push(data);
		}
	}
};
</script>
<style>
    .el-tree {
        overflow-x: hidden;
    }
</style>
<style rel="stylesheet/scss" lang="scss" scoped>
    /deep/ {
        .el-tabs__nav {
            margin-left: 18px;
        }

        .el-tree-node.is-current>.el-tree-node__content {
            background-color: #b9f1f1 !important;
        }

        .el-tree-node:focus>.el-tree-node__content {
            background-color: none;
        }

        .item-point {
            .el-badge__content {
                right: -5px;
                top: 11px;
            }
        }
    }

    #nav {
        padding: 30px;
        text-align: center;
    }

    #nav a {
        font-weight: bold;
        color: #2c3e50;
    }

    #nav a.router-link-exact-active {
        color: #42b983;
    }

    ::-webkit-scrollbar {
        width: 3px;
    }

    ::-webkit-scrollbar-thumb {
        background-color: #c7c7c7;
    }

    .box {
        display: flex;
        justify-content: center;
        z-index: 10;
        position: relative;
    }

    .relation {
        width: 180px;
        float: left;
        height: 300px;

        .personnel {
            width: 100%;
            font-size: 16px;
            line-height: 20px;
            padding-left: 5px;
            cursor: pointer;
            padding: 3px 8px;

            &:hover {
                background-color: #e6e6e6;
            }
        }
    }
</style>
