<template>
  <div>
    <div class="scriptRecordNew" :style="{bottom:(offsetBottom-15)+'px'}">
      <div v-show="isShow" class="scriptRecordNewIn">
        <el-tabs type="card">
          <el-tab-pane :label="$t('scriptRecord.scriptRecordTitle')+'('+language+')'">
            <div class="eachScriptPanel">
              <div class="scriptPanelLeft">
                <div class="panelLeftSelect">
                  <div>
                    <span style="font-size:13px;">当前剧本角色:</span>
                    <span style="font-size:13px;">{{ getRoleName(memberId) }}</span>
                  </div>
                  <div class="quickChange">
                    <!-- <div class="quickChange_head">快捷切换</div> -->
                    <div class="quickChangeList" style="margin:10px 0px 10px 0px;overflow-y:auto;height:200px;">
                      <div v-for="member in quickChangeMember.list" :key="member.id" class="setGroupOut">
                        <span style="font-size: 14px">{{ member.normalName }}</span>
                        <span class="setGroup">
                          <span v-if="member.userId" class="hasSetted">已设置</span>
                          <span v-else class="settingBtn" @click="changeRole(member)">设置</span>
                        </span>
                      </div>
                    </div>
                  </div>
                </div>
                <el-button-group class="button-group">
                  <el-button v-if="isPause" size="small" type="primary" :disabled="executeDisabled" @click="pauseScript">{{ $t('scriptRecord.drivingPause') }}</el-button>
                  <el-button v-else size="small" type="primary" :disabled="executeDisabled" @click="executePlayScript">恢复</el-button>
                  <el-button size="small" type="danger" :disabled="!backDisabled" @click="dumpScenesData">{{ $t('scriptRecord.resetScript') }}</el-button>
                  <el-button size="small" type="primary" :disabled="backDisabled" @click="saveScenesStage">{{ $t('scriptRecord.saveBackground') }}</el-button>
                  <el-button size="small" type="success" :loading="isSavingScript" @click="saveScenesData">{{ $t('scriptRecord.saveData') }}</el-button>
                </el-button-group>
              </div>
              <div class="scriptPanelRight">
                <get-action-new ref="getAction" :group="group" :size="size" :member-list="memberList" @setAction="setAction" />
              </div>
            </div>
          </el-tab-pane>
          <el-tab-pane label="所有成员">
            <div class="eachScriptPanel">
              <all-script-role
                ref="allScriptRole"
                :member-id="memberId"
                :tree-data="treeData"
                :group="group"
                @setMemberId="setMemberId"
                @addMember="addMember"
              />
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
      <div class="scriptRecordNewTitle" @click="minisize">
        <span class="titleStyle">{{ $t('scriptRecord.scriptRecordTitle') }}</span>
      </div>
    </div>
    <add-script-member ref="addScriptMember" @addScriptMember="addScriptMember" />
  </div>
</template>
<script>
import Vue from 'vue';
import GetActionNew from './getAction';
import {executeScriptNew, dumpScriptDataNew, saveScriptDataNew, saveScriptScenesNew, updateMapLocationNew, simulationPause} from '@/api/simulation';
import ConstConfig from '@/scripts/ConstConfig';
import {getDraftScriptByGroupNew, getAllSelectedScriptRole } from '@/api/script';
import AddScriptMember from './addScriptMember';
import Cookies from 'js-cookie';
import AllScriptRole from './allScriptRole';

export default {
    name:'TipScriptRecord',
    components: {
        GetActionNew,
        AllScriptRole,
        AddScriptMember
    },
    props: {
        group: {
            type: String,
            required: true
        },
        offsetBottom:{
            type: Number,
            required: true
        },
        offset:{
            type: Number,
            required: true
        },
        treeData:{
            type:Array,
            required: true
        },
        memberList:{
            type:Array,
            required: true
        }
    },
    data() {
        return {
            isShow:true,
            isFirst:true,
            language:'',
            isPause:false,
            executeDisabled: false,
            backDisabled: false,
            autoSaveScript: null,
            isSavingScript: false,
            mapLocation:null,
            quickChangeMember:{list:[]},
            size: {
                width: 300,
                height: 300
            },
            openWindow:null
        };
    },
    computed:{
        memberId() {
            return this.$store.state.scriptRecord.updateRoleId;
        },
        orignalUserRoleId() {
            return this.$store.state.training.orignalUserRoleId;
        }
    },
    watch:{
        '$store.state.map.mapViewLoadedCount': function (val) {
            Vue.prototype.$jlmap.setOptions(this.$store.state.scriptRecord.mapLocation);
            this.isPause = !(this.$store.state.scriptRecord.simulationPause);
            if (this.mapLocation) {
                const newMapLocation = {'offsetX': this.mapLocation.x, 'offsetY': this.mapLocation.y, 'scaleRate': this.mapLocation.scale};
                Vue.prototype.$jlmap.setOptions(newMapLocation);
            }
        },
        '$store.state.scriptRecord.bgSet': function (val) {
            this.backDisabled = val;
        },
        '$store.state.scriptRecord.simulationPause': function(val) {
            this.isPause = !(this.$store.state.scriptRecord.simulationPause);
        },
        'memberList':function(val) {
            if (this.isFirst) {
                this.isFirst = false;
                this.initData();
            }
        }
    },
    mounted() {
        this.language = this.$route.query.lang == 'en' ? this.$t('scriptRecord.english') : this.$t('scriptRecord.chinese');
        getDraftScriptByGroupNew(this.group).then(response=>{
            this.backDisabled = response.data.bgSet;
            this.mapLocation = response.data.mapLocation;
            this.$store.dispatch('scriptRecord/updateBgSet', response.data.bgSet);
        });
    },
    methods:{
        initData() {
            getAllSelectedScriptRole(this.group).then(res=>{
                res.data.forEach(each=>{
                    const eachMember = this.memberList.find(member=>{ return member.id == each.id; });
                    if (eachMember) {
                        this.quickChangeMember.list.push(eachMember);
                    }
                });
            });
        },
        addScriptMember(member) {
            member.userId = '';
            member.disabled = false;
            const lastData = JSON.stringify([member]);
            const covertmember = this.covert(lastData, ConstConfig.ConstSelect.roleTypeNew);
            this.$emit('addScriptMember', covertmember[0]);
        },
        setMemberId({newRole, oldRole}) {
            this.$emit('changeTreeData', {newRole:newRole, oldRole:oldRole});
            const quickChangeMember = this.quickChangeMember.list;
            quickChangeMember.forEach((mem, index)=>{
                if (oldRole.id && mem.id == oldRole.id) {
                    delete mem.userId;
                }
                if (newRole.id == mem.id) {
                    mem.userId = this.$store.state.user.id;
                }
            });
            this.quickChangeMember = {list:quickChangeMember};
            const memberdata = this.quickChangeMember.list.find(mem=>{ return mem.id == newRole.id; });
            if (!memberdata) {
                newRole.userId = this.$store.state.user.id;
                const roleTypeEnumMap = {
                    'STATION_SUPERVISOR':'行值',
                    'DISPATCHER':'行调',
                    'DRIVER':'司机',
                    'MAINTAINER':'通号',
                    'DEPOT_DISPATCHER':'车辆段调度',
                    'PARENT_DEPARTMENT':'上级部门'
                };
                newRole.type = roleTypeEnumMap[newRole.type];
                this.quickChangeMember.list.push(newRole);
            }
        },
        addMember() {
            this.$refs.addScriptMember.doShow();
        },
        changeRole(member) {
            this.$refs.allScriptRole.changeRole(member);
        },
        getRoleName(memberId) {
            const currentMember = this.memberList.find(member=>{
                return member.id == memberId;
            });
            if (currentMember) {
                return currentMember.normalName;
            }
            return '';
        },
        minisize() {
            if (this.isShow) {
                this.isShow = false;
            } else {
                this.isShow = true;
            }
        },
        covert(data, roleTypeList) {
            let lastData = data;
            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);
            lastData.forEach(each=>{
                let deviceName = '';
                if (each.deviceCode) {
                    const device = this.$store.getters['map/getDeviceByCode'](each.deviceCode);
                    if (device) {
                        if (device._type == 'Train') {
                            deviceName = device.groupNumber;
                        } else {
                            deviceName = device.name;
                        }
                    } else {
                        deviceName = each.deviceCode;
                    }
                }
                each.deviceName = deviceName;
                each.normalName = each.type + deviceName + (each.name ? '' + each.name : '');
                each.label = each.normalName;
            });
            return lastData;
        },
        setAction() {

        },
        pauseScript() {
            simulationPause(this.group).then(resp => {
                this.$store.dispatch('scriptRecord/updateSimulationPause', true);
            }).catch(() => {
                this.$messageBox(this.$t('scriptRecord.pauseFail'));
            });
        },
        saveScenesData() {
            this.isSavingScript = true;
            const data = Vue.prototype.$jlmap.$options;
            const dataZoom = {scale: data.scaleRate, x: data.offsetX, y: data.offsetY};
            updateMapLocationNew(this.group, dataZoom).then(response=>{
                saveScriptDataNew(this.group).then(resp => {
                    this.$message.success(this.$t('scriptRecord.saveDataSucess'));
                    this.isSavingScript = false;
                // this.initAutoSaveScript();
                }).catch(error => {
                    this.$messageBox(`${this.$t('scriptRecord.saveDataFail')}: ${error.message}`);
                    this.isSavingScript = false;
                    if (error.code === 40004 || error.code === 40005 || error.code === 40003) {
                    // this.clearAutoSave();
                    } else {
                    // // this.initAutoSaveScript();
                    }
                });
            }).catch(error => {
                this.$messageBox(`${this.$t('scriptRecord.saveDataFail')}: ${error.message}`);
                this.isSavingScript = false;
                if (error.code === 40004 || error.code === 40005 || error.code === 40003) {
                    // this.clearAutoSave();
                } else {
                    // // this.initAutoSaveScript();
                }
            });

        },
        saveScenesStage() {
            const data = Vue.prototype.$jlmap.$options;
            const group = this.$route.query.group;
            const dataZoom = {scale: data.scaleRate, x: data.offsetX, y: data.offsetY};
            updateMapLocationNew(group, dataZoom).then(response=>{
                saveScriptScenesNew(this.group).then(resp => {
                    this.$store.dispatch('scriptRecord/updateBgSet', true);
                    this.$message.success(this.$t('scriptRecord.saveBackgroundSuceess'));
                }).catch(error => {
                    this.$messageBox(`${this.$t('scriptRecord.updateLocationFail')}: ${error.message}`);
                });
            }).catch((error) => {
                this.$messageBox(`${this.$t('scriptRecord.saveBackgroundFail')}: ${error.message}`);
            });
        },
        initAutoSaveScript() {
            const timeout = 1000 * 20;
            this.clearAutoSave(this.autoSaveScript);
            this.autoSaveScript = setInterval(this.saveScenesData, timeout);
        },
        clearAutoSave() {
            if (this.autoSaveScript) {
                clearInterval(this.autoSaveScript);
                this.autoSaveScript = null;
            }
        },
        executePlayScript() {
            executeScriptNew(this.group).then(resp => {
                this.$store.dispatch('scriptRecord/updateSimulationPause', false);
            }).catch(() => {
                this.$messageBox(this.$t('scriptRecord.recoverFail'));
            });
        },
        dumpScenesData() {
            this.clearAutoSave();
            const group = this.group;
            this.$confirm(this.$t('scriptRecord.clearDataTip'), this.$t('global.tips'), {
                confirmButtonText: this.$t('global.confirm'),
                cancelButtonText: this.$t('global.cancel'),
                type: 'warning'
            }).then(() => {
                dumpScriptDataNew(group).then(resp => {
                    this.$parent.resetBeginTime();
                    this.$refs['getAction'].loadInitData();
                    // this.changeRunPlanStatus();
                    this.$store.dispatch('training/updateMemberListInScript',
                        {
                            oldMemberId:this.memberId,
                            newMemberId:this.orignalUserRoleId,
                            userId:this.$store.state.user.id,
                            name:this.$store.state.user.nickname
                        }
                    );
                    const new_member = this.memberList.find(mem=>{ return mem.id == this.orignalUserRoleId; });
                    const old_member = this.memberList.find(mem=>{ return mem.id == this.memberId; });
                    if (new_member && old_member) {
                        new_member.userId = this.$store.state.user.id;
                        new_member.disabled = true;
                        this.quickChangeMember.list = [new_member];
                        const deviceList = ['行值', '行调', '司机', '通号', '车辆段', '上级部门'];
                        const deviceType = ['STATION_SUPERVISOR', 'DISPATCHER', 'DRIVER', 'MAINTAINER', 'DEPOT_DISPATCHER', 'PARENT_DEPARTMENT'];
                        const new_index = deviceList.indexOf(new_member.type);
                        const old_index = deviceList.indexOf(old_member.type);
                        let oldType, newType;
                        if (new_index >= 0) {
                            newType = deviceType[new_index];
                        }
                        if (old_index >= 0) {
                            oldType = deviceType[old_index];
                        }
                        this.$emit('changeTreeData', {oldRole:{id:this.memberId, type:oldType }, newRole:{id:this.orignalUserRoleId, type:newType}});
                        this.$emit('resetChat');
                    }
                    // this.initAutoSaveScript();
                    this.$store.dispatch('training/setPrdType', '02');
                    this.$store.dispatch('map/resetActiveTrainList');
                    this.$store.dispatch('scriptRecord/updateRole', new_member.type + ':' + this.orignalUserRoleId);
                    this.$store.dispatch('scriptRecord/updateBgSet', false);
                    // this.memberId = this.orignalUserRoleId;
                    this.$message.success(this.$t('scriptRecord.resetDataSuccess'));
                }).catch(() => {
                    this.$messageBox(this.$t('scriptRecord.resetDataFail'));
                });
            });
        }
    }
};
</script>
<style lang="scss" scoped>
.selectRolesTitle{

}
.button-group{
    position: absolute;
    bottom: 0;
}
.eachScriptPanel{
  height: 300px;
  display: inline-block;
  width:100%;
}
.scriptPanelLeft{
    width: 330px;
    height: 100%;
    vertical-align: top;
    position: absolute;
    left: 0;
    top: 0;
    z-index: 2;
}
.scriptPanelRight{
    width: 680px;
}
.scriptRecordNew{
    position: absolute;
    width: 700px;
    z-index: 10;
    padding-top: 28px;
    left: 50%;
    bottom: 0px;
    transform: translateX(-50%) translateY(0);
}
.scriptRecordNewTitle{
    position: absolute;
    background: #fff;
    border-radius: 5px 5px 0px 0px ;
    padding: 5px 0px;
    width: 100px;
    text-align: center;
    left: 50%;
    transform: translateX(-50%);
    cursor: pointer;
    top:0;
}
.scriptRecordNewIn{
    padding: 10px;
    background: #fff;
    border-radius: 5px 5px 0px 0px ;
    height: 380px;
    box-shadow: -1px -1px 3px #656565;
}
.scriptPanelRight{

}
.quickChange{
    width: 300px;
}
.quickChange_head{
    font-size: 14px;
    margin-top: 5px;
    color: #409eff;
}
.setGroup{
    font-size: 14px;
    float: right;
    margin-right: 15px;
}
.settingBtn{
    color: #409eff;
    cursor: pointer;
    padding: 5px 10px;
    border-radius: 4px;
}
.setGroupOut{
        margin-bottom: 5px;
}
</style>
