<template>
    <el-container id="app">
        <el-aside :width="collapse ? '65px' : '200px'" class="aside">
            <div v-if="collapse" class="logo-wrapper collapse" @click="$router.push('/chart1')">监控中心</div>
            <div v-else class="logo-wrapper" @click="$router.push('/chart1')">监控中心</div>
            <el-menu
                :collapse="collapse"
                :background-color="$theme['menu-bg']"
                :text-color="$theme['menu-text-color']"
                :active-text-color="$theme['menu-text-color-active']"
                :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="app-header">
                <div class="header-btn" @click="collapse = !collapse">
                    <div :style="{ transform: collapse ? 'rotate(90deg)' : '' }">
                        <i class="fas fa-bars" style="font-size: 18px"></i>
                    </div>
                </div>
                <div style="flex-grow: 1; margin-left: 20px"></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: 18px"></i>
                    </div>
                </el-tooltip>

                <el-dropdown @command="onCommand" style="margin-left: 20px" trigger="click">
                    <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">
                <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>
        <TFA></TFA>
    </el-container>
</template>

<script>
import SysMenu from '../components/SysMenu';
import { mapState } from 'vuex';
import { isBefore, parse, format, addDays } from 'date-fns';
import TFA from '../components/TFA';
export default {
    name: 'admin',
    created() {
        console.log('73263612');
        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.getRandomThreshold();

        this.$http
            .get('/sysConfig/get/BIG_SHOW')
            .then(res => {
                if (Number(res.value)) {
                    return Promise.reject('大屏展示');
                } else {
                    return Promise.all([
                        this.$http.get('/sysConfig/get/NOTIFY_NUM'),
                        this.$http.get('/sysConfig/get/NOTIFY_HIDDEN')
                    ]);
                }
            })
            .then(res => {
                res.forEach(item => {
                    if (item.name === 'NOTIFY_NUM') {
                        this.num = Number(item.value);
                    } else if (item.name === 'NOTIFY_HIDDEN') {
                        this.hideNum = Number(item.value);
                    }
                });

                setTimeout(() => {
                    this.getRandomThreshold();
                }, this.num);
            })
            .catch(e => {
                console.log(e);
            });
        console.log(this.userInfo.pwdUpdateAt);
        let pwdUpdateAt = this.userInfo.pwdUpdateAt;
        if (!location.href.includes('192.168.')) {
            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,
            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,
            num: 0,
            hideNum: 1
        };
    },
    computed: {
        ...mapState(['userInfo'])
    },
    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() {
            let menus = [
                {
                    active: false,
                    name: '数据可视化',
                    icon: 'fas fa-globe-asia',
                    children: [
                        { active: false, name: '综合数据', path: '/chart1' },
                        { active: false, name: '高程数据', path: '/mapdata1' },
                        { active: false, name: '影像数据', path: '/mapdata2' },
                        { active: false, name: 'GIS数据', path: '/geoserver' }
                    ]
                },
                {
                    active: false,
                    name: '数据统计',
                    icon: 'fas fa-chart-line',
                    children: [
                        {
                            active: false,
                            name: '描述性统计',
                            path: '/chart2',
                            icon: 'fas fa-chart-pie'
                        },
                        {
                            active: false,
                            name: '其他统计',
                            path: '/summaryStateList',
                            icon: 'fas fa-chart-bar'
                        }
                    ]
                },
                { active: false, name: '数据(指标)分析', path: '/chart3', icon: 'fas fa-chart-area' },
                {
                    active: false,
                    name: '系统管理',
                    icon: 'fas fa-cog',
                    children: [
                        { active: false, name: '日志管理', path: '/operationLogList', icon: 'fas fa-bars' },
                        { active: false, name: '配置管理', path: '/sysConfigList', icon: 'fas fa-bars' },
                        { active: false, name: '存储管理', path: '/genCodeList', icon: 'fas fa-bars' },
                        { active: false, name: '用户管理', path: '/userList', icon: 'fas fa-bars' },
                        { active: false, name: '角色管理', path: '/authorityList', icon: 'fas fa-bars' }
                    ]
                },
                {
                    active: false,
                    name: '数据编辑',
                    icon: 'fas fa-bars',
                    children: [
                        { active: false, name: '系统模块', path: '/categoryList', icon: 'fas fa-bars' },
                        { active: false, name: '数据表名', path: '/summaryTypeList', icon: 'fas fa-bars' },
                        { active: false, name: '检测规则', path: '/thresholdList', icon: 'fas fa-bars' },
                        { active: false, name: '企业数量', path: '/orgNumStatList', icon: 'fas fa-bars' },
                        { active: false, name: '项目数量', path: '/projectNumStatList', icon: 'fas fa-bars' },
                        { active: false, name: '城市指数', path: '/cityIndexStatList', icon: 'fas fa-bars' },
                        { active: false, name: '基地分布', path: '/baseStatList', icon: 'fas fa-bars' },
                        { active: false, name: '技术交易', path: '/techTradeStatList', icon: 'fas fa-bars' }
                    ]
                },
                {
                    active: false,
                    name: '指标体系管理',
                    icon: 'fas fa-bars',
                    children: [
                        { active: false, name: '指标(监控)列表', path: '/metricList', icon: 'fas fa-bars' },
                        { active: false, name: '指标编辑', path: '/metricEdit', icon: 'fas fa-bars' }
                    ]
                }
            ];
            function setId(parentId, menus) {
                menus.forEach((i, idx) => {
                    if (parentId) {
                        i.id = parentId * 10000 + idx + 1;
                    } else {
                        i.id = idx + 1;
                    }
                    if (i.children) {
                        setId(i.id, i.children);
                    }
                });
            }
            setId('', menus);
            this.rawMenus = menus;
            this.menus = menus;
            this.findActiveMenu();
        },
        // getMenus() {
        //     console.log(res);
        //     this.$http
        //         .get('/dataCenterMenu/userMenu', {
        //             name: '系统菜单'
        //         })
        //         .then(res => {
        //             console.log(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;
            });
        },
        getRandomThreshold() {
            let labels = [
                {
                    value: 'minValue',
                    name: '最小预警阀值',
                    down: true
                },
                {
                    value: 'maxValue',
                    name: '最大预警阀值'
                },
                {
                    value: 'increaseValue',
                    name: '增长预警阀值'
                },
                {
                    value: 'decreaseValue',
                    name: '下降预警阀值'
                }
            ];
            this.$http.get('/threshold/getOneThreshold').then(res => {
                let label = labels[Math.floor(Math.random() * 4)];
                let value = label.down
                    ? this.sum(0, res[label.value])
                    : this.sum(res[label.value] + 100, res[label.value]);
                this.$notify({
                    title: '预警消息',
                    message: `${res.category.name}的值为:${value},${label.down ? '已经低于' : '已经超过'}${
                        label.name
                    }:${res[label.value]}`,
                    duration: this.hideNum * 1000
                });
                setTimeout(() => {
                    this.getRandomThreshold();
                }, (this.num || 1) * 1000 * this.sum(1, 9));
            });
        },
        sum(m, n) {
            return Math.floor(Math.random() * (m - n) + n);
        }
    },
    watch: {
        $route(val) {
            this.findActiveMenu(this.rawMenus);
        },
        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,
        TFA
    }
};
</script>
<style lang="less" scoped>
#app {
    height: 100%;
}
/deep/ .aside {
    .el-menu {
        border: none !important;
        &:not(.el-menu--collapse) {
            width: 200px;
        }
    }
}
/deep/ .change-pwd-dialog {
    .captcha-image {
        height: 32px;
        vertical-align: middle;
        margin-left: 10px;
        cursor: pointer;
    }
    .el-dialog__body {
        padding-bottom: 0;
    }
}
.app-header {
    font-size: 0;
    height: 52px !important;
    padding: 0 !important;
    color: #303133;
    background: #fff;
    display: flex;
    align-items: center;
    padding-left: 0;
    box-sizing: border-box;
    position: relative;
    &::after {
        .setBottomLine();
    }
    .header-btn {
        width: 52px;
        height: 52px;
        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: 32px;
        height: 32px;
        border-radius: 50%;
        margin-right: 20px;
        cursor: pointer;
    }
    a {
        &:visited {
            color: @text1;
        }
    }
}

.aside {
    background: @menu-bg;
    transition: all 0.4s ease;
    -ms-overflow-style: none;
    .logo-wrapper {
        font-weight: 200;
        display: flex;
        align-items: center;
        justify-content: center;
        height: 52px;
        color: white;
        font-size: 20px;
        background: fade(black, 20%);
        cursor: pointer;
        &.collapse {
            display: block;
            font-size: 14px;
            text-align: center;
            line-height: 16px;
            box-sizing: border-box;
            padding: 10px 0;
        }
    }
}

.aside::-webkit-scrollbar {
    display: none;
}

.app-main {
    background: @bg;
    height: 100%;
    padding: 0 !important;
}
</style>
