<template>
  <div v-loading="loading" class="joylink-card map-list-main">
    <div class="clearfix">
      <span>{{ $t('global.mapList') }}</span>
    </div>
    <div class="left-map-list">
      <filter-city v-if="!getMapByCode" ref="filerCity" filter-empty :local-param-name="localParamName" @filterSelectChange="refresh" />
      <el-input v-if="!getMapByCode" v-model="filterText" :placeholder="this.$t('global.filteringKeywords')" clearable />
      <div style="height: calc(100% - 76px); overflow: auto;">
        <el-tree
          ref="tree"
          :data="treeList"
          node-key="key"
          :props="defaultProps"
          highlight-current
          :span="22"
          :filter-node-method="filterNode"
          :default-expanded-keys="expandList"
          @node-click="clickEvent"
          @node-contextmenu="showContextMenu"
          @node-expand="nodeExpand"
          @node-collapse="nodeCollapse"
        >
          <span slot-scope="{ node }">
            <span
              class="el-icon-tickets"
            />
            <span v-if="node.data.id ==='Simulation'">&nbsp;{{ node.data.name+ $t('global.simulationSystem') }}</span>
            <span v-else-if="node.data.id ==='Lesson'">&nbsp;{{ node.data.name+ $t('global.lessonSystem') }}</span>
            <span v-else-if="node.data.id ==='Exam'">&nbsp;{{ node.data.name+ $t('global.examSystem') }}</span>
            <span v-else-if="node.data.id ==='Plan'">&nbsp;{{ node.data.name+ $t('global.runPlanSystem') }}</span>
            <span v-else>&nbsp;{{ node.data.name }}</span>
          </span>
        </el-tree>
      </div>
    </div>
  </div>
</template>
<script>
import { getTrainingSystemList, getSubSystemInfo, getSubSystemByProjectCode } from '@/api/trainingPlatform';
import { UrlConfig } from '@/scripts/ConstDic';
import FilterCity from '@/views/components/filterCity';
import localStore from 'storejs';
import { getSessionStorage } from '@/utils/auth';
import { GetMapListByProjectList } from '@/scripts/ProjectConfig';

export default {
    name: 'DemonList',
    components: {
        FilterCity
    },
    data() {
        return {
            loading: true,
            defaultShowKeys: [],
            filterText: '',
            treeList: [],
            selected: {},
            defaultProps: {
                children: 'children',
                label: 'name'
            },
            node: {
            },
            mapId: '',
            expandList: [],
            filterSelect: '',
            localParamName: 'training_cityCode'
        };
    },
    computed: {
        userId() {
            return this.$store.state.user.id;
        },
        project() {
            return getSessionStorage('project');
        },
        getMapByCode() {
            const project = getSessionStorage('project');
            return GetMapListByProjectList.includes(project);
        }
    },
    watch: {
        filterText(val) {
            this.$refs.tree.filter(val);
        }
    },
    beforeDestroy () {
    },
    mounted() {
        if (this.getMapByCode) {
            this.refresh();
        }
    },
    methods: {
        filterNode(value, data) {
            if (!value) return true;
            return data.name.indexOf(value) !== -1;
        },
        showContextMenu(e, obj, node, vueElem) {
            if (obj) {
                this.node = node;
                this.selected = obj;
            }
        },
        clickEvent(obj, data, ele) {
            localStore.set('trainingPlatformCheckId' + this.filterSelect + this.userId + this.project, obj.key);
            while (data) {
                if (data.data.type === 'Map') {
                    this.mapId = data.data.id;
                    break;
                }
                data = data.parent;
                if (!data) { break; }
            }
            if ( obj.type === 'Map') {
                this.mapId = obj.id;
                this.$router.push({ path: `${UrlConfig.trainingPlatform.permission}/${this.mapId}`});
            } else if ( obj.type === 'MapSystem') {
                getSubSystemInfo(obj.id).then(resp => { // 查询子系统信息
                    let router = '';
                    switch (resp.data.type) {
                    case 'Exam':
                        this.setLocalRoute(`${UrlConfig.trainingPlatform.examHome}/${obj.id}`);
                        router = localStore.get('examDetail' + obj.id);
                        if (router) {
                            this.$router.push(router);
                        } else {
                            this.$router.push({ path: `${UrlConfig.trainingPlatform.examHome}/${obj.id}`});
                        }
                        break;
                    case 'Lesson':
                        this.setLocalRoute(`${UrlConfig.trainingPlatform.teachHome}/${obj.id}`);
                        router = localStore.get('teachDetail' + obj.id);
                        if (router) {
                            this.$router.push(router);
                        } else {
                            this.$router.push({ path: `${UrlConfig.trainingPlatform.teachHome}/${obj.id}`});
                        }
                        break;
                    case 'Simulation':
                        this.setLocalRoute(`${UrlConfig.trainingPlatform.prodDetail}/${obj.id}?mapId=${this.mapId}`);
                        this.$router.push({ path: `${UrlConfig.trainingPlatform.prodDetail}/${obj.id}`, query: { mapId: this.mapId}});
                        break;
                    }
                }).catch((error) => {
                    if (error.code === '40004') {
                        this.$messageBox(this.$t('systemGenerate.getSubSystemInfoFail'));
                    }
                });
            }
        },
        setLocalRoute(path) {
            localStore.set('trainingPlatformRoute' + this.userId + this.project, path);
        },
        forTree(item) {
            item.children && item.children.forEach(childrenItem => {
                childrenItem.key = item.id + childrenItem.id + childrenItem.type;
                if (childrenItem.children && childrenItem.children.length) {
                    this.forTree(childrenItem);
                }
            });
        },
        async refresh(filterSelect) {
            this.loading = true;
            this.treeList = [];
            this.filterSelect = filterSelect;
            try {
                let res = {};
                if (this.getMapByCode) {
                    res = await getSubSystemByProjectCode();
                } else {
                    res = await getTrainingSystemList(filterSelect);
                }
                this.$emit('goRoutePath', res.data);
                res.data && res.data.forEach(item =>{
                    item.key = item.id + item.type;
                    this.forTree(item);
                });
                this.treeList = res.data;
                this.getExpandList(filterSelect);
                this.$nextTick(() => {
                    const checkId = localStore.get('trainingPlatformCheckId' + filterSelect + this.userId + this.project) || null;
                    this.$refs.tree && this.$refs.tree.setCurrentKey(checkId);
                    if (!this.$route.path.includes('result')) {
                        checkId && this.findTree(this.treeList, checkId);
                        !checkId && this.treeList && this.treeList.length && this.clickEvent(this.treeList[0], {data: this.treeList[0]});
                    }
                    this.loading = false;
                });
            } catch (error) {
                this.loading = false;
                this.$message.error(this.$t('error.refreshFailed'));
            }
        },
        /* 根据localstorage缓存的trainingPlatformCheckId跳转右侧显示页面 */
        findTree(treeList, checkId, data) {
            treeList && treeList.length && treeList.forEach(item =>{
                if (item.type === 'Map') {
                    data = item;
                }
                if (checkId === item.key) {
                    this.clickEvent(item, {data: data});
                } else {
                    this.findTree(item.children, checkId, data);
                }
            });
        },
        nodeExpand(obj, node, ele) {
            const key = obj.key;
            this.expandList = this.expandList.filter(item => item !== key);
            this.expandList.push(key);
            localStore.set('trainIngPlatformExpandList' + this.filterSelect + this.userId + this.project, this.expandList);
        },
        nodeCollapse(obj, node, ele) {
            const key = obj.key;
            this.expandList = this.expandList.filter(item => item !== key);
            localStore.set('trainIngPlatformExpandList' + this.filterSelect + this.userId + this.project, this.expandList);
        },
        getExpandList(filterSelect) {
            this.expandList = [];
            let expand = localStore.get('trainIngPlatformExpandList' + filterSelect + this.userId + this.project);
            expand = expand ? (expand + '').split(',') : '';
            if (expand instanceof Array) {
                this.expandList = expand;
            }
        }
    }
};
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
    .clearfix{
        width:100%;
        height: 47px;
        line-height: 47px;
        padding-left: 17px;
        position:absolute;
    }
    .back-home {
        float: right;
        cursor: pointer;

    &:hover {
         color: #3ea726;
     }
    }
    .left-map-list{
        width: 100%;
        height: 100%;
        padding-top: 47px;
    }
    .map-list-main{
        text-align:left;
        height: 100%;
        position: relative;
    }
</style>
<style>
    .el-tree {
        overflow-x: hidden;
    }

    .el-tree-node.is-current>.el-tree-node__content {
        background-color: #e4e3e3 !important;
    }
</style>
