<template>
    <div id="slimvue" class="ces-slimvue">

        <el-container>
            <el-header>
                <div class="frame-top-logo" tabindex="0">
                    <span class="fa fa-list fa-2x ces-gamename-list" @click="asideShowOrHide"></span>
                    <img src="../assets/img/logo.png" width="40"> <strong>CES 内容管理系统</strong>
                    <span class="ces-version">v1.0.0</span>
                </div>
                <div class="frame-top-right">
                    <el-menu class="el-menu-demo" mode="horizontal" background-color="#424a55"
                             text-color="#fff">
                        <el-submenu index="1">
                            <template slot="title">
                                {{username}}
                                <img src="../assets/img/avatar.png" width="24">
                            </template>
                            <el-menu-item index="1-1"><a href="/logout.html" style="color: #fff; display:block;">退出</a>
                            </el-menu-item>
                        </el-submenu>
                    </el-menu>
                </div>
            </el-header>
            <el-container>
                <el-aside width="240px" class="ces-aside" ref="aside">
                    <div class="search">
                        <el-input placeholder="Filter keyword" v-model="filterText"></el-input>
                    </div>
                    <div style="text-align: left;padding-left: 12px;">
                        <el-button class="addBtn" style="margin: 10px 0 10px 10px;" @click="dialogFormVisible = true"><i class="el-icon-circle-plus"></i></el-button>
                    </div>
                    <el-dialog title="创建游戏" :visible.sync="dialogFormVisible" width="30%" 
                    :before-close="cenelFn">
                        <el-form :model="createGameForm" ref="createGameForm" :rules="rules">
                            <el-form-item label="游戏名称" :label-width="formLabelWidth" prop="gamename">
                                <el-input v-model.trim="createGameForm.gamename" autocomplete="off"></el-input>
                            </el-form-item>
                            <el-form-item label="Code" :label-width="formLabelWidth" prop="gamecode" >
                                <el-input v-model.trim="createGameForm.gamecode" autocomplete="off"></el-input>
                            </el-form-item>

                        </el-form>
                        <div slot="footer" class="dialog-footer">
                            <el-button @click="cenelFn">取 消</el-button>
                            <el-button type="primary" @click="submitForm('createGameForm')">确 定</el-button>
                        </div>
                    </el-dialog>

                    <el-tree
                            v-loading="loading"
                            class="filter-tree"
                            :data="treeData"
                            :props="defaultProps"
                            default-expand-all
                            highlight-current
                            node-key="id"
                            :current-node-key="lastid"
                            @node-click="listDrawFn"
                            @current-change="clearContent"
                            :filter-node-method="filterNode"
                            ref="tree2">
                    </el-tree>
                </el-aside>

                <slot></slot>

            </el-container>
        </el-container>
    </div>
</template>


<script>
    import locale from 'element-ui/lib/locale/lang/en';
    import ElementUI from 'element-ui';
    import Vue from 'vue';
    import axios from '../common/axios';
    import {mapState, mapGetters, mapMutations} from 'vuex';

    Vue.use(ElementUI, {locale});

    export default {
        name: 'layout',
        data() {
            var checkGameCodeExist = (rule, value, callback) => {
                if (value.length) {
                    axios({
                        method: 'post',
                        url: 'https://api-ces-test.oasgames.com/api/item/list',
                        params: {
                            parent_id: 0
                        },
                        token: window.bridge.token
                    }).then((response) => {
                        let num = response.data.length;
                        for (let i = 0; i < num; i++) {
                            if (this.createGameForm.gamecode === response.data[i].id) {
                                return callback(new Error('game code 已存在！'));
                            }
                        }
                        callback();
                    });
                }
                else {
                    return callback(new Error('请输入游戏code'));
                }
               
            };
            return {
                loading: 1,
                asideShowOrHideBok: true,
                username: window.bridge.username,
                token: window.bridge.token,
                lastid: localStorage.getItem("lastid"),
                filterText: '',
                treeData: [],
                defaultProps: {
                    children: 'children',
                    label: 'label'
                },
                dialogTableVisible: false,
                dialogFormVisible: false,
                createGameForm: {
                    gamecode: '',
                    gamename: ''
                },
                formLabelWidth: '80px',
                rules: {
                    gamecode: [
                        {required: true, validator: checkGameCodeExist, trigger: 'blur'}
                    ],
                    gamename: [
                        {required: true, message: '请输入游戏名称', trigger: 'blur'}
                    ]
                }
            };
        },
        watch: {
            filterText(val) {
                console.log(val);
                this.$refs.tree2.filter(val);
            }
        },
        methods: {
            asideShowOrHide() {
                if (this.asideShowOrHideBok) {
                    this.$refs.aside.$el.style.width = '0';
                    this.asideShowOrHideBok = false;
                }
                else {
                    this.$refs.aside.$el.style.width = '240px';
                    this.asideShowOrHideBok = true;
                }
            },
            filterNode(value, data) {
                if (!value) return true;
                return data.label.indexOf(value) !== -1 || data.id.indexOf(value) !== -1;
            },
            getRootTree() {
                axios({
                    method: 'post',
                    url: 'https://api-ces-test.oasgames.com/api/item/list',
                    params: {
                        parent_id: 0
                    },
                    token: window.bridge.token
                }).then((response) => {

                    let flag = false;
                    for (let key in response.data) { 
                        this.treeData.push({
                            id: response.data[key].id, 
                            label: response.data[key].title,

                        });  
                        if (this.lastid && this.lastid === response.data[key].id) {
                            this.listDrawFn({
                                id: response.data[key].id, 
                                label: response.data[key].title
                            });
                            flag = true;
                        }
                    }
                    if (flag === false) {
                        this.listDrawFn(this.treeData[0]);
                    }
                    this.loading = 0;
                }); 
               
            },
            listDrawFn(node) { 
                this.isgameCodeIdChange(node.id);
               
                if (node.id) {
                    this.checkToken(node.id);
                }
                else {
                   
                    this.getCategroy();
                }

            },
            clearContent() {
                this.$router.push({
                    path: '/'
                });
            },
            checkToken(id) {
                if (!id) {
                    return false;          
                }
                axios({
                    method: 'post',
                    url: '/panel/exchange-token/' + id
                }).then((res) => {
                    window.bridge.token = res.data; 
                    this.getCategroy();
                });
                localStorage.setItem("lastid", id);
                this.lastid = id;
                this.isgameCodeIdChange(id);
                return id;
            },
            getCategroy(res) {
                let header = '';
                if (typeof res !== 'undefined') {
                    header = {
                        'oasis-ces-token': res
                    };
                }
                axios({
                    method: 'post',
                    url: 'https://api-ces-test.oasgames.com/api/item/list',
                    params: {
                        type: -1
                    },
                    headers: header
                }).then((response) => {
                    this.addArticleData('resetUpdata');
                    this.addPictureVideoData('resetUpdata');
                    this.addMapData('resetUpdata');
                    response.data.map((key) => {
                        switch (key.type) {
                            case 1:
                                this.addArticleData(key);
                                break;
                            case 2:
                                this.addPictureVideoData(key);
                                break;
                            case 3:
                                this.addPictureVideoData(key);
                                break;
                            case 4:
                                this.addMapData(key);
                                break;
                        }

                    });
                });
            },
            ...mapMutations('article', {
                addArticleData: 'isArticleDataChange'
            }),
            ...mapMutations('pictureVideo', {
                addPictureVideoData: 'isPictureVideoDataChange'
            }),
            ...mapMutations('map', {
                addMapData: 'isMapDataChange'
            }),
            ...mapMutations('utils', {
                isgameCodeIdChange: 'isgameCodeIdChange'
            }),
            submitForm(createGameForm) {

                this.$refs[createGameForm].validate((valid) => {
                    if (valid) {
                        axios({
                            method: 'get',
                            url: '//ces-test.oasgames.com/panel/exchange-token/' + this.createGameForm.gamecode,
                            params: {
                                gamename: this.createGameForm.gamename
                            }
                        }).then((response) => {
                            console.log(response.data);
                            this.getCategroy(response.data);
                            this.dialogFormVisible = false;
                            this.treeData = [];
                            this.getRootTree();
                        });
                    }
                });
            },
            cenelFn() {
                this.dialogFormVisible = false;
                this.createGameForm = {
                    gamecode: '',
                    gamename: ''
                };
            }
        },
        mounted() {
            this.getRootTree();
            let node = {
                id: ''
            };
            this.listDrawFn(node);
        }
    };
</script>
<style>
    .ces-gamename-list{
        vertical-align: middle;
        margin-right: 10px;
        cursor: pointer;
    }
    .ces-gamename-list:hover{
        color: #199ed8;
    }
    .ces-version{
        font-size: 12px;
        display: inline-block;
        margin-left: 10px;
    }
    .ces-aside{
        transition: 1s ease;

    }
</style>

