<template>
    <el-container id="app">
        <!-- <el-aside :width="collapse ? '65px' : '200px'" class="aside">
            <div class="logo-wrapper">江西军民融合</div>
            <el-menu
                :collapse="collapse"
                background-color="#324157"
                text-color="#BFCBD9"
                active-text-color="#20A0FF"
                :unique-opened="true"
                :router="true"
                :default-active="activeMenu"
                style="border-right: 1px solid #545c64;"
                class="el-menu-vertical-demo"
            >
                <sys-menu v-for="item in menus" :menu="item" :key="item.id"> </sys-menu>
            </el-menu>
        </el-aside>
        <el-container>
            <el-header class="header">
                <div class="header-btn" @click="collapse = !collapse">
                    <div :style="{ transform: collapse ? 'rotate(90deg)' : '' }">
                        <i class="fas fa-bars" style="font-size: 20px;"></i>
                    </div>
                </div>
                <div style="flex-grow: 1; margin-left: 20px;">
                    <el-breadcrumb separator-class="el-icon-arrow-right">
                        <el-breadcrumb-item :to="{ path: '/dashboard' }">
                            首页
                        </el-breadcrumb-item>
                        <el-breadcrumb-item v-if="$route.name !== 'dashboard'">{{
                            $route.meta.title || $route.name
                        }}</el-breadcrumb-item>
                    </el-breadcrumb>
                </div>

                <el-tooltip
                    effect="dark"
                    :content="isFullscreen ? '退出全屏' : '全屏'"
                    placement="bottom"
                    :open-delay="1000"
                >
                    <div class="header-btn" @click="toggleFullScreen" ref="fullscreen">
                        <i class="fas fa-expand" style="font-size: 20px;"></i>
                    </div>
                </el-tooltip>

                <el-dropdown @command="onCommand" style="margin-left: 20px;">
                    <img :src="userInfo ? userInfo.avatar || '' : ''" class="avatar" />
                    <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item command="logout">退出登录 </el-dropdown-item>
                    </el-dropdown-menu>
                </el-dropdown>
            </el-header>
            <el-main style="background: #f2f4f5; height: 100%;">
                <router-view></router-view>
            </el-main>
        </el-container> -->
        <el-aside :width="collapse ? '65px' : '200px'" class="aside">
            <!-- <div class="user-content" v-if="userInfo">
                    <img :src="userInfo ? userInfo.avatar || '' : ''" class="avatar" />
                    <div class="user-name">{{ userInfo.nickname }}</div>
                </div> -->
            <div class="logo-wrapper">江西军民融合</div>
            <div class="user-menu">
                <el-menu
                    :collapse="collapse"
                    background-color="#324157"
                    text-color="#BFCBD9"
                    active-text-color="#20A0FF"
                    :unique-opened="true"
                    :router="true"
                    :default-active="activeMenu"
                    style="border-right: 1px solid #545c64"
                    class="el-menu-vertical-demo"
                >
                    <sys-menu v-for="item in menus" :menu="item" :key="item.id"> </sys-menu>
                </el-menu>
            </div>
        </el-aside>
        <el-container class="main">
            <el-header class="header">
                <div class="header-btn" @click="collapse = !collapse">
                    <div :style="{ transform: collapse ? 'rotate(90deg)' : '' }">
                        <i class="fas fa-bars" style="font-size: 20px"></i>
                    </div>
                </div>
                <div class="header-title"></div>
                <el-tooltip
                    effect="dark"
                    :content="isFullscreen ? '退出全屏' : '全屏'"
                    placement="bottom"
                    :open-delay="1000"
                >
                    <div class="header-btn" @click="toggleFullScreen" ref="fullscreen">
                        <i class="fas fa-expand" style="font-size: 20px"></i>
                    </div>
                </el-tooltip>

                <el-dropdown @command="onCommand" style="margin-left: 20px">
                    <div style="display: flex; align-items: center; padding-right: 20px; cursor: pointer">
                        <img :src="userInfo ? userInfo.avatar || '' : ''" class="avatar" />{{
                            (userInfo || {}).nickname
                        }}
                    </div>
                    <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item command="pwd" style="word-break: keep-all">修改密码 </el-dropdown-item>
                        <el-dropdown-item command="logout">退出登录 </el-dropdown-item>
                    </el-dropdown-menu>
                </el-dropdown>
            </el-header>

            <el-main class="app-main">
                <!-- <el-tabs
                    class="app-tabs"
                    v-model="currentTab"
                    type="card"
                    @tab-remove="removeTab"
                    @tab-click="clickTab"
                >
                    <el-tab-pane
                        v-for="item in tabs"
                        :key="item.name"
                        :label="item.title"
                        :name="item.name"
                        :closable="item.title !== '待办列表'"
                    >
                    </el-tab-pane>
                </el-tabs> -->
                <div
                    class="app-tabs-wrapper"
                    @mousedown.left="mousedown"
                    @mousemove="mousemove"
                    @mouseup.left="mouseup"
                    ref="appTabs"
                >
                    <el-tag
                        class="app-tab-item"
                        size="large"
                        v-for="(item, index) in tabs"
                        :key="item.name"
                        :closable="item.title !== '待办列表'"
                        @close="removeTab(index)"
                        @click="clickTab(index)"
                        :type="item.active ? '' : 'info'"
                    >
                        {{ item.title }}
                    </el-tag>
                </div>
                <router-view> </router-view>
            </el-main>
        </el-container>
        <el-dialog
            :visible.sync="showPwdDialog"
            title="修改密码"
            width="500px"
            top="30vh"
            :close-on-click-modal="false"
            custom-class="change-pwd-dialog"
        >
            <el-form :model="pwdForm" label-width="100px" label-position="right" ref="pwdForm" :rules="pwdRules">
                <el-form-item label="输入新密码" prop="password">
                    <el-input v-model="pwdForm.password" type="password" placeholder="输入新密码"></el-input>
                </el-form-item>
                <el-form-item label="确认新密码" prop="repeat">
                    <el-input v-model="pwdForm.repeat" type="password" placeholder="确认新密码"></el-input>
                </el-form-item>
                <el-form-item label="验证码" prop="code">
                    <el-input v-model="pwdForm.code" placeholder="请输入验证码" style="width: 150px"></el-input>
                    <img :src="captcha" class="captcha-image" @click="refreshCaptcha" />
                </el-form-item>
            </el-form>
            <span slot="footer">
                <el-button @click="showPwdDialog = false">取 消</el-button>
                <el-button type="primary" @click="savePwd" :loading="pwdLoading">确认修改</el-button>
            </span>
        </el-dialog>
    </el-container>
</template>

<script>
import SysMenu from '../components/SysMenu';
import { mapState } from 'vuex';
import { isBefore, parse, format, addDays } from 'date-fns';
export default {
    name: 'admin',
    created() {
        this.getMenus();
        let fn = () => {
            this.isFullscreen = document.fullScreen || document.mozFullScreen || document.webkitIsFullScreen;
        };
        document.addEventListener('fullscreenchange', fn);
        document.addEventListener('webkitfullscreenchange', fn);
        document.addEventListener('mozfullscreenchange', fn);
        document.addEventListener('MSFullscreenChange', fn);
        this.tabs = [
            {
                name: this.homePage,
                title: this.homePage == 'audit' ? '待办列表' : '企业认证'
            }
        ];

        if (this.$route.path === '/') {
            this.$router.replace({
                name: this.homePage
            });
        } else {
            let index = this.tabs.findIndex(i => i.name === this.$route.name);
            if (index === -1) {
                this.tabs.push({
                    name: this.$route.name,
                    title: this.$route.query.tabTitle || this.$route.meta.title || this.$route.name,
                    query: this.$route.query,
                    params: this.$route.parms
                });
            } else {
                this.$set(this.tabs, index, {
                    name: this.$route.name,
                    title: this.$route.query.tabTitle || this.$route.meta.title || this.$route.name,
                    query: this.$route.query,
                    params: this.$route.parms
                });
            }
        }
        let index = this.tabs.findIndex(i => i.name === this.$route.name);
        if (index > -1) {
            this.$set(this.tabs[index], 'active', true);
        }
        this.currentTab = this.$route.name;
        this.getMenus();

        // let pwdUpdateAt = this.userInfo.pwdUpdateAt;
        // if (!pwdUpdateAt || isBefore(parse(pwdUpdateAt, 'yyyy-MM-dd HH:mm:ss', new Date()), addDays(new Date(), -30))) {
        //     this.$alert('您已30天未修改密码，请尽快修改密码', '提示').then(() => {
        //         this.onShowPwdDialog();
        //     });
        // }
    },
    data() {
        return {
            rawMenus: [],
            menus: [],
            activeMenu: '',
            menuPath: [],
            collapse: localStorage.getItem('menu-collapse') == 'true',
            isFullscreen: false,
            tabs: [
                {
                    title: '企业认证',
                    name: 'orgInfoList',
                    path: '/orgInfoList',
                    active: true
                }
            ],
            currentTab: 'roomStatus',
            lastX: 0,
            leftMouseDown: false,
            showPwdDialog: false,
            pwdForm: {
                password: '',
                repeat: '',
                code: '',
                key: ''
            },
            captcha: '',
            pwdRules: {
                password: [
                    { required: true, message: '请输入新密码', trigger: 'blur' },
                    {
                        pattern: /(?=.*[0-9])(?=.*[A-Z])(?=.*[a-z]).{8,30}/,
                        message: '密码必须包含大小写字母和数字，且长度为8-30',
                        trigger: 'blur'
                    }
                ],
                repeat: [
                    { required: true, message: '请确认新密码', trigger: 'blur' },
                    {
                        validator: (rule, value, callback) => {
                            if (value && value == this.pwdForm.password) {
                                callback();
                            } else {
                                callback(new Error('两次密码输入不一致'));
                            }
                        },
                        trigger: 'blur'
                    }
                ],
                code: [
                    { required: true, message: '请输入验证码', trigger: 'blur' },
                    {
                        validator: (rule, value, callback) => {
                            this.$http
                                .get('/captcha/verify', {
                                    key: this.pwdForm.key,
                                    code: value
                                })
                                .then(res => {
                                    if (res === true) {
                                        callback();
                                    } else {
                                        callback(new Error('验证码错误'));
                                    }
                                })
                                .catch(e => {
                                    callback(new Error('验证码错误'));
                                });
                        },
                        trigger: 'blur'
                    }
                ]
            },
            pwdLoading: false
        };
    },
    computed: {
        ...mapState(['userInfo', 'homePage'])
    },
    methods: {
        findActiveMenu() {
            this.activeMenu = '';
            this.menuPath = [];
            let path = this.$route.path;
            const findActiveMenu = (parents, childMenus) => {
                childMenus.forEach(i => {
                    let parents_copy = [...parents];
                    if (i.path === path) {
                        parents_copy.push(i);
                        this.menuPath = parents_copy.map(i => i.name);
                        this.activeMenu = '' + i.id;
                    } else {
                        if (i.children) {
                            parents_copy.push(i);
                            findActiveMenu(parents_copy, i.children);
                        }
                    }
                });
            };
            findActiveMenu([], this.rawMenus);
        },
        getMenus() {
            this.$http
                .get('/menu/userMenu', {
                    name: '系统菜单'
                })
                .then(res => {
                    this.rawMenus = res;
                    this.menus = res;
                    this.findActiveMenu();
                });
        },
        toggleFullScreen() {
            this.isFullscreen = document.fullScreen || document.mozFullScreen || document.webkitIsFullScreen;
            let element = document.body;
            let requestMethod;
            if (this.isFullscreen) {
                requestMethod =
                    document.exitFullscreen || document.mozCancelFullScreen || document.webkitExitFullscreen;
            } else {
                requestMethod =
                    element.requestFullScreen ||
                    element.webkitRequestFullScreen ||
                    element.mozRequestFullScreen ||
                    element.msRequestFullScreen;
            }
            if (requestMethod) {
                requestMethod.call(this.isFullscreen ? document : element);
            }
        },
        onCommand(command) {
            if (command === 'logout') {
                localStorage.removeItem('token');
                this.$store.commit('updateUserInfo', null);
                this.$router.replace('/login');
            } else if (command === 'pwd') {
                this.onShowPwdDialog();
            }
        },
        onShowPwdDialog() {
            this.$refs.pwdForm && this.$refs.pwdForm.resetFields();
            this.$http.get('/captcha/get').then(res => {
                this.captcha = res.image;
                this.pwdForm = {
                    password: '',
                    repeat: '',
                    code: '',
                    key: res.key
                };
                this.showPwdDialog = true;
            });
        },
        savePwd() {
            this.pwdLoading = true;
            this.$refs.pwdForm.validate(valid => {
                if (valid) {
                    this.$http
                        .post('/user/changePassword', {
                            ...this.pwdForm
                        })
                        .then(res => {
                            console.log(res);
                            this.pwdLoading = false;
                            this.showPwdDialog = false;
                            localStorage.removeItem('token');
                            this.$store.commit('updateUserInfo', null);
                            this.$router.replace('/login');
                            this.$message.success('修改成功，请重新登录');
                        })
                        .catch(e => {
                            this.pwdLoading = false;
                            this.$message.error(e.error || '修改失败');
                        });
                } else {
                    this.pwdLoading = false;
                }
            });
        },
        refreshCaptcha() {
            this.$http.get('/captcha/get').then(res => {
                this.captcha = res.image;
                this.pwdForm.key = res.key;
            });
        },
        removeTab(removeIndex) {
            let currentIndex = this.tabs.findIndex(i => i.name === this.$route.name);
            if (this.tabs.length > 1 && removeIndex > 0) {
                this.tabs.splice(removeIndex, 1);
                if (removeIndex === currentIndex) {
                    this.$router.push({
                        name: this.tabs[currentIndex - 1].name,
                        query: this.tabs[currentIndex - 1].query,
                        params: this.tabs[currentIndex - 1].params
                    });
                }
            }
        },
        clickTab(index) {
            console.log('clickTab', index);
            this.tabs.forEach((item, idx) => {
                this.$set(this.tabs[idx], 'active', false);
            });
            this.$set(this.tabs[index], 'active', true);
            this.$router.push({
                name: this.tabs[index].name,
                query: this.tabs[index].query,
                params: this.tabs[index].params
            });
        },
        mousedown(e) {
            this.leftMouseDown = true;
            this.lastX = e.clientX;
        },
        mousemove(e) {
            if (this.leftMouseDown) {
                let d = e.clientX - this.lastX;
                console.log(d);
                this.$refs.appTabs.scrollLeft = this.$refs.appTabs.scrollLeft - d;
            }
            this.lastX = e.clientX;
        },
        mouseup(e) {
            this.leftMouseDown = false;
        }
    },
    watch: {
        // $route(val) {
        //     this.findActiveMenu(this.rawMenus);
        // },
        $route(route) {
            this.tabs.forEach((item, idx) => {
                this.$set(this.tabs[idx], 'active', false);
            });
            this.findActiveMenu(this.rawMenus);
            var routeInfo = { ...this.$route };
            var tabs = [...this.tabs];
            var nameList = tabs.map(item => {
                return item.name;
            });

            let index = this.tabs.findIndex(i => i.name === route.name);
            if (index === -1) {
                console.log('watch', index);
                this.tabs.push({
                    name: route.name,
                    title: route.query.tabTitle || route.meta.title || route.name,
                    query: route.query,
                    params: route.parms,
                    active: true
                });
            } else {
                console.log('watch', index);
                this.$set(this.tabs, index, {
                    name: route.name,
                    title: route.query.tabTitle || route.meta.title || route.name,
                    query: route.query,
                    params: route.parms,
                    active: true
                });
            }
            this.currentTab = route.name;
        },
        isFullscreen(val) {
            this.$refs.fullscreen.innerHTML = '';
            let i = document.createElement('i');
            i.style.fontSize = '20px';
            i.className = val ? 'fas fa-compress' : 'fas fa-expand';
            this.$refs.fullscreen.append(i);
            FontAwesome.dom.i2svg();
        },
        collapse(val) {
            localStorage.setItem('menu-collapse', val);
        }
    },
    components: {
        SysMenu
    }
};
</script>
<style lang="less">
.aside {
    .el-menu {
        border: none !important;
        &:not(.el-menu--collapse) {
            width: 200px;
        }
    }
}
</style>
<style lang="less" scoped>
#app {
    height: 100%;
}

.header {
    color: #303133;
    background: #fff;
    display: flex;
    align-items: center;
    padding-left: 0;
    border-bottom: 1px solid #e4e7ed;
    .header-title {
        flex-grow: 1;
    }
    .header-btn {
        width: 60px;
        height: 60px;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        transition: all 0.3s;
        & > div {
            transition: all 0.3s;
        }
        &:hover {
            background: fade(black, 10%);
        }
    }
    .avatar {
        width: 40px;
        height: 40px;
        margin-right: 20px;
        border-radius: 50%;
    }
    a {
        &:visited {
            color: #303133;
        }
    }
}

.aside {
    background: #324157;
    transition: all 0.4s ease;
    -ms-overflow-style: none;
    .logo-wrapper {
        font-weight: 200;
        display: flex;
        align-items: center;
        justify-content: center;
        height: 60px;
        color: white;
        font-size: 20px;
        background: fade(black, 20%);
    }
}

.aside::-webkit-scrollbar {
    display: none;
}
.el-tabs {
    background: #fff;
}
.app-main {
    background: #f2f4f5;
    padding: 0 !important;
    display: flex;
    flex-direction: column;
}
.app-tabs-wrapper {
    height: 32px;
    min-height: 32px;
    padding: 10px 0;
    margin: 0 !important;
    overflow-x: auto;
    white-space: nowrap;
    user-select: none;
    &::-webkit-scrollbar {
        display: none;
    }
    .app-tab-item {
        margin-left: 10px;
        cursor: pointer;
        &:first-child {
            margin-left: 20px;
        }
        &:last-child {
            margin-right: 20px;
        }
    }
}
/deep/ .change-pwd-dialog {
    .captcha-image {
        height: 32px;
        vertical-align: middle;
        margin-left: 10px;
        cursor: pointer;
    }
    .el-dialog__body {
        padding-bottom: 0;
    }
}
</style>
