<template>
  <div v-loading="loading" class="joylink-card map-list-main">
    <div class="clearfix">
      <span>{{ $t('map.publishedMapList') }}</span>
    </div>
    <div class="text_item">
      <filter-city v-if="project==='design'" ref="filerCity" filter-empty :query-function="queryFunction" :local-param-name="localParamName" @filterSelectChange="refresh" />
      <el-input v-if="project==='design'" v-model="filterText" :placeholder="this.$t('global.filteringKeywords')" clearable />
      <div class="tree_mian_box">
        <el-tree ref="tree" class="tree_box" :data="treeList" node-key="id" :props="defaultProps" highlight-current :span="22" :filter-node-method="filterNode" @node-click="clickEvent">
          <span slot-scope="{ node:tnode, data }">
            <span class="el-icon-tickets" :style="{color: data.valid ? 'green':''}" />
            <span>&nbsp;{{ tnode.label }}</span>
          </span>
        </el-tree>
      </div>
    </div>
  </div>
</template>
<script>
import { listPublishMap, getMapListByProjectCode } from '@/api/jmap/map';
import { UrlConfig } from '@/router/index';
import { superAdmin, admin } from '@/router';
import { getSessionStorage, setSessionStorage, removeSessionStorage } from '@/utils/auth';
import FilterCity from '@/views/components/filterCity';
import localStore from 'storejs';
import { ProjectCode } from '@/scripts/ConstDic';

export default {
    name: 'PublicMapList',
    components: {
        FilterCity
    },
    props: {
        width: {
            type: Number,
            required: true
        }
    },
    data() {
        return {
            loading: true,
            defaultShowKeys: [],
            queryFunction: listPublishMap,
            filterText: '',
            treeData: [],
            treeList: [],
            selected: {},
            defaultProps: {
                children: 'children',
                label: 'name'
            },
            node: {
            },
            localParamName: 'publish_cityCode'
        };
    },
    computed: {
        project() {
            return getSessionStorage('project');
        }
    },
    watch: {
        filterText(val) {
            this.treeList = this.treeData.filter((res) => {
                return res.name.includes(val);
            });
        }
    },
    beforeDestroy () {
        removeSessionStorage('demonList');
    },
    mounted() {
        if (this.project === 'designxty' || this.project === 'designgzb') {
            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) {
            switch (obj.type) {
            case 'scriptDesign': {
                setSessionStorage('designType', 'scriptDesign');
                this.$router.push({ path: `${UrlConfig.design.scriptHome}/${obj.mapId}?lineCode=${obj.lineCode}&drawWay=${obj.drawWay}` });
                break;
            }
            case 'lessonDesign': {
                setSessionStorage('designType', 'lessonDesign');
                this.$router.push({ path: `${UrlConfig.design.lessonHome}/${obj.mapId}`, query: {cityCode: obj.cityCode} });
                break;
            }
            case 'runPlanDesign': {
                setSessionStorage('designType', 'runPlanDesign');
                this.$router.push({ path: `${UrlConfig.design.runPlan}/${obj.mapId}?lineCode=${obj.lineCode}` });
                break;
            }
            case 'map': {
                setSessionStorage('demonList', obj.id);
                break;
            }
            case 'mapPreview': {
                if (obj.drawWay) {
                    this.$router.push({ path: `${UrlConfig.design.mapPreviewNew}/${obj.mapId}` });
                } else {
                    this.$router.push({ path: `${UrlConfig.design.mapPreview}/${obj.mapId}` });
                }
                break;
            }
            case 'ibpDesign': {
                setSessionStorage('designType', 'ibpDesign');
                this.$router.push({ path: `${UrlConfig.design.ibpHome}/${obj.mapId}`, query: {cityCode: obj.cityCode} });
                break;
            }
            }
        },
        async refresh(filterSelect) {
            this.loading = true;
            this.treeData = this.treeList = [];
            const that = this;
            try {
                let res = '';
                if (this.project === 'designxty' || this.project === 'designgzb') {
                    res = await getMapListByProjectCode(ProjectCode[this.project]);
                } else {
                    res = await listPublishMap({cityCode: filterSelect});
                }
                res.data && res.data.forEach(elem=>{
                    elem.children = [
                        {
                            id: '1',
                            name: this.$t('designPlatform.mapPreview'),
                            type: 'mapPreview',
                            mapId: elem.id,
                            cityCode: elem.cityCode,
                            drawWay: elem.drawWay
                        }
                    ];
                    this.isAdministrator() ? elem.children.push({id: '2', name: this.$t('designPlatform.lessonDesign'), type: 'lessonDesign', mapId: elem.id, cityCode: elem.cityCode}) : '';
                    elem.children.push(
                        {
                            id: '3',
                            name: this.$t('designPlatform.scriptDesign'),
                            type: 'scriptDesign',
                            mapId: elem.id,
                            cityCode: elem.cityCode,
                            lineCode: elem.lineCode,
                            drawWay: elem.drawWay
                            // code:elem.children.find(n => { return n.name.includes("行调")})
                        });
                    elem.children.push(
                        {
                            id: '4',
                            name: this.$t('designPlatform.runPlanDesign'),
                            type: 'runPlanDesign',
                            mapId: elem.id,
                            lineCode: elem.lineCode,
                            cityCode: elem.cityCode
                        }
                    );
                    elem.children.push(
                        {
                            id: '5',
                            name: 'IBP盘设计',
                            type: 'ibpDesign',
                            mapId: elem.id,
                            lineCode: elem.lineCode,
                            cityCode: elem.cityCode
                        }
                    );
                });
                this.treeData = res.data;
                this.treeList = this.filterText
                    ? res.data.filter(elem => { return elem.name.includes(this.filterText); })
                    : res.data;
                this.$nextTick(() => {
                    const mapId = getSessionStorage('demonList') || null;
                    this.$refs.tree.setCurrentKey(mapId);
                    this.loading = false;
                });
            } catch (error) {
                this.loading = false;
                this.$messageBox(that.$t('error.refreshFailed'));
            }
        },
        resize() {
            this.widthLeft = Number(localStore.get('LeftWidth')) || this.widthLeft;
            const width = this.$store.state.app.width - 521 - this.widthLeft;
            const height = this.$store.state.app.height - 90;
            this.$store.dispatch('config/resize', { width: width, height: height });
        },
        isAdministrator() {
            return this.$store.state.user.roles.includes(superAdmin) || this.$store.state.user.roles.includes(admin);
        }
    }
};
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
    .back-home {
        float: right;
        cursor: pointer;

    &:hover {
         color: #3ea726;
     }
    }
    .text_item{
        height: calc(100% - 47px);
        .tree_mian_box{
            height: calc(100% - 76px);
        }
    }

    .map-list-main{
        text-align:left;
		height: 100%;
    }
	.clearfix{
		padding: 0 20px;
		border-bottom: 1px solid #EBEEF5;
		box-sizing: border-box;
		height: 47px;
		line-height: 47px;
	}
	.tree_box{
		height: 100%;
	}
</style>
<style>
    .el-tree {
        overflow-x: hidden;
    }

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