<template>
    <!-- 页面头部 -->
    <header>
        <!-- 顶部导航 -->
        <nav class="headerNav">
            <div class="inner">
                <div class="left">
                    <span>您好,欢迎来到农副产品供销网!</span>
                </div>
                <div class="right">

                    <div class="menu">
                        <button class="reg" @click="goTopic">
                            <img src="http://img.bjzxtw.org.cn/master/bjzxtw/public/head/topicon1.png" alt="商圈">商圈
                        </button>
                        <button class="reg" @click="goAdvertising">
                            <img src="http://img.bjzxtw.org.cn/master/bjzxtw/public/head/topicon2.png" alt="广告服务">广告服务
                        </button>
                    </div>
                    <div class="right-top-menu">
                        <button class="reg" @click="goLogin" v-show="!showToken">
                            <img src="http://img.bjzxtw.org.cn/master/bjzxtw/public/head/topicon3.png" alt="登录">登录
                        </button>
                        <button class="reg" @click="goRegister" v-show="!showToken">
                            <img src="http://img.bjzxtw.org.cn/master/bjzxtw/public/head/topicon4.png" alt="注册">注册
                        </button>
                        <button class="reg" @click="userCenter" v-show="showToken">
                            <img src="http://img.bjzxtw.org.cn/master/bjzxtw/public/head/topicon3.png" alt="用户信息">{{ username }}
                        </button>
                        <button class="reg" @click="goSearch">
                            <img src="http://img.bjzxtw.org.cn/master/bjzxtw/public/head/searchicon.png" alt="搜索">搜索
                        </button>
                    </div>
                    <ul class="userInfo11" v-if="isShow">
                        <li @click="gotosystem">个人中心</li>
                        <li @click="exit">退出</li>
                    </ul>
                </div>

                <div class="phone_head_btn" @click="togglePanel"></div>
                <!-- <div class="phone_head_btn"></div> -->
            </div>
        </nav>
        <!-- 头部logo -->
        <div class="headerLogo">
            <div class="inner">
                <img :src="logo" :alt="webSiteName" class="left" @click="backHome">

                <div class="titlead" v-if="adImg">
                    <a href="http://sannongdy.org.cn/" v-if="adImg.image_url==null" target="_blank" :title="adImg.place_name">
                        <img :src="adImg.thumb" :alt="adImg.place_name" data-tag="imgurl.ad_tag">
                    </a>     
                    <a :href="adImg.image_url" v-else :title="adImg.ad_name">
                        <img :src="adImg.image_src" :alt="adImg.ad_name" data-tag="imgurl.ad_tag">
                    </a>
                </div>

                
                <div class="logo_right_box">
                    
                    <div class="logo_right_btn" @click="goTopic">
                        <img class="logo_right_btn_img" src="../../public/image/4.png" alt="商圈">
                        <span class="logo_right_btn_text" >商圈</span>
                    </div>
                     
                    <div class="logo_right_btn" @click="user_fun">
                        <img class="logo_right_btn_img" src="../../public/image/6.png" alt="用户">
                        <span class="logo_right_btn_text" >用户</span>
                    </div>
                    <div class="logo_right_btn" @click="goSearch">
                        <img class="logo_right_btn_img" src="../../public/image/7.png" alt="搜索">
                        <span class="logo_right_btn_text" >搜索</span>
                    </div>

                </div>

            </div>
        </div>
        <el-dialog v-model="dialogTableVisible" title="" width="800">
            <div class="tips">
                <p>
                    <img src="../../public/topic/tips.png" alt="">
                    提示:注册请联系管理员操作!
                </p>
                <p>
                    联系电话:010-56019387
                </p>
                <p>
                    QQ ： 2909421493 、213552413
                </p>
            </div>
        </el-dialog>

        
        <el-dialog v-model="dialogTableVisible_phone" width="800"> 
            <div class="tips">
                <p>
                    <!-- <img src="http://img.bjzxtw.org.cn/master/bjzxtw/public/topic/tips.png"> -->
                    <img src="@/public/topic/tips.png">
                    注册请联系管理员操作!
                </p>
                <p>联系电话:010-56019387</p>
                <p>QQ ： 2909421493 、213552413</p>

                <div class="dialog_load_btn" @click="phone_close_fun">登录</div> 

            </div>
        </el-dialog>

        <section class="HomePanel_out" v-show="panelVisible">
        <!-- <section class="HomePanel_out" v-show="true">  -->
            <HomePanel></HomePanel> 
        </section>

    </header>
</template>

<script setup>


// 引入全局状态-HomePanel_out
const panelVisible = useState('panelVisible')


//1.加载基本依赖 start ---------------------------------------->
import { ref, watch, onMounted } from 'vue'
import { ElDialog,ElMessage } from 'element-plus'
import { getToken, setToken, removeToken } from '@/store/useCookieStore'
import { setTicket, removeTicket } from '@/store/useticketStore'
//网站地址
const { $webUrl, $CwebUrl, $BwebUrl, $LoginWebUrl } = useNuxtApp()
//1.加载基本依赖 end ---------------------------------------->

//1.登录逻辑 start ---------------------------------------->
let ticket = ref('')
let token = ref('')
let route = useRoute()

//页面每次刷新先判断一下用户状态是否已经过期了
//如果没有过期再储存token
ticket.value = route.query.ticket
token.value = route.query.admintoken

if (ticket.value) {
    setTicket(ticket.value)
}
if (token.value) {
    setToken(token.value)
}

//搜索框
let keyword = useState('keyword', () => '')
//用户名
let username = useState('username', () => '用户中心')
//是否删除
let isDel = useState('isDel', () => 1)
//是否显示用户中心
let isShow = useState('isShow', () => false)

let token1 = useState("token1", () => '')
let showToken = useState("showToken", () => '')
token1.value = getToken()




//检测登录状态
let tokenStatus = ref('');
tokenStatus.value = getToken()
if (tokenStatus.value == undefined) {
    // console.log("SSR waring ---------- SSR waring ---------- SSR waring ---------->")
    // console.log('错误：未获取到用户token,如果在本地测试请忽略！');
    // console.log("SSR waring ---------- SSR waring ---------- SSR waring ---------->")
} else {
    console.log(tokenStatus.value);
}

//点击登录按钮
let goLogin = () => {
    //开启线上登录模式 start---------------------------------------->
    isDel.value = 0
    token1.value = getToken()
    //王鹏
    //window.open($BwebUrl + "/auth/login.php?backurl=" + $CwebUrl, '_blank');
    //刘佳伟
    //window.open($LoginWebUrl + "/api/goLogin?backurl=" + $CwebUrl, '_blank');
    //党云龙
    window.open($BwebUrl + "/#/login?backurl=" + $CwebUrl, '_blank');
    //开启线上登录模式 end---------------------------------------->

    //开启本地登录模式 start---------------------------------------->
    // window.location.href = $BwebUrl + "/auth/login.php?backurl=" + $CwebUrl;
    //"http://adminpre.bjzxtw.org.cn/auth/login.php?backurl=http://nwpre.bjzxtw.org.cn";
    //开启本地登录模式 end---------------------------------------->
}
let dialogTableVisible = ref(false)
let dialogTableVisible_phone = ref(false)

//点击注册按钮
let goRegister = () => {
    dialogTableVisible.value = true
}

//点击用户中心
let userCenter = () => {
    if (isShow.value) {
        isShow.value = false
        return
    } else {
        isShow.value = true
        return
    }
}
//2.登录逻辑 end ---------------------------------------->

//3.跳转菜单逻辑 start ---------------------------------------->
let gotosystem = () => {
    let url = $BwebUrl + '/#/login?userurl=' + $CwebUrl;
    isShow.value = false;
    //window.location.href = url; 
    window.open(url, '_blank');
}

//点击退出按钮
let exit = () => {
    window.location.href = $CwebUrl;
    isShow.value = false;
    isDel.value = 1
    token1.value = getToken()

    let tokendata = getToken()
    console.log("用户退出登录======token为：", tokendata)
    //王鹏
    //let url = $BwebUrl + '/auth/logout.php?backurl=' + $CwebUrl + '&admintoken=' + tokendata;
    //刘佳伟
    let url = $LoginWebUrl + '/api/logout?backurl=' + $CwebUrl + '&admintoken=' + tokendata;
    window.location.href = url;
    removeToken()
    removeTicket()
}

//点击返回首页
let backHome = () => {
    window.location.href = $CwebUrl;
}

//点击搜索按钮
let goSearch = () => {
    const route = `/search/search?keyword=${keyword.value}`;
    window.location.href = route;
}

// 点击广告服务
let goAdvertising = () => {
    //本地启动广告服务
    //window.open('/advertising?activeName=1', '_blank');
    //线上启动
    if (getToken()) {
        window.open($CwebUrl + '/advertising?activeName=1', '_blank');
    } else {
        goLogin()
    }
}

//点击商圈
let goTopic = () => {
    //本地启动//测试
    // window.open('/topic', '_blank');


    if (getToken()) {
        window.open($CwebUrl + '/topic', '_blank');
    } else {
        goLogin()
    }
}


    //点击用户==手机版11
 let user_fun = () => {
            
            if (getToken()) {//已经登录
                 goLogin()


            } else {//没有登录

                dialogTableVisible_phone.value = true
                // alert("请先登录");
                
                return
                
            }

    }
 // 添加关闭对话框处理函数
const phone_close_fun = () => {
    // 在这里可以添加关闭对话框前需要执行的逻辑
     
    dialogTableVisible_phone.value = false; // 确保对话框关闭
    goLogin()
}

//监听token状态
watch(token1, (newval, oldval) => {
    //console.log(newval, oldval);
    showToken.value = newval
}, {
    deep: true,
    immediate: true,
})

//获得网站logo
const logo = ref("")
const webSiteName = ref("")
let getLogo = async () => {
    const responseStatus = await requestDataPromise('/web/getWebsiteHead', {
        method: 'GET',
        query: {},
    });
    if (responseStatus.code == 200) {
        logo.value = responseStatus.data.logo;
        webSiteName.value = responseStatus.data.website_name;
    } else if (responseStatus.code == 0) {
        window.location.href = $CwebUrl + '/404';
    }
}
getLogo();
//3.跳转菜单逻辑 end ---------------------------------------->

//4.获取广告 start ---------------------------------------->
let adImg = ref({})
//4.获取广告 end ---------------------------------------->

//5.获取登录状态 start ---------------------------------------->
onMounted(async () => {

    //从客户端获取登录状态
    //从客户端阶段开始 持续查询登录状态
    let getLoginStatus = async () => {
        //获得token
        const token = getToken();
        const { $webUrl, $CwebUrl } = useNuxtApp();

        if(token == undefined){
            //如果没有获取到token 不访问后端获取在线状态
            console.log("没有获取到token！无需查询登录状态！")
            showToken.value = false;

        }else{
            //如果获取到了token 访问后端查询状态
            console.log("已获取到用户token,开始查询登录状态！")
            const queryParams = new URLSearchParams({
                token: getToken()
            });
            let url = `${$webUrl}/api/loginStatus?${queryParams.toString()}`
            const responseStatus = await fetch(url, {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                    'Userurl': $CwebUrl,
                    //'token': getToken(),
                    'Origin': $CwebUrl
                }
            });
            const result = await responseStatus.json();
            console.log(result)
            
            if (result.code == 200) {
                console.log("用户已经登录！");
                showToken.value = true;
            }
            if (result.code == -1) {
                isShow.value = false;
                showToken.value = false;
                removeToken();
                removeTicket();
                ElMessage.error('您没有权限登录该网站！')
            }
            if (result.code == -2) {
                isShow.value = false;
                showToken.value = false;
                removeToken();
                removeTicket();
                ElMessage.error('您已退出登录！')
            }
        }
    }
    getLoginStatus();
    setInterval(getLoginStatus, 3000);

    //从客户端获取广告
    //从客户端获取行政职能部门 加快打开速度
    const { $webUrl, $CwebUrl } = useNuxtApp();
    //广告1
    let url = `${$webUrl}/web/getWebsiteAdvertisement?ad_tag=nfcpgxw_top`
    const responseAd1 = await fetch(url, {
        headers: {
            'Content-Type': 'application/json',
            'Userurl': $CwebUrl,
            'Origin': $CwebUrl
        }
    });
    const resultAd1 = await responseAd1.json();
    adImg.value = resultAd1.data[0];

    //从客户端获取用户名
    let userInfoUrl = `${$webUrl}/user/getUserInfo`
    const userInfoResponse = await fetch(userInfoUrl, {
        headers: {
            'Content-Type': 'application/json',
            'Userurl': $CwebUrl,
            'Origin': $CwebUrl
        }
    });
    const userInfo = await userInfoResponse.json();
    if (userInfo.code == 200) {
        username.value = userInfo.data.nickname
    }
})
//5.获取登录状态 end ---------------------------------------->


//点击手机
// 添加全局状态
// const panelVisible = useState('panelVisible', () => false)

const togglePanel = () => {
  panelVisible.value = true
}

</script>

<style lang="less" scoped>
    @import url('@/assets/css/public/head.less');
</style>


<style lang="less" scoped>

 
    @media screen and (min-width:801px){/*pc*/

            .index_main{width:100%;}
            
            .phone_head_btn{display:none;}
            .logo_right_box{ display:none;}
            .pc_none{display:none;}
        }

    @media screen and (max-width:800px){/*ipad_phone*/
                       .headerNav{overflow:hidden;height:auto; padding:5px 0px;background:#f7f7f7;}
              .inner{width:92%;margin:0 auto;overflow:hidden;}
              .headerLogo .inner{
                    width:92%;height:auto;
                    display: flex;margin:4px auto; 
                }   

                .headerLogo .inner>img{ height:40px;margin:0px 10px 0px 0px;width:auto;}
                
                .logo_right_box{ 

                    .logo_right_btn{float:left; width:10vw;margin-left:7vw;text-align:center;}    
                    .logo_right_btn:nth-of-type(1){margin-left:0px;}    
                    .logo_right_btn_img{width:6vw; display:inline-block; }    
                    .logo_right_btn_text{display:block;width:100%;height:16px;color:#333;
                                        text-align:center;line-height:16px;font-size:3vw;}    

                }   
                .phone_head_btn{display:block;float:right;width:26px;height:26px; margin-top:4px;
                     
                    background:url(../../public/image/2.png) no-repeat 0 0px;background-size:100% 100%;
        
                }
                .headerLogo{height:auto;}
            .tips{font-size:16px;}
                
            .tips img{width:60px;height:60px;margin-right:7px;}
            .tips p{line-height:28px; }
            .tips > p:first-child(1){margin-bottom:13px;}
                
            .dialog_load_btn{
                line-height:33px;width:111px;margin:40px auto 0;border-radius:4px; 
                height:33px;text-align:center;
                background: #004564;
                
                font-size: 14px;
                color: #fff; 
            }
            
       
         /deep/.el-overlay{ width:100%;
                    .el-overlay-dialog{width:90%;left:5%;}
                    .el-dialog{width:100%;}
        
        }               
              .headerLogo .inner .titlead{display:none;}
                .headerNav .right{display:none;}   
                .phone_none{display:none;}
    }


</style>

 