<template>
    <!-- 公司名 -->
    <div class="name-box font12" style="padding-top: 2px">
        <span style="margin-right: 10px; margin-left: 10px">
            {{ NAMES[userStore.userInfo?.identity] }}
        </span>
    </div>
    <!-- 组织名 -->
    <div v-if="isOrgsShow" class="name-box font12">
        <el-dropdown trigger="click" class="triangle-box" v-if="isIdentity" @command="handleCommand" :max-height="300">
            <div>
                {{ userStore.orgName }}
                <el-icon class="triangle">
                    <i-ep-arrow-down />
                </el-icon>
            </div>
            <template #dropdown>
                <el-dropdown-menu>
                    <el-dropdown-item
                        v-for="(it, index) in userStore.orgIdArr"
                        :key="index"
                        :command="it.id"
                        :value="it.name"
                        :style="{
                            height: it.disable ? '0px' : 'auto'
                        }"
                    >
                        {{ !it.disable ? it.name : "" }}
                    </el-dropdown-item>
                </el-dropdown-menu>
            </template>
        </el-dropdown>
        <span v-else>{{ userStore.orgName }}</span>
    </div>
    <!-- 用户名 -->
    <div class="name-box font12">
        <el-dropdown trigger="click" class="triangle-box">
            <div>
                {{ userStore.userInfo.nickname }}
                <el-icon class="triangle">
                    <i-ep-arrow-down />
                </el-icon>
            </div>
            <template #dropdown>
                <el-dropdown-menu>
                    <el-dropdown-item @click="logout">
                        <el-icon> <i-ep-switch-button /> </el-icon>重新登录
                    </el-dropdown-item>
                </el-dropdown-menu>
            </template>
        </el-dropdown>
    </div>
</template>

<script setup lang="ts">
import { logoutApi } from "@/api/modules/login";
import { useMsg } from "@/hooks/useMsg";
import { useUserStore } from "@/stores/modules/user";
import { ElMessageBox } from "element-plus";
import { usePathUrl } from "@/hooks/usePathUrl";
const userStore: any = useUserStore();

const NAMES: Record<string, any> = {
    1: userStore?.userInfo?.companyName,
    2: userStore?.userInfo?.supplierName,
    3: userStore?.userInfo?.customerName
};
const THENIDS: Record<number, any> = {
    1: userStore?.orgId,
    2: userStore?.userInfo?.supplierId,
    3: userStore?.userInfo?.customerId
};
const isOrgsShow = computed(() => {
    if (userStore.orgIdArr && userStore.orgIdArr.length && userStore.userInfo?.identity !== 2) {
        return true;
    } else {
        return false;
    }
});
const isIdentity = computed(() => {
    return userStore.userInfo?.identity !== 2 ? true : false;
});
// 设置用户数据
const setUserData = (params: any) => {
    // 更新组织id
    userStore.setOrgId(params.orgId as number);
    // 更新组织名称
    userStore.setOrgName(params.orgName);
    //更新组织code
    userStore.setOrgCode(params.orgCode as number);
};

//组织改变;
const handleCommand = (val: number | null) => {
    const orgIdArr: any[] = userStore?.orgIdArr || [];
    // 组织不能为空
    if (!Array.isArray(orgIdArr) || !orgIdArr.length) {
        return;
    }
    // 获取组织ID
    let identity = userStore?.userInfo?.identity;
    const id = userStore?.userInfo ? THENIDS[identity] : null;
    //设置默认id
    const orgId: number | null = val ? val : id;
    // 获取当前组织下标
    const index: number = orgIdArr.findIndex((it: any) => {
        return it.id === orgId;
    });
    // 获取组织名称
    let orgName: string = index !== -1 ? orgIdArr[index]?.name : "";
    let orgCode: string = index !== -1 ? orgIdArr[index]?.code : "";
    console.log(orgCode, "=改变=");
    setUserData({
        orgId,
        orgName,
        orgCode
    });
};
const handleCommandInit = () => {
    const orgIdArr: any[] = userStore?.orgIdArr || [];
    const index: number = orgIdArr.findIndex((it: any) => {
        return it.isDefault;
    });
    // 获取组织名称
    let orgName: string = index !== -1 ? orgIdArr[index]?.name : orgIdArr[0]?.name;
    let orgCode: string = index !== -1 ? orgIdArr[index]?.code : orgIdArr[0]?.code;
    setUserData({
        // orgId,
        orgName,
        orgCode
    });
};
handleCommandInit();

//通知单点退出登录
const getUcOffline = (redirectUrl: any) => {
    let httpUrl = import.meta.env.VITE_SINGLE_URL + "uc/offline";
    fetch(httpUrl, {
        method: "POST",
        credentials: "include",
        keepalive: true,
        headers: {
            Authorization: userStore.phpToken,
            "Refresh-Authorization": userStore.refreshToken
        }
    })
        .then((res: any) => {
            if (res.status === 200) {
                useMsg("success", "退出登录成功 ！");
                setTimeout(() => {
                    console.log(redirectUrl, "=redirectUrl=");
                    location.href = redirectUrl;
                    userStore.$reset();
                    // 3.清除 本地
                    localStorage.clear();
                }, 500);
            }
        })
        .catch(() => {
            useMsg("error", "退出登录失败,请稍后再试 ！");
        });
};
// 退出登录
const logout = () => {
    ElMessageBox.confirm("您是否确认重新登录?", "温馨提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
    }).then(async () => {
        //1.退出登录
        const result: any = await logoutApi();
        if (result.status === 200 || result.status === 40003 || result.status === 401) {
            //4.通知单点退出登录
            getUcOffline(usePathUrl());
        } else {
            useMsg("error", result.message);
        }
    });
};
</script>

<style scoped lang="scss">
.name-box {
    position: relative;
    display: flex;
    align-items: center;
    color: #303133;
    cursor: pointer;
    ::v-deep(.el-dropdown) {
        color: #303133;
    }
}
.name-box::before {
    position: absolute;
    top: 50%;
    display: block;
    height: 20px;
    content: "";
    border-left: 1px solid #e4e7ed;
    transform: translateY(-50%);
}
.triangle-box {
    margin: 0 10px;
}
.triangle {
    margin-left: 3px;
    transition: transform 0.3s ease; /* 添加动画过渡效果 */
}
.triangle-box:hover .triangle {
    transform: rotate(180deg); /* 鼠标悬停时旋转180度 */
}
</style>
