<template>
    <div class="kf-nav-container w-100 h-100 flex-row-start-center" v-show="props.show" :style="cardStyle" :class="'vivify '+ buttonClass">
        <div class="flex-row-start-center gap-16">
            <div class="nav-item kf-nav-container-logo" v-if="(props.logoShow === undefined || props.logoShow)">
                <img v-if="props.logo.includes('.')" :src="getImageUrl(props.logo)" alt="">
                <img v-else src="../../../../public/img/logo3.png">
            </div>
            <div class="nav-item kf-nav-container-name">{{ props.sysName }}</div>
            <div class="nav-item kf-nav-container-name1">{{ props.sysSubName }}</div>
            <div class="nav-item kf-nav-container-tabs" v-if=" (props.showBtns==undefined || props.showBtns) && menuList?.length>0">
                <div class="kf-3dc-atom-item" v-show="page.show" v-for="(page,index) in menuList" :key="index+'nav-btn'"
                     :style="{background:(isActive == index ? props.highlightColor:props.btnColor),borderColor:(isActive == index ? props.btnSelectedBorderColor:props.btnBorderColor)}"
                     @click="menuHandleClick(page,index)">
                    {{ page.name }}
                </div>
            </div>
        </div>
        <div class="nav-item kf-nav-container-name alert_content" v-if="props.alertShow">
            <span><b v-for="(alert,index) in unreadAlerts" :key="alert.uuid + index" @click="showAlert(alert)">{{
          alert.title + " " + alert.alarmTime.getHours() + ":" + alert.alarmTime.getMinutes() + ":" + alert.alarmTime.getSeconds() + "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"
        }}</b></span>
        </div>
        <div class="flex-row-end-center gap-16">
            <div class="nav-item kf-nav-container-date">
                <div class="kf-nav-container-date-left" v-if="props.dateShow">
                    <span>{{ time }}</span>
                    <span>UTC+8.0</span>
                </div>
                <div class="kf-nav-container-date-right" v-if="props.weekShow">
                    <span class="nav-week">{{ getWeek() }}</span>
                    <span class="nav-date">{{ getFormatData() }}</span>
                </div>
            </div>
            <div class="nav-item kf-nav-container-name" v-if="props.alertCountShow">
                <el-popover placement="top-start" title="" :width="250" trigger="click" popper-class="alert-popover-box">
                    <template #reference>
                        <el-badge :value="unreadCount()" class="item" type="primary">
                            <el-button @click="showAlertList($event)">消息</el-button>
                        </el-badge>
                    </template>
                    <div v-show="alertListFlag" class="nav-alert-list">
                        <div class="nav-alert-list-item"
                             v-for="(alert,index) in unreadAlerts"
                             :key="alert.uuid + index +'alert'"
                             @click="showAlert(alert)"
                            :title="(alert.unread ? '*' : '&nbsp;') + alert.title + ' ' + alert.alarmTime.getHours() + ':' + alert.alarmTime.getMinutes() + ':' + alert.alarmTime.getSeconds()">
                            {{(alert.unread ? "*" : "&nbsp;") + alert.title + " " + alert.alarmTime.getHours() + ":" + alert.alarmTime.getMinutes() + ":" + alert.alarmTime.getSeconds() }}
                        </div>
                    </div>
                </el-popover>
            </div>
            <div class="nav-item kf-nav-container-icon">
                <svgIcon class="nav-icon" v-for="icon in icons" :key="icon.value" v-show="props[icon.showKey]" :name="icon.icon"
                         @click="iconHandle(icon)" />
                <section class="kf-nav-user" v-if="userShow">
                    <div class="user-header">用户设置 / <span>{{ userInfo.userName }}</span></div>
                    <div class="user-quit" @click="userQuit">退出登录</div>
                </section>
            </div>
        </div>
    </div>
</template>

<script>
import {
    ref,
    watch,
    onMounted,
    getCurrentInstance,
    onUnmounted,
    computed,
} from "vue";
import { useRouter } from "vue-router";
import styleManager from "../utils/style.vue";
import svgIcon from "../../uiWidget/svgIcon.vue";
import pageModel from "../model/page";
import utils from "../utils/utils.vue";
import { ElMessage } from "element-plus";
import messageModel from "../model/message";
import eventManager from "../utils/event";
import alertModel from "@/components/ui/model/alert";
import Const from "@/utils/const";
import { openFullscreen, cancelFullscreen } from "@/utils/tools";

export default {
    components: { svgIcon },
    name: "kfNavigation",
    props: {
        props: {
            type: Object,
            default: () => {},
        },
        eventList: {
            type: Array,
            default: () => [],
        },
        eventScript: {
            type: String,
        },
    },
    widgetConfig: {
        parent: "base",
        rank: 12,
        label: {
            zh: "导航栏",
        },
        category: "业务",
        component: "kfNavigation",
        display: true,
        version: 1,
        icon: "icon-anniu",
        defaultSize: {
            x: 1920,
            y: 60,
        },
        imgName: "kfNavigation",
        state: {
            isAdd: false,
            isCondition: false,
        },
    },
    setup(props) {
        let buttonClass = ref("");
        let userInfo = ref({})
        const router = useRouter();

        let userShow = ref(false);
        let cardStyle = ref({});
        const { proxy } = getCurrentInstance();
        let time = ref(""),
            // menuList = ref([]),
            isActiveIndex = ref(0),
            //isActive = ref({}),
            timer = null,
            icons = [
                {
                    label: "主题切换",
                    value: "theme",
                    showKey: "themeChangeShow",
                    icon: "dayTheme",
                },
                {
                    label: "返回首页",
                    value: "backHome",
                    showKey: "isHomeShow",
                    icon: "backHome",
                },
                {
                    label: "全屏",
                    value: "fullScreen",
                    icon: "fullScreen",
                    showKey: "fullSceneShow",
                },
                {
                    label: "用户设置",
                    value: "userSet",
                    icon: "userSet",
                    showKey: "userShow",
                },
            ];

        const data = computed(() => {
            if (props.props.datas?.logo != undefined) {
                return props.props.datas;
            } else {
                return {
                    logo: "",
                    logoShow: true,
                    sysName: "系统名称",
                    sysNameShow: true,
                    sysSubName: "系统副标题",
                    sysSubNameShow: true,
                    pageTabShow: true,
                    dateShow: true,
                    weekShow: true,
                    themeChangeShow: true,
                    isHomeShow: true,
                    fullSceneShow: true,
                    userShow: true,
                };
            }
        });
        let defaultHandler = ref({});
        onMounted(() => {
            refreshEvents();
            loadUser()
            cardStyle.value = styleManager.updateStyle(proxy);
            timer = setInterval(() => {
                time.value = updateTime();
            }, 1000);
            let entrancePage = pageModel.pageList.value.find(
                (page) => page.isEntrance === true
            );
            buttonClass.value = styleManager.updateClass(proxy);
        });

        const loadUser =function (){
            if(pageModel.publishWithUser.value){
                let _info=JSON.parse(localStorage.getItem("projectUser"));
                if(_info?.data){
                    userInfo.value = _info.data;
                }
            }else{
                userInfo.value = JSON.parse(localStorage.getItem("KC_USER"));
            }
        }
        const refreshEvents = function (firstTime = false) {
            eventManager.registerEvent(proxy);
        };

        const eventHandler = computed(() => {
            console.log("计算事件处理");
            return eventManager.loadEventHandler(
                defaultHandler,
                undefined,
                props.props.pageName
            );
        });

        watch(defaultHandler, () => {}, {
            deep: true,
        });

        const menuList = computed(() => {
            let nameKey = "btnList";
            let res = [];
            if (props.props[nameKey]?.length == 1 && props.props[nameKey][0] == "0") {
                if (pageModel.pageList.value?.length > 0) {
                    pageModel.pageList.value.forEach((page, index) => {
                        if (index < 5) {
                            res.push({
                                name: page.name,
                                index: index,
                                show: true,
                            });
                        }
                    });
                }
                pageModel.updatePropValue(nameKey, res);
            } else {
                res = props.props[nameKey];
            }
            return res;
        });
        let isActive = computed(() => {
            let activeIndex = props.props.currValue;
            if (props?.eventList?.length > 0) {
                props.eventList.forEach((item) => {
                    if (props.props && props.props[item.name]?.actions?.length > 0) {
                        let _param = null;
                        props.props[item.name].actions.some((action) => {
                            if (action.name === "gotoPage" && pageModel.currPage.value.uuid == action?.source?.page?.uuid) {
                                _param = action.params;
                                return true;
                            }
                            return false;
                        });
                        if (_param != null) {
                            props.props.btnList.some((btnItem) => {
                                if (btnItem.name === _param) {
                                    activeIndex = btnItem.index;
                                    return true;
                                }
                                return false;
                            });
                        }
                    }
                });
            }
            return activeIndex;
        });
        onUnmounted(() => {
            clearInterval(timer);
        });
        pageModel.watchProps(props, watch, proxy, (changes) => {
            if (styleManager.styleChanged("kfNavigation", changes)) {
                cardStyle.value = styleManager.updateStyle(proxy);
            }
            if (styleManager.classChanged("kfNavigation", changes)) {
                buttonClass.value = styleManager.updateClass(proxy);
            }
        });
        const getFormatData = () => {
            const date = new Date();
            let year = date.getFullYear();
            let mounth = date.getMonth() + 1;
            mounth = mounth < 10 ? "0" + mounth : mounth;
            let day = date.getDate();
            day = day < 10 ? "0" + day : day;
            return year + "/" + mounth + "/" + day;
        };
        const updateTime = () => {
            let date = new Date();
            let hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
            let minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
            let seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
            return hours + ":" + minutes + ":" + seconds;
        };
        const getWeek = () => {
            let date = new Date();
            let weekMap = [
                "星期天",
                "星期一",
                "星期二",
                "星期三",
                "星期四",
                "星期五",
                "星期六",
            ];
            return weekMap[date.getDay()];
        };
        const iconHandle = (icon) => {
            if (icon.value == "fullScreen") {
                if (document.fullscreenElement === null) {
                    openFullscreen();
                } else {
                    cancelFullscreen();
                }
            } else if (icon.value == "backHome") {
                let entrancePage = pageModel.pageList.value.find(
                    (page) => page.isEntrance === true
                );
                if (entrancePage?.uuid) {
                    isActive.value = entrancePage;
                    loadPage(entrancePage);
                } else {
                    ElMessage({type: "error", grouping: true, customClass: "kf-3dc-create-success", message: messageModel.messageTip.noHomePage});
                }
            } else if (icon.value === "userSet") {
                userShow.value = !userShow.value;
            }
        };
        const menuHandleClick = (menu, index) => {
            isActive.value = index;
            try {
                pageModel.updatePropValue("currValue", index, props);
                eventHandler.value.click(menu, event, menu.name);
            } catch (e) {
                console.error(e);
            }
        };
        const loadPage = (value) => {
            let p = {
                componentKey: props.props.key,
                fields: "currValue",
                value: props.props,
                pageId: props.props.pageId,
            };
            utils.loadPage(value.uuid, value.version, () => {}, JSON.stringify(p));
        };

        // 退出登录
        const userQuit = () => {
            const { projectUuid, pageId, shortKey } = router.currentRoute.value.params;
            let _projectUuid = projectUuid ?projectUuid:pageModel.currProject.value.uuid;
            let _pageId = pageId?pageId:pageModel.currPage.value.uuid;
            let _shortKey = shortKey?shortKey:router.currentRoute.value.params.shortLink;
            if(_shortKey===undefined){
                ElMessage({type: "error", grouping: true, customClass: "kf-3dc-create-success", message:messageModel.messageTip.notExitLogin});
            }else{
                router.replace({
                    path: `/projectLogin/${_projectUuid}/${_pageId}/${_shortKey}`,
                });
            }

        };

        const getImageUrl = function (pubUuid) {
            let url = Const.servicePath.value + "/api/repo/kf-pub-resource/load-file?uuid=" + pubUuid;
            return url;
        };

        const showAlert = (alert) => {
            alertListFlag.value = false;
            alert.unread = false;
            alertModel.showAlert(alert);
        };

        const alertListFlag = ref(false);
        const alertListStyle = ref({
            position: "absolute",
        });

        const showAlertList = (event) => {
            alertListFlag.value = true;
            alertListStyle.value.top = event.clientY + "px";
            alertListStyle.value.left = event.clientX + "px";
        };


        const unreadAlerts = computed(() => {
             return alertModel.alerts.value.length > 50 ?alertModel.alerts.value.slice(alertModel.alerts.value.length - 30, alertModel.alerts.value.length) : alertModel.alerts.value
        });

        return {
            alertListFlag,
            alertListStyle,
            showAlertList,
            cardStyle,
            value: 30,
            time,
            getFormatData,
            getWeek,
            icons,
            iconHandle,
            isActive,
            menuList,
            menuHandleClick,
            data,
            isActiveIndex,
            defaultHandler,
            eventHandler,
            userInfo,
            userQuit,
            userShow,
            getImageUrl,
            unreadAlerts,
            unreadCount: alertModel.getUnreadCount,
            showAlert,
            buttonClass,
        };
    },
};
</script>

<style lang="scss">
.kf-nav-container {
    padding: 5px 8px 5px 8px;
    flex-direction: row;
    align-items: center;
    gap: 16px;
    border-radius: 6px;
    background: #0e0e0e;
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-family: Alibaba PuHuiTi;
    /*grid-template-columns: 1fr 1.2fr 5fr 1.2fr 1fr;*/
    .nav-item {
        // border: 1px solid #555;
        min-height: 3rem;
        display: flex;
        align-items: center;
    }

    .kf-nav-container-logo {
        font-weight: 600;
        color: #0c93e6;
        display: flex;
        align-items: center;
        text-align: center;
        display: flex;
        align-items: center;

        img {
            height: 30px;
            object-fit: cover;
        }
    }

    .kf-nav-container-name {
        font-weight: 500;
        color: #fff;
        display: flex;
        align-items: center;
        text-align: center;
    }

    .kf-nav-container-name1 {
        color: rgba(255, 255, 255, 0.44);
        font-style: normal;
        font-weight: 400;
        font-size: 12px;
    }

    .kf-nav-container-date {
        display: flex;
        justify-content: space-between;
        align-items: center;
        max-width: 180px;

        &-left {
            font-size: 15px;
            font-weight: 600;
            color: #0094ff;
            display: flex;
            flex-direction: column;
            align-items: center;

            span:first-child {
                letter-spacing: 1px;
            }

            span:last-child {
                font-size: 12px;
                color: #888;
            }
        }

        &-right {
            font-size: 15px;
            font-weight: 600;
            color: #0094ff;
            display: flex;
            flex-direction: column;
            align-items: center;

            span:first-child {
                letter-spacing: 1px;
            }

            span:last-child {
                font-size: 12px;
                color: #888;
            }
        }
    }

    .kf-nav-container-icon {
        display: flex;
        justify-content: space-around;
        align-items: center;
        max-width: 180px;

        .nav-icon {
            width: 30px;
            height: 30px;
            display: flex;
            align-items: center;
            justify-content: center;
            // padding: 3px;
        }

        .nav-icon:hover {
            background-color: rgba(0, 148, 255, 0.2);
            // box-shadow: 0 0 5px 3px rgba(0, 148, 255,0.3);
            border-radius: 50%;
        }

        .kf-nav-user {
            display: flex;
            width: 273px;
            height: 205px;
            position: fixed;
            z-index:1;
            right: 10px;
            top: 60px;
            padding: 8px;
            flex-direction: column;
            align-items: flex-start;
            gap: 8px;
            border-radius: 4px;
           /* border: 1px solid #777777;*/
           background: var(--100, #161616);
            /* 投影 */
            box-shadow: 0px 0px 20px 0px rgba(0, 0, 0, 0.5);
            color: #fff;
            font-family: Alibaba PuHuiTi;
            font-size: 14px;
            font-style: normal;
            line-height: normal;
            text-transform: capitalize;
            transform-origin: right top;
            animation: visible-ani-true 0.2s 0s ease-in-out;

            .user-header {
                display: flex;
                padding: 8px;
                align-items: flex-start;
                gap: 4px;
                font-weight: 500;
                align-self: stretch;

                span {
                    color: rgba(255, 255, 255, 0.7);
                }
            }

            .user-quit {
                width: 100%;
                height: 30px;
                text-align: center;
                line-height: 30px;
                // border: 1px solid #777777;
                color: rgba(255, 255, 255, 0.7);
                background: rgba(33, 33, 33);
                transition: all 0.4s;
                border-radius: 5px;
            }

            .user-quit:hover {
                background: rgba(66, 66, 66);

                color: #fff;
            }
        }
    }

    .kf-nav-container-tabs {
        border-width: 0;
        border-style: solid;
        display: flex;
        padding: 0;
        flex-direction: row;
        justify-content: flex-start;
        gap: 1rem;
        align-items: center;
        overflow: hidden;

        .kf-3dc-atom-item {
            min-width: 80px;
            padding: 2px 5px;
            height: 100%;
            background: transparent;
            border: none;
            display: flex;
            justify-content: center;
            align-items: center;
            color: inherit;
            font-size: inherit;
            border-radius: 0;
            font-family: inherit;
            cursor: pointer;
            border-radius: 5px;
            border: 1px solid rgba(255, 255, 255, 0);
            transition: all 0.2s linear 0s;
        }

        .kf-3dc-atom-item-active {
            border-radius: 5px;
            border: 1px solid rgba(255, 255, 255, 0.12);
            background: #305792;
        }
    }
}

.gap-16 {
    gap: 16px;
}

@keyframes marquee {
    0% {
        transform: translateX(0);
    }
    100% {
        transform: translateX(-100%);
    }
}

.alert_content {
    flex: 1;
    overflow: hidden;

    span {
        display: block;
        width: auto;
        white-space: nowrap;
        animation: marquee 60s linear infinite;
    }
}
.alert-popover-box.el-popper {
    /* 投影 */
    box-shadow: 0px 0px 20px 0px rgba(0, 0, 0, 0.5);
    border-radius: 4px;
    border: 1px solid #303030;
    background: var(--100, #161616);
    line-height: normal;
    text-transform: capitalize;
    transform-origin: right top;
    animation: visible-ani-true 0.2s 0s ease-in-out;
    padding: 0;
}
.nav-alert-list {
    /* position: absolute;*/
    width: 250px;
    padding: 8px 0;
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;

    color: #fff;
    font-family: Alibaba PuHuiTi;
    font-size: 14px;
    font-style: normal;

    height: 250px;
    overflow-y: auto;
    display: flex;
    .nav-alert-list-item {
        width: 100%;
        height: 25px;
        flex-shrink: 0;
        display: block;
        line-height: 25px;
        text-overflow: ellipsis;
        overflow: hidden;
        white-space: nowrap;
        border-bottom: 1px solid #000;
        padding-left: 10px;
    }
}
</style>
