<template>
  <div class="trademark mr-8 flex items-center text-white">
    <img :src="loginLogin" class="w-10 h-10 mr-4" />
    <div class="text-nowrap">客户管家</div>
  </div>
  <div class=" flex flex-row justify-start items-center text-white flex-1 parentDiv" ref="parentDiv">
    <div v-for="(routerItem, routerItemIdex) in routerList" @click="setCurrentRouter(routerItem)"
      :class="`border-b-2 border-transparent hover:border-white p-2 mr-4 cursor-pointer multipleyHeader ${activeRouter?.path === routerItem.path ? 'border-white' : ''}`"
      :key="routerItem.path" ref="childDivs" v-show="visibleItems.includes(routerItemIdex)">
      <div v-if="routerItem.children && routerItem.children.length <= 0 && routerItem?.isMenu" class="text-nowrap headerText">
        {{ routerItem.name }}
      </div>
      <div v-if="routerItem.children && routerItem.children.length > 0" class="flex justify-center items-center">
        <el-dropdown>
          <div class="text-white w-full h-full headerText">
            {{ routerItem.name }}
            <el-icon class="el-icon--right">
              <arrow-down />
            </el-icon>
          </div>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item v-for="child in routerItem.children" :key="child.path" @click="setCurrentRouter(child)">
                {{ child.name }}
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>
    <div v-if="moreRoutes.length > 0" class="flex justify-center items-center">
      <el-dropdown trigger="click">
        <span class="text-white w-full h-full headerText">
          <el-icon>
            <MoreFilled />
          </el-icon>
        </span>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item v-for="(child, childIndex) in moreRoutes" :key="child.path"
              @click="moreSetCurrentRouter(child, childIndex)">
              {{ child.name }}
            </el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>
  </div>
  <div class="flex flex-row justify-start items-center text-white header-right">
    <el-badge :value="numberOfLogos" :max="99" class="ml-4 cursor-pointer h-[26px]" :show-zero="false">
      <el-icon :size="26" @click="newsDrawer = true">
        <Bell />
      </el-icon>
    </el-badge>
    <div>
      <img class="w- h-8 rounded-full ml-4 cursor-pointer" :src="defaultCover" alt="" @click="drawerVis = true">
    </div>
    <el-icon :size="26" class="ml-4 cursor-pointer">
      <Grid />
    </el-icon>
  </div>

  <!-- 左侧 -->
  <el-drawer v-model="drawerVis" modal-class="drawerVisClass" :with-header="false">
    <div class="w-full h-full">
      <div class="bg-[#075985]">
        <div class="p-8">
          <div class="w-[100px] h-[100px] p-2 border-[1px] border-[#999] rounded-full m-auto">
            <img class="w-full h-full" :src="defaultCover">
          </div>
        </div>
        <div class="text-center text-[20px] leading-none text-white pb-3">
          <TextTranslation translationTypes="userName" :translationValue="userInfo.name" />
        </div>
        <div class="text-center leading-none text-slate-50 pb-3">角色：{{ userInfo.roleName }}</div>
        <div class="text-center leading-none text-slate-50 pb-3">公司：{{ userInfo.companyName }}</div>
        <div class="w-full drawerVisBtn">
          <div @click="logout()">退出</div>
        </div>
      </div>
    </div>
  </el-drawer>

  <!-- 消息 -->
  <el-drawer v-model="newsDrawer" modal-class="drawerVisClass" :with-header="false" size="50%">
    <div class="w-full h-full flex flex-row" v-loading="newsDrawerLoading">
      <div class="w-full h-full">
        <el-table :data="newsDrawerTableData" style="flex1" border>
          <el-table-column prop="msg" label="消息内容">
            <template #default="scope">
              <el-link type="primary" :underline="false" @click="toDetail(scope.row)">{{ scope.row.msg }}</el-link>
            </template>
          </el-table-column>
          <el-table-column prop="checked" label="状态" width="100">
            <template #default="scope">
              <el-tag :type="scope.row.checked ? 'success' : 'danger'">
                {{ scope.row.checked ? '已读' : '未读' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="time" label="时间" width="140" />
        </el-table>
      </div>
      
      <div class="messageStyle">
        <el-dropdown>
          <span class="el-dropdown-link">
            <el-icon class="el-icon--right">
              <el-icon><MoreFilled /></el-icon>
            </el-icon>
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="oneClickRead()" :disabled="numberOfLogos <= 0">一键已读</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>
  </el-drawer>
</template>

<!-- /information/list -->

<script lang="ts" setup>
import { onMounted, ref, watchEffect, watch } from 'vue';
import { RouteRecordRaw, useRouter, useRoute } from 'vue-router';
import { useStore } from "../../store/index"
import { post, uploadFile } from "@/utils/request";
import defaultCover from "../../assets/defaultCover.png";
import { formatDate } from '@/utils/times'
import loginLogin from '../../assets/login/login_logo.png'
const { routers, clearStore, userInfo } = useStore()
const router = useRouter();
const route = useRoute()
// const routerList = ref<RouteRecordRaw[]>([]);
const routerList = ref<any[]>([]);
const activeRouter = ref<RouteRecordRaw>();

const visibleItems = ref<number[]>([]);
const parentDiv = ref<HTMLElement | null>(null);
const itemLastIndex = ref(0)
const moreRoutes = ref<any[]>([])
const newsDrawerTableData = ref<any[]>([])
const drawerVis = ref(false)
const newsDrawer = ref(false)
const newsDrawerLoading = ref(false)
const numberOfLogos = ref(0)

const updateVisibleItems = () => {
  const parentWidth = (parentDiv.value?.offsetWidth && parentDiv.value?.offsetWidth - 150) || 10;
  const canvas = document.createElement('canvas');
  const context = canvas.getContext('2d');

  let textWidthList: any = [] // 所有文字的宽度
  let totalWidth = 0;
  let temporaryIndex: any = []

  if (context) {
    context.font = '16px 微软雅黑';
    textWidthList = routerList.value.map((item: any) => {
      const metrics = context.measureText(item.name);
      return Math.ceil(metrics.width) + 32; // 32是padding和margin的宽度
    })
  }
  for (let i in textWidthList) {
    if (totalWidth + textWidthList[i] > parentWidth) {
      break;
    }
    totalWidth += textWidthList[i];
    temporaryIndex.push(+i);
  }

  // 替换最后一个元素
  const lastIndex = routerList.value.findIndex(obj => obj.name === '系统设置');
  itemLastIndex.value = lastIndex
  temporaryIndex.splice(temporaryIndex.length - 1, 1, lastIndex)
  visibleItems.value = temporaryIndex;

  // 过滤出隐藏的元素
  let interceptIndex = Object.values(visibleItems.value).findIndex(v => +v == lastIndex)
  let newVisibleItems = JSON.parse(JSON.stringify(temporaryIndex)).splice(0, interceptIndex + 1)
  let missingIndex = findMissingNumbers(newVisibleItems)
  let routerLists = []
  for (var i in missingIndex) {
    routerLists.push(routerList.value[missingIndex[i]])
  }
  moreRoutes.value = routerLists

  // 判断当前的索引是否在隐藏元素中
  let currentIndex = moreRoutes.value.findIndex(obj => obj.name === activeRouter.value?.name);
  if (currentIndex >= 0) {
    replaceData(activeRouter.value, currentIndex)
  }
};

const findMissingNumbers = (arr: any) => {
  let missingNumbers = [];
  arr.sort((a: any, b: any) => a - b); // 对数组进行排序

  for (let i = arr[0]; i < arr[arr.length - 1]; i++) {
    if (!arr.includes(i)) { // 如果数组中不包含当前数字
      missingNumbers.push(i); // 将缺失的数字添加到结果数组中
    }
  }

  return missingNumbers;
}

const setCurrentRouter = (item: RouteRecordRaw) => {
  activeRouter.value = item;
  if (item.children && item.children.length > 0) {
    router.push({ path: item.children[0].path });
    return
  }
  router.push({ path: item.path });
};

const moreSetCurrentRouter = (item: RouteRecordRaw, index: any) => {
  activeRouter.value = item;
  router.push({ path: item.path });
  replaceData(item, index)
};

const replaceData = (item: any, index: any) => {
  let itemIndex = routerList.value.findIndex(v => v.name == item.name)
  let lastItem = routerList.value[visibleItems.value[visibleItems.value.length - 2]]
  visibleItems.value.splice(visibleItems.value.length - 2, 1, itemIndex),
    moreRoutes.value.splice(index, 1, lastItem)
}

const logout = () => {
  clearStore();
  router.push({ path: '/login' });
};

const getNewsDrawerTableData = () => {
  newsDrawerLoading.value = true
  post(`/information/list`, {}).then(res => {
    const data = res.data.map((item: any) => {
      return {
        ...item,
        time: formatDate(new Date(item.time))
      }
    })
    numberOfLogos.value = (data || []).filter((item: any) => !item.checked).length
    newsDrawerTableData.value = data
  }).catch(err => {
    newsDrawerTableData.value = []
    console.log(err)
  }).finally(() => {
    newsDrawerLoading.value = false
  })
}

const oneClickRead = () => {
  newsDrawerLoading.value = true
  post(`/information/checkAll`).then(_res => {
    getNewsDrawerTableData()
  }).catch(err => {
    console.log(err, '<==== 失败')
  }).finally(() => {
    newsDrawerLoading.value = false
  })
}

const toDetail = (row: any) => {
  console.log(row, '<=== 点击数据')
  const { id, type, path } = row
  post(`/information/check`, { id }).then(res => {
    console.log(res, '<=== 成功')
    getNewsDrawerTableData()
    if (path) {
      router.push({ path });
    }
  }).catch(err => {
    console.log(err, '<==== 失败')
  }).finally(() => {
    newsDrawer.value = false
  })
}

onMounted(() => {
  getNewsDrawerTableData()
  routerList.value = routers;
  activeRouter.value = routerList.value.find((item) => item.path === router.currentRoute.value.path);

  window.addEventListener('resize', updateVisibleItems);
  setTimeout(() => {
    updateVisibleItems();
  }, 500);
})
watchEffect(() => {
  watch(() => route.path, (newPath, _oldPath) => {
    activeRouter.value = routerList.value.find((item) => item.path === newPath);
  }, {
    immediate: false
  }
  );
});
</script>

<style scoped lang="scss">
.messageStyle {
  margin: 15px;
  margin-left: 100px;
}
.trademark {
  font-size: 20px;
}

.multipleyHeader {
  height: 96%;
  display: flex;
  align-items: center;
  text-wrap: nowrap;

  .headerText {
    font-size: 16px;
  }
}

.parentBox {
  // max-width: 80%;
  // min-width: 300px;
  flex: 1;
  overflow: hidden;
}

.header-right {
  width: 135px;
}

.parentDiv {
  width: 10%;
}

.drawerVisClass {
  .drawerVisBtn {
    margin-top: 10px;
    border-top: 1px solid #999;

    div {
      text-align: center;
      line-height: 40px;
      color: #fff;
      cursor: pointer;

      &:hover {
        background: #086597;
      }
    }
  }
}
</style>