<template>
  <div class="roles">
    <div class="roles__head">
      <div class="roles__head--title">
        <div class="label">人员分配</div>
        <div class="notes">{{ room.permissionRest }} / {{ room.permissionNum - 1 }}</div>
      </div>
      <div class="roles__head--reset">
        <!--<el-button size="mini" round>重置</el-button>-->
      </div>
    </div>
    <div class="roles__container">
      <el-scrollbar wrap-class="scrollbar-wrapper" :style="{height: rolesHeight+'px', width: '100%'}">
        <div class="roles">
          <e-role
            class="role"
            title-i18n="trainRoom.dispatcher"
            role-type="Dispatcher"
            :room="room"
            :options="dispatcherList"
            @addUser="handleAddUser"
            @changeUser="handleUpdUser"
            @delUser="handleDelUser"
          />
          <e-role
            class="role"
            title-i18n="trainRoom.stationAttendant"
            role-type="Attendant"
            :room="room"
            :options="attendantList"
            :device-list="stationListForAttendant"
            @addUser="handleAddUser"
            @changeUser="handleUpdUser"
            @delUser="handleDelUser"
          />
          <e-role
            class="role"
            title-i18n="trainRoom.teacher"
            role-type="Instructor"
            :room="room"
            :options="instructorList"
            @addUser="handleAddUser"
            @changeUser="handleUpdUser"
            @delUser="handleDelUser"
          />
          <e-role
            class="role"
            title-i18n="trainRoom.universalAccount"
            role-type="Repair"
            :room="room"
            :options="repairList"
            @addUser="handleAddUser"
            @changeUser="handleUpdUser"
            @delUser="handleDelUser"
          />
          <e-role
            class="role"
            title-i18n="trainRoom.driver"
            role-type="Driver"
            :room="room"
            :options="driverList"
            @addUser="handleAddUser"
            @changeUser="handleUpdUser"
            @delUser="handleDelUser"
          />
          <e-role
            class="role"
            title-i18n="trainRoom.ibp"
            role-type="IBP"
            :room="room"
            :options="ibpList"
            :device-list="stationListForIBP"
            @addUser="handleAddUser"
            @changeUser="handleUpdUser"
            @delUser="handleDelUser"
          />
          <e-device
            class="role"
            title-i18n="trainRoom.realDevice"
            device-type="StationStand"
            :room="room"
            :options="standList"
            :device-list="doorList"
            :has-plc="hasPlc"
            @addDevice="handleAddDevice"
            @changeDevice="handleUpdDevice"
            @delDevice="handleDelDevice"
          />
        </div>
      </el-scrollbar>
    </div>
    <div class="roles__footer">
      <el-button v-if="userId == room.creatorId" style="margin-left: 10px" type="danger" :loading="loading" @click="handleExit">{{ $t('trainRoom.destroyRoom') }}</el-button>
      <el-button v-if="userId == room.creatorId" style="margin-left: 10px" type="success" :loading="loading" @click="handlePostQrcode">{{ $t('trainRoom.generatingQRCode') }}</el-button>
      <template v-if="!starting">
        <el-button v-if="userId == room.creatorId" style="margin-left: 10px" type="primary" :loading="loading" @click="handleStart"> {{ $t('trainRoom.startSimulation') }}</el-button>
      </template>
      <template v-else>
        <el-button type="primary" style="margin-left: 10px" :loading="loading" @click="handleJoinTraining"> {{ $t('trainRoom.enterSimulation') }}</el-button>
        <el-button v-if="userId == room.creatorId" style="margin-left: 10px" type="warning" :loading="loading" @click="handleStop"> {{ $t('trainRoom.endSimulation') }}</el-button>
      </template>
      <el-button type="" @click="handleBack">{{ $t('global.back') }}</el-button>
    </div>
    <add-person ref="addPerson" :audience-list="audienceList" @dispatch="handleDispatchUser" />
    <qr-code ref="qrCode" />
  </div>
</template>

<script>
import eRole from './e-role';
import eDevice from './e-device';
import AddPerson from './add-person';
import QrCode from '@/components/QrCode';
import { getJoinTrainCode, startJointTraining, deljointTrainRoom, putJointTrainingExit, putJointTrainingSimulation, putUserRoles, setRealDevice, delRealDevice } from '@/api/chat';
import { getPlcGateway } from '@/api/simulation';

export default {
    components : {
        eRole,
        eDevice,
        AddPerson,
        QrCode
    },
    props: {
        room: {
            type: Object,
            required: true
        },
        members: {
            type: Array,
            required: true
        },
        height: {
            type: Number,
            required: true
        },
        stationList: {
            type: Array,
            default() {
                return [];
            }
        },
        standList: {
            type: Array,
            default() {
                return [];
            }
        },
        doorList: {
            type: Array,
            default() {
                return [];
            }
        }
    },
    data() {
        return {
            loading: false,
            hasPlc: false
        };
    },
    computed: {
        rolesHeight() {
            return this.height - 100;
        },
        group() {
            return this.$route.query.group;
        },
        userId() {
            return this.$store.state.user ? this.$store.state.user.id : '';
        },
        starting() {
            return this.room.state == '02';
        },
        stationListForAttendant() {
            return this.stationList.filter(elem => { return elem.centralized; }).map(item => {
                const elem = { code: item.code, name: item.name, disabled: false };
                this.attendantList.forEach(nor => {
                    if (elem.code == nor.deviceCode) {
                        elem.disabled = true;
                    }
                });
                return elem;
            });
        },
        stationListForIBP() {
            return this.stationList.map(item => {
                const elem = { value: item.code, label: item.name, children: [{value: 'left', label: this.$t('trainRoom.left')}, {value: 'right', label: this.$t('trainRoom.right')}] };
                return elem;
            });
        },
        dispatcherList() {
            return this.members.filter(elem => { return [elem.userRole].includes('Dispatcher'); });
        },
        attendantList() {
            return this.members.filter(elem => { return [elem.userRole].includes('Attendant'); });
        },
        instructorList() {
            return this.members.filter(elem => { return [elem.userRole].includes('Instructor'); });
        },
        repairList() {
            return this.members.filter(elem => { return [elem.userRole].includes('Repair'); });
        },
        driverList() {
            return this.members.filter(elem => { return [elem.userRole].includes('Driver'); });
        },
        ibpList() {
            return this.members.filter(elem => { return [elem.userRole].includes('IBP'); });
        },
        audienceList() {
            return this.members.filter(elem => { return [elem.userRole].includes('Audience'); });
        }
    },
    async mounted() {
        await this.checkPlcGateway();
    },
    methods: {
        async checkPlcGateway() {
            try {
                const resp = await getPlcGateway(this.group);
                this.hasPlc = !!resp.data;
            } catch (e) {
                this.hasPlc = false;
                this.$messageBox(this.$t('error.inquiryPLCDeviceFailed'));
            }
        },
        async handlePostQrcode() {
            this.loading = true;
            const res = await getJoinTrainCode({}, this.group);
            if (res.code == '200') {
                const param = {
                    url: res.data,
                    title: this.$t('trainRoom.distributeTheRoomQRCode')
                };
                if (this.$refs) {
                    this.$refs.qrCode.doShow(param);
                }
            }
            this.loading = false;
        },
        async handleJoinTraining() {
            this.$emit('joinTraining');
        },
        async handleAddDevice({deviceType}) {
            const roomDeviceVo = {id: '', deviceType: 'ScreenDoor', deviceCode: ''};
            if (this.standList.findIndex(elem => { return elem.deviceType == roomDeviceVo.deviceType; }) > -1) {
                this.$message.info(this.$t('error.theDeviceTypeAlreadyExists'));
                return;
            }

            await setRealDevice(this.group, roomDeviceVo);
        },
        async handleUpdDevice({deviceType, device}) {
            try {
                await setRealDevice(this.group, device);
            } catch (e) {
                this.$messageBox(this.$t('error.connectToRealDeviceFailed'));
            }
        },
        async handleDelDevice({deviceType, device}) {
            try {
                await delRealDevice(device.id, this.group);
            } catch (e) {
                this.$messageBox(this.$t('error.deleteRealDeviceFailed'));
            }
        },
        async handleAddUser({roleType}) {
            this.$refs.addPerson.doShow(roleType);
        },
        async handleDelUser({roleType, user}) {
            const params = [{
                id: user.id,
                nickName: user.nickName,
                userRole: 'Audience',
                deviceCode: ''
            }];

            await putUserRoles(params, this.group);
        },
        async handleUpdUser({roleType, user, deviceList}) {
            let deviceCode = '';
            if (roleType === 'IBP') {
                user.ibpPart = user.deviceCode[1];
                deviceCode = user.deviceCode[0];
            } else {
                user.ibpPart = '';
                deviceCode = user.deviceCode;
            }

            const params = [{
                id: user.id,
                nickName: user.nickName,
                userRole: roleType,
                deviceCode: deviceCode,
                ibpPart: user.ibpPart
            }];

            await putUserRoles(params, this.group);

            this.stationList.forEach(item => {
                item.disabled = false;
                deviceList.forEach(nor => {
                    if (item.code === nor.deviceCode) {
                        item.disabled = true;
                    }
                });
            });
        },
        async handleDispatchUser({roleType, userList}) {
            const list = userList.map(elem => { return { id: elem.id, nickName: elem.nickName, userRole: roleType }; });
            if (list.length) {
                try {
                    await putUserRoles(list, this.group);
                    list.forEach(item => {
                        this.treeData.forEach(nor => {
                            if (item.id == nor.id) {
                                nor.userRole = item.userRole;
                            }
                        });
                    });
                } catch (error) {
                    if (error.code == 500009) {
                        this.messageInfo({error:'error', message: this.$t('error.exceededTheTotalNumberOfAssignableRoles')} );
                    }
                }
            }
        },
        async handleStart() {
            this.loading = true;
            if (this.attendantList.findIndex(item => { return !item.deviceCode; }) < 0) {
                try {
                    await startJointTraining(this.group);
                    this.loading = false;
                } catch (error) {
                    this.$emit('message', {type:'error', message: this.$t('error.startedComprehensiveDrillFailure')});
                    this.loading = false;
                }
            } else {
                this.$emit('message', {type:'error', message: this.$t('error.stationAttendantStationCannotBeEmpty')});
                this.loading = false;
            }
        },
        async handleStop() {
            this.loading = true;
            const res = await putJointTrainingSimulation(this.group);
            this.mapId = res.data.mapId;
            this.loading = false;
        },
        async handleExit() {
            this.loading = false;
            this.$confirm( this.$t('tip.destroyRoomHint'), this.$t('tip.hint'), {
                confirmButtonText: this.$t('global.confirm'),
                cancelButtonText: this.$t('global.cancel'),
                type: 'warning'
            }).then(async () => {
                try {
                    await deljointTrainRoom(this.group);
                } catch (error) {
                    this.$emit('message', {type:'error', message: this.$t('error.destroyedRoomFailed')});
                }
            });
        },
        async handleBack() {
            try {
                this.loading = true;
                await putJointTrainingExit(this.group);
                this.loading = false;
                history.go(-1);
            } catch (error) {
                this.$emit('message', {type:'error', message: this.$t('error.operationFailure')});
            }
        }
    }
};
</script>

<style scoped lang="scss">
	.roles {
		display: flex;
		flex-direction: column;
		background: #fff;

		&__head {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 0 30px;
			border-top: 1px solid #ccc;
			box-shadow: 0 3px 3px #ccc;
			background: #F0F0F0;

			&--title {
				display: flex;
				align-items: flex-end;
                padding: 10px 0px;

				.label {
					font-size: 16px;
					font-weight: bold;
					border-left: 5px solid #CF2727;
					padding: 0 5px
				}

				.notes {
					font-size: 12px;
					padding: 0 5px
				}
			}

			&--reset {
				.el-button {
					background: #CF2727;
					color: #fff;
				}
			}
		}

		&__container {
			display: flex;
			flex-grow: 1;
			padding: 5px 10px;
			.roles {
				display: flex;
				justify-content: space-around;
				flex-flow: row wrap;
				flex-grow: 1;

				.role {
					display: flex;
					flex-basis: 340px;
					margin-top: 20px;
				}
			}
		}

		&__footer {
			height: 60px;
			display: flex;
			padding: 0 30px;
			align-items: center;
			border-top: 1px solid #ccc;
			border-bottom: 1px solid #ccc;
		}
	}
</style>
