<template>
  <div v-loading="loading" class="map-list-main">
    <div class="mapListName">
      <span>{{ $t('global.mapList') }}</span>
    </div>
    <template v-if="!IsProject">
      <filter-city ref="filerCity" filter-empty local-param-name="training_cityCode" @filterSelectChange="refresh" />
      <el-input v-model="filterText" :placeholder="this.$t('global.filteringKeywords')" clearable />
    </template>
    <div id="trainingMapTree" class="left-map-list">
      <el-tree
        ref="tree"
        :data="treeList"
        node-key="key"
        :props="{children:'children',label:'name'}"
        highlight-current
        :span="22"
        :filter-node-method="filterNode"
        :default-expanded-keys="expandList"
        @node-click="clickEvent"
        @node-expand="nodeExpand"
        @node-collapse="nodeCollapse"
      >
        <span slot-scope="{ node }">
          <span
            class="el-icon-tickets"
          />
          <span v-if="node.data.id ==='Simulation'" :id="node.data.key">&nbsp;{{ node.data.name+ $t('global.simulationSystem') }}</span>
          <span v-else-if="node.data.id ==='Lesson'" :id="node.data.key">&nbsp;{{ node.data.name+ $t('global.lessonSystem') }}</span>
          <span v-else-if="node.data.id ==='Exam'" :id="node.data.key">&nbsp;{{ node.data.name+ $t('global.examSystem') }}</span>
          <span v-else-if="node.data.id ==='Plan'" :id="node.data.key">&nbsp;{{ node.data.name+ $t('global.runPlanSystem') }}</span>
          <span v-else :id="node.data.key">&nbsp;{{ node.data.name }}</span>
        </span>
      </el-tree>
    </div>
  </div>
</template>
<script>
import { getTrainingSystemList, getSubSystemInfo, getSubSystemByProjectCode } from '@/api/trainingPlatform';
import { getPublishMapInfo } from '@/api/jmap/map';
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,
            filterText: '',
            treeList: [],
            mapId: '',
            expandList: [],
            filterSelect: ''
        };
    },
    computed: {
        userId() {
            return this.$store.state.user.id;
        },
        project() {
            return getSessionStorage('project');
        },
        IsProject() {
            // 实训平台 是否为通过项目code获取地图列表的项目
            return GetMapListByProjectList.includes(this.project);
        }
    },
    watch: {
        filterText(val) {
            this.$refs.tree.filter(val);
        }
    },
    mounted() {
        if (this.IsProject) {
            this.refresh();
        }
    },
    methods: {
        filterNode(value, data) {
            if (!value) return true;
            return data.name.includes(value);
        },
        clickEvent(obj, data, ele, isReplace = false) {
            if (ele) {
                if ( ele.expanded) {
                    ele.expanded = false;
                } else {
                    ele.expanded = true;
                }
            }

            localStore.set('trainingPlatformCheckId' + this.filterSelect + this.userId + this.project, obj.key);
            this.mapId = obj.key.split('-')[0];
            if ( obj.type === 'Map') {
                this.mapId = obj.id;
                const router = { path: `${UrlConfig.trainingPlatform.permission}/${this.mapId}`};
                this.toNextPage(isReplace, router);
            } else if ( obj.type === 'System' ) {
                const router = { path: `${UrlConfig.trainingPlatform.secondaryHome}`, query: { type: obj.id } };
                this.toNextPage(isReplace, router);
            } 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) { router = { path: `${UrlConfig.trainingPlatform.examHome}/${obj.id}`}; }
                        // this.toNextPage(isReplace, router);
                        router = { path: `${UrlConfig.trainingPlatform.examHome}/${obj.id}`};
                        this.toNextPage(isReplace, router);
                        break;
                    case 'Lesson':
                        this.setLocalRoute(`${UrlConfig.trainingPlatform.teachHome}/${obj.id}`);
                        router = { path: `${UrlConfig.trainingPlatform.teachHome}/${obj.id}`};
                        this.toNextPage(isReplace, router);
                        break;
                    case 'Simulation':
                        if (resp.data.prdType == '08') {
                            // 运行图编辑工作站
                            getPublishMapInfo(this.mapId).then(rest => {
                                this.setLocalRoute(`${UrlConfig.trainingPlatform.runPlan}/${this.mapId}?lineCode=${rest.data.lineCode}`);
                                router = { path: `${UrlConfig.trainingPlatform.runPlan}/${this.mapId}`, query: { lineCode: rest.data.lineCode}};
                                this.toNextPage(isReplace, router);
                            });
                        } else {
                            this.setLocalRoute(`${UrlConfig.trainingPlatform.prodDetail}/${obj.id}?mapId=${this.mapId}`);
                            router = { path: `${UrlConfig.trainingPlatform.prodDetail}/${obj.id}`, query: { mapId: this.mapId}};
                            this.toNextPage(isReplace, router);
                        }
                        break;
                    }
                }).catch((error) => {
                    if (error.code === '40004') {
                        this.$messageBox(this.$t('systemGenerate.getSubSystemInfoFail'));
                    }
                });
            }
        },
        toNextPage(isReplace, router) {
            isReplace ? this.$router.replace(router) : this.$router.push(router);
        },
        setLocalRoute(path) {
            localStore.set('trainingPlatformRoute' + this.userId + this.project, path);
        },
        forTree(item) {
            item.children && item.children.forEach(childrenItem => {
                childrenItem.key = item.key + '-' + childrenItem.id;
                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.IsProject) {
                    res = await getSubSystemByProjectCode();
                } else {
                    res = await getTrainingSystemList(filterSelect);
                }
                this.$emit('goRoutePath', res.data);
                res.data && res.data.forEach(item =>{
                    item.key = item.id;
                    this.forTree(item);
                });
                if (this.project === 'cgy') {
                    this.treeList = [];
                    res.data.forEach(item => {
                        const childList = [];
                        if (item && item.children && item.children.length > 3) {
                            item.children.forEach(elem => {
                                if (elem.id === 'Lesson') {
                                    childList[0] = elem;
                                } else if (elem.id === 'Exam') {
                                    childList[3] = elem;
                                } else if (elem.id === 'Simulation') {
                                    childList[1] = elem;
                                } else {
                                    childList[2] = elem;
                                }
                            });
                            item.children = childList;
                        }
                    });
                }
                this.treeList = res.data;
                this.getExpandList(filterSelect);
                this.$nextTick(() => {
                    let checkId = localStore.get('trainingPlatformCheckId' + filterSelect + this.userId + this.project) || null;
                    checkId = checkId && checkId.includes('-') ? checkId : null;
                    this.$refs.tree && this.$refs.tree.setCurrentKey(checkId);
                    if (!this.$route.path.includes('result') && !this.$route.path.includes('/trainingPlatform/teach/')) {
                        checkId && this.findTree(this.treeList, checkId);
                        !checkId && this.treeList && this.treeList.length && this.clickEvent(this.treeList[0], {data: this.treeList[0]});
                    }
                    setTimeout(()=> {
                        if (checkId) {
                            const checkIdDom = document.getElementById(checkId);
                            const mapTreeDom = document.getElementById('trainingMapTree');
                            if (checkIdDom && mapTreeDom) {
                                mapTreeDom.scrollTop = checkIdDom.offsetTop;
                            }
                        }
                        this.loading = false;
                    }, 200);
                });
            } 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}, null, true);
                } 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 && !item.startsWith(`${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>
    .mapListName{
        padding: 15px 0px 15px 17px;
    }
    .left-map-list{
        width: 100%;
        flex: 1;
        overflow: auto;
        padding-bottom: 10px;
        padding-top: 5px;
    }
    .map-list-main{
        height: 100%;
        display:flex;
        flex-direction:column;
    }
</style>
<style>
    .el-tree {
        overflow-x: hidden;
    }
    .el-tree-node.is-current>.el-tree-node__content {
        background-color: #e4e3e3 !important;
    }
</style>
