<template>
  <el-affix>
    <div class="p-header">
      <div class="return" v-if="route.path!='/' && noReturn.indexOf(route.path)<0 && route.path!=('/home/user')"><img src="@/assets/img/h_return.png" @click="returnFun"></div>
      <div class="head-title" v-if="(route.path.indexOf('/home/')>-1 && route.path!='/home/user') || route.path.indexOf('/login')>-1 || route.path.indexOf('/register')>-1">{{user.adminTitle}}</div>
      <NuxtLink v-else-if="!searchShow" to="/" class="logo"><img src="@/assets/img/logo.svg"></NuxtLink>
      <div class="search-input-wrap" v-else-if="route.path.indexOf('/admin/')<0">
        <el-input class="input-wrap" v-model="user.publicSearch" size="large" placeholder="输入中英文产品名称搜索" @keyup.enter.native="SearchFun">
          <template #append>
            <div @click="SearchFun">
              <el-icon>
                <Search />
              </el-icon>
            </div>
          </template>
        </el-input>
        <i class="category-icon" @click="openFun"></i>
      </div>
      <div v-if="route.path=='/home/support/create'" class="supportLink">
        <NuxtLink to="/home/support">我的售后</NuxtLink>
      </div>
      <div v-else-if="route.path=='/home/support'" class="supportLink">
        <NuxtLink to="/home/support/create">我要售后</NuxtLink>
      </div>
      <div class="user-href" v-else-if="route.path.indexOf('/login') < 0 && route.path.indexOf('/register') < 0">
        <!-- <a href="javascript:;" class="updateBom" v-if="route.path.indexOf('/admin/')<0">
          上传BOM
        </a> -->
        <div class="message">
          <i v-if="msmTotal>0">{{msmTotal}}<template v-if="msmTotal==99">+</template></i>
          <img @click="linkToMsg" src="@/assets/img/message.png">
        </div>
        <div class="cart" @click="linkToCart">
          <i><template v-if="cartNum<=99">{{cartNum}}</template><template v-if="cartNum>99">99+</template></i>
          <img src="@/assets/img/header/cart.svg">
        </div>
        <i class="user-icon" v-if="route.path=='/'|| noReturn.indexOf(route.path)>-1 || route.path==('/home/user')" @click="openFun"></i>
      </div>
    </div>
  </el-affix>
  <div class="seo-nav" v-if="!isClient">
    <h-Header-seo></h-Header-seo>
  </div>
  <el-drawer v-model="open.user" size="55%" direction="ltr" append-to-body class="user-drawer">
    <template #header="{ close, titleId, titleClass }">
      <NuxtLink :id="titleId" :class="titleClass" to="/" class="logo"><img src="@/assets/img/logo.svg"></NuxtLink>
    </template>
    <template v-if="isClient">
      <div class="a-nav">
        <NuxtLink to="/">首页</NuxtLink>
        <NuxtLink :to="{path:'/ategory'}">产品中心</NuxtLink>
        <NuxtLink :to="{path:'/bom'}">BOM配单</NuxtLink>
        <NuxtLink :to="{path:'/specifications'}">商城资讯</NuxtLink>
        <NuxtLink :to="{path:'/specifications'}">查规格书</NuxtLink>
        <NuxtLink :to="{path:'/home/order/list'}">我的订单</NuxtLink>
        <NuxtLink :to="{path:'/about'}">关于合科泰</NuxtLink>
        <NuxtLink :to="{path:'/Inquiry'}">联系我们</NuxtLink>
      </div>
    </template>
  </el-drawer>

  <el-drawer v-model="user.searchFalg" size="100%" direction="rtl" no-title append-to-body class="search-drawer" :show-close="false">
    <template v-if="isClient">
      <div class="drawer-con">
        <div class="search-wrap">
          <img src="@/assets/img/h_return.png" @click="drawerReturnFun" class="return">
          <div class="search-input-wrap">
            <el-input class="input-wrap" v-model="user.publicSearch" size="large" placeholder="输入中英文产品名称搜索" @keyup.enter.native="SearchFun">
              <template #append>
                <div @click="SearchFun">
                  <el-icon>
                    <Search />
                  </el-icon>
                </div>
              </template>
            </el-input>
            <i class="category-icon" @click="openFun"></i>
          </div>
        </div>
        <div class="history-wrap" v-if="historyList.length>0">
          <h3 class="search-drawer-title">最近搜索</h3>
          <ul>
            <li v-for="(item, index) in historyList" :key="index" @click="linkToSearch(item)">{{ item }}<img @click.stop="removeItem(index)" src="@/assets/img/header/delete.svg"></li>
          </ul>
        </div>
        <div class="ggs-wrap">
          <h3 class="search-drawer-title">规格书查询</h3>
          <NuxtLink to="/specifications"><img src="@/assets/img/icon/ggs_2.png"></NuxtLink>
        </div>
        <div class="hot-search">
          <h3>热门搜索</h3>
          <ul>
            <li v-for="(i,idx) in hotArr" :key="i.id" @click="linkToSearch(i.name)"><i :class="`i_${idx+1}`">{{ idx+1 }}</i>{{ i.name }}</li>
          </ul>
        </div>
      </div>
    </template>
  </el-drawer>
</template>
<script setup lang="ts">
import { useAll } from "~/api/pubAll/service";
const { selectProductHot, getCartList } = useAll();
import { Search } from "@element-plus/icons-vue";
import newsIcon from "@/assets/img/ico/news.png";
const route = useRoute();
const router = useRouter();
const user = useUserStore();
import { useMsg } from "~/api/msg/msgService";
const { setMsgReadAll } = useMsg();
import { useCategory } from "~/api/category/categoryService";
const CategoryStore = useCategoryStore();
const { getCategory } = useCategory();
const isLogin = useCookie("tokenKey");
import { userLogout } from "~/api/apiHttps";
const tokenKey: any = useCookie("tokenKey");
import { useLogin } from "~/api/login/loginService";
const loginService = useLogin();
const searchShow = ref(false);
const nuxtApp = useNuxtApp();
const isClient = !nuxtApp.ssrContext;
let msmTotal: any = ref(0);
let noReturn = ref(["/search", "/category", "/news"]);
let open: any = ref({
  user: false,
  announcement: false,
});
let announcementFalg: any = ref(null);
let announcementCloseNumber: any = ref(3);
let searchVal: Ref<string> = ref((route.query.key as string) || "");
let categoryId = ref("");
const clubFalg: any = useCookie("clubFalg", {
  maxAge: 60 * 5,
  sameSite: "strict", // 防止 CSRF 攻击
});
watch(
  () => route.path,
  async (first: any, second: any) => {
    setTimeout(() => {
      searchShow.value = false;
    }, 100);
    open.value.user = false;
    if (route.path != "/category") {
      categoryId.value = "";
    }
    user.value.searchFalg = false;
  },
  { deep: true }
);

watch(
  () => user.value.cartUpdate,
  (newValue: any, oldValue: any) => {
    if (!process.server && user.value.isLogin && oldValue != undefined) {
      getCartListFun();
    }
  },
  { immediate: true }
);

if (CategoryStore.value.Category.length == 0) {
  const {
    data: ssrSpuData,
    error,
    refresh,
  } = await useAsyncData<any>("categoryData", () => getCategory());
  if (ssrSpuData.value) {
    setCat(ssrSpuData.value);
  } else {
    getCategoryFun();
  }
}
function readAll() {
  ElMessageBox.confirm("确认标记全部已读吗？", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
  })
    .then(() => {
      setMsgReadAllFun();
    })
    .catch(() => {
      // catch error
    });
}
async function setMsgReadAllFun() {
  const res: any = await setMsgReadAll();
  if (res.code == 200) {
    user.value.msgLoad = true;
    ElMessage.success("标记全部已读成功");
  }
}

async function linkToCart() {
  if (!user.value.isLogin) {
    return navigateTo({
      path: "/login",
      query: { redirect: '/cart' },
    });
  }
  navigateTo("/cart");
}

function drawerReturnFun() {
  user.value.searchFalg = false;
}
function returnFun() {
  if(route.fullPath.indexOf('/login')>-1){
    return navigateTo('/');
  }
  router.go(-1);
}
async function linkTo() {
  if (!user.value.isLogin) {
    return navigateTo({
      path: "/login",
      query: { redirect: '/home/user' },
    });
  }
  navigateTo("/home/user");
}
async function getCategoryFun() {
  const res: any = await getCategory();
  setCat(res);
}
function setCat(res: any) {
  if (res.httpCode == 200) {
    CategoryStore.value.Category = res.data;
  }
}
function scrollFun() {
  if (route.path == "/home/user") {
    return;
  }
  const scrollTop = window.scrollY || document.documentElement.scrollTop;
  if (scrollTop >= 43) {
    searchShow.value = true;
  } else {
    searchShow.value = false;
  }
}
onBeforeUnmount(() => {
  window.removeEventListener("scroll", scrollFun);
});
function openFun() {
  open.value.user = !open.value.user;
}

const historyList = ref<string[]>([]);
// 保存到本地存储
const saveToLocalStorage = () => {
  localStorage.setItem("searchHistory", JSON.stringify(historyList.value));
};
function SearchFun() {
  // 去重并添加到历史记录
  const index = historyList.value.indexOf(user.value.publicSearch);
  if (index !== -1) historyList.value.splice(index, 1);

  historyList.value.unshift(user.value.publicSearch);
  if (historyList.value.length > 10) historyList.value.pop();
  saveToLocalStorage();
  linkToSearch(user.value.publicSearch);
}
const linkToSearch = (key: any) => {
  navigateTo({
    path: "/search",
    query: {
      key: key,
      pageNum: 1,
      pageSize: 20,
    },
  });
};
// 删除单条记录
const removeItem = (index: number) => {
  historyList.value.splice(index, 1);
  saveToLocalStorage();
};
// 清空所有记录
const clearAll = () => {
  historyList.value = [];
  localStorage.removeItem("searchHistory");
};

async function linkToMsg() {
  if (!user.value.isLogin) {
    return navigateTo({
      path: "/login",
      query: { redirect: '/home/message' },
    });
  }
  navigateTo("/home/message");
}
const userInfo: any = useCookie("userInfo");
onMounted(() => {
  if (!user.value?.userInfo?.id) {
    user.value.userInfo = userInfo.value;
  }
  const saved = localStorage.getItem("searchHistory");
  if (saved) historyList.value = JSON.parse(saved);
  getCartListFun();
});

let cartNum = ref(0);
async function getCartListFun() {
  const res: any = await getCartList();
  if (res.httpCode == 200) {
    cartNum.value = res.data.length;
    if (res.data.length > 0) {
      res.data.forEach((item: any) => {
        item.priceTemplateArr = JSON.parse(item.priceTemplate);
        let pri = Number(getPrice(item.goodsNum, item));
        let xPrice = Number((pri * item.goodsNum).toFixed(6));
        item.priceNum = xPrice;
      });
    }
    user.value.cartGroup = res.data;
    user.value.cartEnd = true;
  }
}

const {
  data: ssrData,
  error,
  refresh,
} = await useAsyncData<any>("selectProductHot", () =>
  selectProductHot({
    pageNum: 1,
    pageSize: 10,
  })
);
const hotArr: any = ref<any[]>(ssrData.value?.data?.records || []);
function getPrice(b: any, item: any) {
  let a = item.priceTemplateArr;
  for (let i = 0; i < a.length; i++) {
    const min = i === 0 ? a[i].num : a[i].num; // 左区间从当前 num 开始
    const max = a[i + 1] ? a[i + 1].num : Infinity; // 右区间是下一个 num，如果没有就是 Infinity
    if (b >= min && b < max) {
      return a[i].price;
    }
  }
  return a[a.length - 1].price; // b 超过最大 num
}
</script>
<style scoped lang="scss">
.seo-nav {
  position: absolute;
  left: -200px;
  top: -500px;
}
.msgReadAll {
  position: absolute;
  right: 12px;
  top: 0;
  bottom: 0;
  margin: auto;
  height: 24px;
  display: flex;
  align-items: center;
}
.nav_text {
  position: relative;
  i {
    position: absolute;
    top: -18px;
    bottom: 0;
    left: 63px;
    width: 32px;
    height: 20px;
    font-size: 12px;
    color: #ffffff;
    font-style: normal;
    z-index: 1;
    display: flex;
    justify-content: center;
    align-items: center;
    span {
      transform: scale(0.8);
      display: block;
      font-weight: 400;
    }
    .el-image {
      width: 32px;
      height: 20px;
      position: absolute;
      top: 0;
      left: 0;
      z-index: -1;
    }
    :deep(img) {
      width: 32px;
      height: 20px;
    }
  }
}
.search-input-wrap {
  display: flex;
  width: 100%;
  margin-right: 125px;
  margin-left: 18px;
  .input-wrap {
    height: 32px;
    background: #fff;
    border-radius: 28px;
    width: 100%;
    border: 1px solid rgba(0, 0, 0, 0.15);
  }
  :deep(.el-input--large .el-input__wrapper) {
    border-radius: 28px;
    box-shadow: unset;
    padding-right: 0;
  }
  :deep(.el-input__inner) {
    height: 30px;
    line-height: 20px;
    padding: 5px 0;
  }
  :deep(.el-input__prefix) {
    font-size: 18px;
  }
  .el-input:deep(.el-input__wrapper.is-focus) {
    box-shadow: unset !important;
  }
  :deep(.el-input-group__append) {
    background: #fff;
    border-radius: 0 25px 25px 0;
    box-shadow: 0 0 0 1px #fff inset;
    color: $mainColor;
    padding: 0 10px;
    .el-icon {
      width: 26px;
      height: 26px;
      font-size: 18px;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
}
.user-icon {
  width: 24px;
  min-width: 24px;
  height: 40px;
  background: url("@/assets/img/category.png") no-repeat center center;
  background-size: 24px auto;
  display: block;
}
.p-header {
  height: 44px;
  background: #ffffff;
  display: flex;
  align-items: center;
  padding: 0 12px;
  position: relative;
  .return {
    min-width: 24px;
    width: 24px;
    height: 24px;
    display: flex;
    align-items: center;
    justify-content: flex-start;
    margin-right: 12px;
  }
  .logo {
    width: 80px;
    min-width: 80px;
  }
  .user {
    height: 24px;
    width: auto;
    display: flex;
    justify-content: center;
    align-items: center;
    color: #333;
    position: absolute;
    right: 12px;
    top: 0;
    bottom: 0;
    margin: auto;
    img {
      width: 24px;
    }
  }
  .user-href {
    position: absolute;
    right: 12px;
    top: 0;
    bottom: 0;
    margin: auto;
    display: flex;
    align-items: center;
    .updateBom {
      border: 1px solid $mainColor;
      color: $mainColor;
      padding: 0 5px;
      line-height: 22px;
      border-radius: 3px;
      margin-right: 10px;
      font-size: 12px;
    }
    img {
      width: 25px;
    }
    .cart {
      margin-right: 15px;
      position: relative;
      i {
        min-width: 16px;
        height: 16px;
        padding: 0 3px;
        position: absolute;
        background: $mainColor;
        font-size: 10px;
        color: #fff;
        border-radius: 50px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-style: normal;
        left: 12px;
        top: -5px;
      }
    }
    .message {
      margin-right: 12px;
      position: relative;
      i {
        min-width: 16px;
        height: 16px;
        padding: 0 3px;
        position: absolute;
        background: $mainColor;
        font-size: 10px;
        color: #fff;
        border-radius: 50px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-style: normal;
        left: 12px;
        top: -5px;
      }
    }
  }
  .logout {
    position: absolute;
    right: 12px;
    top: 0;
    bottom: 0;
    margin: auto;
    display: flex;
    align-items: center;
  }
}
.head-title {
  flex: 1;
  padding-right: 30px;
  text-align: center;
  font-size: 15px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  max-width: 300px;
  margin: 0 auto;
}
// 新年 start
.scroll-container {
  /* 设置滚动区域的宽度和高度 */
  overflow: hidden;
  white-space: nowrap;
  position: relative;
  display: flex;
  align-items: center;
  width: 100%;
  height: 20px;
  font-size: 12px;
}
.scroll-content {
  display: block;
  white-space: nowrap;
  position: absolute;
  //animation: scroll-left 50s linear infinite; /* 动画30秒循环，匀速滚动 */
  width: 100%;
  span {
    display: block;
    padding-right: 0px;
    font-size: 13px;
    color: $mainColor;
    cursor: pointer;
    width: 100%;
    text-align: center;
  }
}
@keyframes scroll-left {
  0% {
    transform: translateX(95vw);
  }
  100% {
    transform: translateX(-97%);
  }
}
// 新年 end
</style>
<style lang="scss">
.el-affix--fixed {
  .p-header {
    box-shadow: 0 8px 18px rgba(0, 0, 0, 0.1);
  }
}
.user-drawer {
  .logo {
    width: 120px;
    max-width: 120px;
  }
  .el-drawer__header {
    margin-bottom: 0px;
    padding-right: 17px;
    padding-top: 15px;
    display: flex;
    justify-content: space-between;
  }
  .el-drawer__body {
    padding-top: 10px;
    padding-left: 0;
    padding-right: 0;
  }
  .el-drawer__close-btn {
    padding: 0;
  }
  ul {
    margin: 10px 0px 0;
    border-top: 1px solid #e8e8e8;
    display: flex;
    flex-wrap: wrap;
    padding: 6px 0px 0;
  }
  li {
    height: 40px;
    padding: 0 20px 0 20px;
    font-size: 14px;
    width: 50%;
    position: relative;
    &:first-child {
      width: 100%;
      &::before {
        display: none;
      }
    }
    &:nth-child(2n + 1) {
      &::before {
        content: "";
        height: 14px;
        width: 1px;
        position: absolute;
        left: -4px;
        top: 13px;
        background: #e8e8e8;
      }
    }
    a {
      position: relative;
      transition: all 0.3s ease;
      font-size: 14px;
      color: #333;
      display: flex;
      align-items: center;
      &::before {
        position: absolute;
        content: "";
        width: 0;
        height: 1px;
        background: $mainColor;
        left: 0;
        bottom: -3px;
        transition: all 0.3s ease;
      }
    }
  }
  .current {
    a {
      color: $mainColor;
      &::before {
        position: absolute;
        content: "";
        width: 100%;
        height: 1px;
        background: $mainColor;
        left: 0;
        bottom: -3px;
      }
    }
  }
  .categoryTitle {
    font-weight: bold;
    font-size: 14px;
    color: #222;
  }
  .el-drawer__title {
    font-size: 18px;
    color: #000;
  }
  .a-nav {
    display: flex;
    flex-wrap: wrap;
    padding: 0 20px;
    justify-content: space-between;
    flex-direction: column;
    a {
      font-size: 14px;
      color: #222;
      width: 100%;
      font-weight: bold;
      margin: 15px 0;
      text-align: center;
    }
    .linkToClub {
      margin: 8px 0;
      img {
        width: 104px;
      }
    }
  }
}
// 公告 start
.announcement-dialog {
  width: 85%;
  padding: 0 !important;
  border-radius: 10px !important;
  .el-dialog__header {
    display: none;
  }
  .el-dialog__body {
    padding: 0 !important;
  }
  .announcement-wrap {
    background: url(https://io.house-tk.com/hop/pro/other/images/0d60430ec81024223afaccd67e2470f2)
      no-repeat top center;
    background-size: 100%;
    padding: 10px 15px 25px;
    h3 {
      display: flex;
      align-items: center;
      justify-content: center;
      padding-top: 8px;
      margin-bottom: 0px;
      font-size: 16px;
      font-weight: bold;
      color: $mainColor;
      line-height: 50px;
    }
    p {
      font-size: 14px;
      line-height: 20px;
      color: #666;
      margin-bottom: 13px;
      &:last-child {
        margin-bottom: 18px;
      }
    }
    .btn_main {
      height: 42px !important;
      font-size: 16px;
      width: 100%;
      border-radius: 10px !important;
      border: none !important;
      margin: 0 auto;
      display: flex;
      &.btn_main_disabled {
        background: #eda7bd !important;
      }
    }
  }
}
// 公告 end
.search-drawer {
  .el-drawer__header {
    display: none;
  }
}
.search-drawer .el-drawer__body {
  padding-left: 15px;
  padding-right: 15px;
}
.drawer-con {
  margin-bottom: 20px;
  .search-wrap {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    .return {
      min-width: 24px;
      width: 24px;
      height: 24px;
      display: flex;
      align-items: center;
      justify-content: flex-start;
    }
    .search-input-wrap {
      margin: 0 0px 0 10px;
    }
  }
  .search-drawer-title {
    font-size: 14px;
    color: #666;
  }
  .ggs-wrap {
    margin-top: 10px;
    img {
      margin-top: 10px;
      width: 100%;
    }
  }
  .history-wrap {
    ul {
      display: flex;
      flex-wrap: wrap;
      margin-top: 10px;
      li {
        height: 26px;
        display: flex;
        align-items: center;
        background: #f4f4f4;
        margin-right: 10px;
        margin-bottom: 10px;
        font-size: 12px;
        border-radius: 3px;
        color: #666;
        padding: 0 3px 0 10px;
        img {
          width: 20px;
          height: 20px;
          padding: 5px 4px;
        }
      }
    }
  }
  .hot-search {
    background: linear-gradient(to bottom, #f9e9ea 0%, #fff 80%, #fff 100%);
    padding: 12px 12px 0 12px;
    border-radius: 5px;
    border: 1px solid #e8e8e8;
    margin-top: 20px;
    h3 {
      padding-left: 25px;
      background: url(@/assets/img/header/hot.svg) no-repeat center left;
      background-size: 20px auto;
      font-size: 16px;
      color: #333;
      margin-bottom: 10px;
    }
    ul {
    }
    li {
      height: 46px;
      padding: 0;
      display: flex;
      align-items: center;
      & + li {
        border-top: 1px solid #e8e8e8;
      }
      i {
        width: 20px;
        height: 20px;
        background: url(@/assets/img/header/ph_0.svg) no-repeat center center;
        background-size: 20px auto;
        display: flex;
        align-items: flex-start;
        justify-content: center;
        font-style: normal;
        font-size: 12px;
        color: #fff;
        font-weight: 400;
        margin-right: 10px;
        &.i_1 {
          background: url(@/assets/img/header/ph_1.svg) no-repeat center center;
          background-size: 20px auto;
        }
        &.i_2 {
          background: url(@/assets/img/header/ph_2.svg) no-repeat center center;
          background-size: 20px auto;
        }
        &.i_3 {
          background: url(@/assets/img/header/ph_3.svg) no-repeat center center;
          background-size: 20px auto;
        }
      }
    }
  }
}

.supportLink {
  position: absolute;
  right: 12px;
}
</style>
