<template>
    <div id="Header" class="header bgc-fff fix border-bottom">
        <div class="header-left ps-a">
            <img src="@/assets/img/logo.png" alt="" class="inline-block">
        </div>
        <div class="app-header-userinfo ps-r flex-center-vertical">
            <div class="menu-box flex ps-r flex-start-center">
                <div class="flex">
                    <el-tooltip v-for="(menu, index) in headerTab" :key="menu.id" :content="menu.terminalName" placement="bottom" effect="light" :disabled="menu.terminalName&&menu.terminalName.length<=7">
                        <span :class="['ft16 menu curs-poin link-btn border-box over-flow ta-c br4 inline-block', index === active ? 'bgc-theme c-fff' : 'bgc-theme-5 c-303133', menu.jumpWay === '2' ? 'triangle' : '']" @click="headMenuClick(menu, index, 'main')">{{ menu.platformCode==='111111' ? menu.name : menu.terminalName }}</span>
                    </el-tooltip>
                </div>
                <el-dropdown v-if="otherDropDownTab && otherDropDownTab.length" trigger="click" class="ml24">
                    <button class="ft16 menu link-btn border-box over-flow ta-c br4 bgc-theme-5 c-303 pd0">
                        其它系统
                        <i class="el-icon-arrow-down el-icon--right" />
                    </button>
                    <el-dropdown-menu slot="dropdown" class="hader-other-menu">
                        <div class="dropdown-panel">
                            <el-dropdown-item v-for="(item, index) in otherDropDownTab" :key="item.id" @click.native="headMenuClick(item, index, 'other')">{{ item.terminalName }}</el-dropdown-item>
                        </div>
                        <span class="bgc-theme-5 edit-btn block ft14 c-167 ta-c line-height40 pointer" @click="editVisible = true">
                            <i class="el-icon-edit-outline mr2 ft14" />
                            编辑
                        </span>
                    </el-dropdown-menu>
                </el-dropdown>
            </div>
            <div class="header-r-box ps-a flex-center-vertical">
                <!-- <span v-for="menu in headMenuArr" :key="menu.id" class="ft18 pd10 c-fff menu pointer" @click="jumpSystem(menu)">{{ menu.name }}</span> -->
                <span class="line" />
                <el-avatar class="mr10" :size="32" :src="circleUrl" />
                <el-dropdown class="mr18">
                    <span class="pointer c-303">
                        {{ userName || '' }}
                        <i class="el-icon-caret-bottom el-icon--right" />
                    </span>
                    <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item @click.native="showPwd">修改密码</el-dropdown-item>
                        <el-dropdown-item divided @click.native="logout">退出登录</el-dropdown-item>
                    </el-dropdown-menu>
                </el-dropdown>
            </div>
            <el-dialog title="修改密码" :visible.sync="dialogVisible" :close-on-click-modal="false" append-to-body center width="400px">
                <div>
                    <el-form ref="changePwdForm" :model="adminEntity" size="mini" :rules="rules" label-width="100px">
                        <el-form-item label="旧密码">
                            <el-input v-model="adminEntity.oldPwd" type="password" placeholder="输入旧密码" :clearable="true" />
                        </el-form-item>
                        <el-form-item label="新密码">
                            <el-input v-model="adminEntity.newPwd1" type="password" placeholder="输入新密码" :clearable="true" />
                        </el-form-item>
                        <el-form-item label="确认新密码">
                            <el-input v-model="adminEntity.newPwd2" type="password" placeholder="输入新密码" :clearable="true" />
                        </el-form-item>
                    </el-form>
                </div>
                <span slot="footer" class="dialog-footer">
                    <el-button type="primary" @click="updatePass">修 改</el-button>
                </span>
            </el-dialog>
        </div>
        <MenuEdit v-if="editVisible" :edit-visible.sync="editVisible" :header-menu="headerTab" :other-menu="otherDropDownTab" @handleUpdateHeaderMenu="fetchNewHeaderMenu" />
    </div>
</template>
<script>
import MenuEdit from './MenuEdit.vue';
import { setStorage, getStorage, removeStorage } from '@/tool/storage';
import tool from '@/tool/appInfo';
import api_user from '@/api/api_user';
import { isEmpty, notEmpty } from '@/tool/func';
import { getMenus, getRouters } from '@/tool/route';
import { getSaasManageKeyPrefix } from '@/router';

export default {
    components: {
        MenuEdit
    },
    props: {
        isLoginPage: {
            type: Boolean,
            default: false
        }
    },
    data() {
        return {
            circleUrl: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
            loading: false,
            dialogVisible: false,
            userName: '',
            adminEntity: {
                oldPwd: '',
                newPwd1: '',
                newPwd2: ''
            },
            rules: {
                oldPwd: [
                    {
                        required: true,
                        message: '请输入旧密码',
                        trigger: 'blur'
                    }
                ],
                newPwd1: [
                    {
                        required: true,
                        message: '请输入新密码',
                        trigger: 'blur'
                    }
                ],
                newPwd2: [
                    {
                        required: true,
                        message: '请再次输入新密码',
                        trigger: 'blur'
                    }
                ]
            },
            userInfo: {},
            headMenuArr: getStorage({ name: 'headerList' }),
            editVisible: false,
            active: 0
        };
    },
    computed: {
        headerTab() {
            return this.headMenuArr && this.headMenuArr.filter(item => item.showHeader) || [];
        },
        otherDropDownTab() {
            return this.headMenuArr && this.headMenuArr.filter(item => !item.showHeader) || [];
        }
    },
    created() {
        this.userInfo = getStorage({ name: 'userInfo' }) || {};
        this.userName = this.userInfo.name || '-';
        if (this.userInfo !== undefined) {
            if (!this.userInfo['changePwd']) {
                this.dialogVisible = this.userInfo.needChangePwd;
            }
            this.userInfo['changePwd'] = true; // 再不点击弹出修改框的情况下，只弹出一次修改框
            this.$store.commit('user/setLoginState', { userInfo: this.userInfo }); // 更新vuex
            setStorage({ name: 'userInfo', content: this.userInfo });
        }
    },
    beforeDestroy() {
        clearInterval(this.timer);
    },
    inject: ['reload'],
    methods: {
        jumpSystem(menu) {
            if (menu.jumpWay === '1') {
                window.location.href = menu.url;
            } else if (menu.jumpWay === '2') {
                window.open(menu.url + '/' + menu.verification, '_blank');
            } else {
                window.alert('不能跳转！');
            }
        },
        logout: function() {
            this.$confirm('确认退出?', '提示', {})
                .then(() => {
                    this.loading = true;
                    this.$store.dispatch('user/logout');
                    this.$message.info({
                        message: '服务正在登出中...',
                        duration: '5000'
                    });
                    setTimeout(() => {
                        // 回到登录页面
                        window.location.href = window.location.origin + `/${process.env.VUE_APP_NAME}/login`;
                    }, 1000);
                    // 回到登录页面
                })
                .catch(() => {
                    this.$message.info('已取消');
                });
        },
        showPwd() {
            this.adminEntity.oldPwd = '';
            this.adminEntity.newPwd1 = '';
            this.adminEntity.newPwd2 = '';
            this.dialogVisible = true;
        },
        updatePass() {
            this.$refs.changePwdForm.validate(valid => {
                if (valid) {
                    this.loading = true;
                    const params = {
                        mobile: this.userInfo.mobile,
                        saasId: tool.app.saasId,
                        platformCode: tool.app.platformCode,
                        oldPassword: this.adminEntity.oldPwd,
                        password: this.adminEntity.newPwd1
                    };
                    api_user.ecloudRetrievePassword(params).then(data => {
                        this.loading = false;
                        this.$store.dispatch('user/logout');

                        this.$message({
                            type: 'success',
                            message: '修改密码成功，请重新登录'
                        });
                        // 回到登录页面
                        this.$router.push({ path: '/login' });
                        this.dialogVisible = false;
                    })
                        .catch(() => {
                            this.loading = false;
                        });
                }
            });
        },
        async headMenuClick(item, index, type) {
            // 原有代码
            if (type === 'other') {
                const temp = this.headerTab.length >= 7 ? [...this.headerTab.slice(0, 6), item] : [...this.headerTab, item];
                const smHeaderList = temp.map((item, index) => ({
                    platformId: item.platformId,
                    sort: index
                }));
                const param = {
                    saasId: this.userInfo.saasId || '',
                    userId: this.userInfo.id || '',
                    smHeaderList: smHeaderList
                };
                try {
                    await api_user.saveHeaderSort(param);
                    await this.fetchNewHeaderMenu();
                } catch {
                    this.$message.error('调取排序接口失败');
                }
            }
            if (item.systemServiceName === 'saasmanage') {
                const params = { 'params': { 'token': item.verification, 'systemServiceName': item.systemServiceName }};
                api_user.querySmMenusListByToken(params).then(resp => {
                    let menus = [...resp.smMenusList];
                    menus = menus.map(({ id, name, url, icon, pid, orderNum, component, type }) => ({
                        id, name, url, path: `/${url}`, icon, pid, order: orderNum, children: [], component, type
                    }));
                    removeStorage({ key: getSaasManageKeyPrefix() + 'menus' });
                    removeStorage({ key: getSaasManageKeyPrefix() + 'menuTree' });
                    setStorage({ key: getSaasManageKeyPrefix() + 'menus', content: menus || [] });
                    setStorage({ key: getSaasManageKeyPrefix() + 'token', content: item.verification });
                    getMenus(menus);

                    const menuTree = getStorage({ name: 'menuTree' });

                    getRouters(menuTree, isEmpty(menus), menus);
                    if (item.jumpWay === '1') {
                        const obj = this.getPath(menuTree);
                        this.$router.push({ path: obj.path });
                    } else if (item.jumpWay === '2') {
                        window.open(item.url, '_blank');
                    }
                    this.reload();
                });
                return false;
            }
            setStorage({ name: 'token', content: item.verification });
            if (item.jumpWay === '1') {
                window.location.href = item.url;
            } else if (item.jumpWay === '2') {
                window.open(item.url, '_blank');
            }
        },
        getPath(menuTree) {
            if (notEmpty(menuTree) && isEmpty(menuTree[0].children)) {
                return menuTree[0];
            }
            return this.getPath(menuTree[0].children);
        },
        compare(key) {
            return (obj1, obj2) => {
                const value1 = obj1[key];
                const value2 = obj2[key];
                if ((value1 || value1 === 0) && (value2 || value2 === 0)) {
                    if (value1 > value2) {
                        return 1;
                    }
                    return -1;
                }
                if ((value1 || value1 === 0) && (!value2 && value2 !== 0)) {
                    return -1;
                }
                if ((!value1 && value1 !== 0) && (value2 || value2 === 0)) {
                    return 1;
                }
                if ((!value1 && value1 !== 0) && (!value2 && value2 !== 0)) {
                    return 0;
                }
                return 0;
            };
        },
        async fetchNewHeaderMenu() {
            try {
                const param = {
                    params: {
                        terminal: 'WEB',
                        userId: this.userInfo.id || ''
                    }
                };
                const { smHeaderList } = await api_user.querySmMenusList(param);
                smHeaderList.sort(this.compare('sort'));
                removeStorage({ name: 'headerList' });
                setStorage({ name: 'headerList', content: smHeaderList });
                this.headMenuArr = getStorage({ name: 'headerList' });
            } catch {
                this.$message.error('调取接口失败');
            }
        }
    }
};
</script>
<style lang="less" scoped>
.header {
	height: 80px;
	color: #303133;
	line-height: 80px;
	box-sizing: border-box;
	font-size: 24px;
}

.header-left {
    left: 0;
    top: 0;
    img {
        width: 100%;
    }
}

.header-left {
    padding-left: 24px;
    padding-right: 29px;
    width: 256px;
    box-sizing: border-box;
}

.menu-box {
    width: calc(100% - 200px);
    height: 76px;
    overflow-x: auto;
    overflow-y: hidden;
    white-space: nowrap;
    .link-btn {
        width: 120px;
        height: 40px;
        line-height: 38px;
        box-sizing: border-box;
        border: 1px solid #f2f6fc;
        &:not(:first-of-type) {
            margin-left: 24px;
        }
    }
    .link-btn:hover {
        border: 1px solid #e0e0e0;
    }
}
.menu-box::-webkit-scrollbar-thumb{
    background-color: var(--middleThemeColor);
}
.menu-box::-webkit-scrollbar {
    height: 6px !important;
}

.app-header-userinfo {
	padding-left: 256px;
	height: 80px;
}

.header-r-box {
    right: 0;
    top: 0;
}

.span-space {
	margin: 0 16px 0;
}

.sign-btn {
	border-radius: 3px;
	color: #fff;
	padding: 2px 6px;
	margin-left: 5px;
	&.in {
		background: var(--themeColor);
	}
	&.out {
		background: #c8c9cc;
	}
}
.curs-poin{
    cursor:pointer;
}
.edit-btn {
    height: 40px;
}
.triangle {
    position: relative;
    &::before {
        content: '';
        position: absolute;
        right:0;
        top: 0;
        width: 0;
        border-top: 12px solid  var(--subThemeColor);// #e4e7ed;
        border-left: 12px solid transparent;
    }
}
.dropdown-panel {
    max-height: 564px;
    overflow-y: auto;
}
</style>
