<template>
  <div class="shop-menu">
    <el-scrollbar class="menu-1" height="100%" :style="{ width: menu1WidthValue }">
      <div class="title my-10px">
        <sa-image :url="appInfo?.logo" size="36" fit="contain"></sa-image>
      </div>
      <el-menu :default-active="shop.name" @select="onSelect">
        <template v-for="menu in shopApp?.children || []" :key="menu">
          <menu-item :menuItem="menu" />
        </template>
      </el-menu>

      <!-- 底部用户区域 -->
      <div class="menu-footer">
        <div class="line sa-m-t-10 sa-m-b-10"></div>
        <!-- <div class="el-menu-item">
          <el-tooltip effect="light" content="个人信息" placement="right" :offset="6" popper-class="el-menu-tooltip">
            <div class="el-menu-tooltip__trigger" @click="toView('admin.profile')">
              <img src="/static/images/shop/avatar.png" class="mr-4px w-40px h-40px rounded-full" />
            </div>
          </el-tooltip>
        </div> -->
        <div class="el-menu-item sa-m-t-10">
          <el-tooltip effect="light" content="设置" placement="right" :offset="6" popper-class="el-menu-tooltip">
            <div class="el-menu-tooltip__trigger" @click.stop="onOpenSetting">
              <sa-icon icon="sa-setting" size="32" />
            </div>
          </el-tooltip>
        </div>
      </div>
    </el-scrollbar>

    <el-scrollbar v-if="shop.childrenMenu.length > 0" class="menu-2" height="100%" :style="{ width: menu2WidthValue }">
      <el-menu :default-active="route.name" @select="toView">
        <template v-for="menu in shop.childrenMenu" :key="menu">
          <loop-menu :menuItem="menu" :level="0" />
        </template>
      </el-menu>
    </el-scrollbar>
  </div>
</template>

<script setup>
import { onMounted, reactive, computed } from 'vue';
import { useI18n } from 'vue-i18n';
import sheep from '@/sheep';
import { useRouter, useRoute } from 'vue-router';
import { useApp, useModal } from '@/sheep/hooks';
import MenuItem from './menu-item.vue';
import LoopMenu from './loop-menu.vue';
import AppSetting from '../../../setting.vue';
import { isEmpty } from 'lodash';
import { translateNavigation } from '@/utils/navigationI18n';
import { useNavigationConfig } from '@/hooks/useNavigationConfig';
// import { fromQuery } from 'lodash-contrib';

// 简单的查询字符串解析函数
function fromQuery(queryStr) {
  if (!queryStr) return {};
  const params = new URLSearchParams(queryStr);
  const result = {};
  for (const [key, value] of params) {
    result[key] = value;
  }
  return result;
}

const { t, locale } = useI18n();
const {
  navigationWidth,
  menu1WidthValue,
  menu2WidthValue,
  navigationContainerStyle,
  menuItemStyle
} = useNavigationConfig({
  menu1Width: { zh: '104px', en: '140px' },  // 主菜单独立宽度
  menu2Width: { zh: '110px', en: '134px' }   // 子菜单独立宽度
});

const accountStore = sheep.$store('account');
const appStore = sheep.$store('app');
const route = useRoute();
const router = useRouter();

const { appInfo, appBrowser, appMenu } = useApp();
const account = computed(() => accountStore.info);

// 获取商城管理菜单数据（国际化处理）
const shopApp = computed(() => {
  const originalApp = appMenu.value?.find((app) => app.composingKey === 'shop.admin') || { children: [] };

  // 对菜单数据进行国际化处理
  if (originalApp.children && originalApp.children.length > 0) {
    const translatedChildren = translateNavigation(originalApp.children, t);
    return {
      ...originalApp,
      children: translatedChildren
    };
  }

  return originalApp;
});

const shop = reactive({
  name: '',
  childrenMenu: [],
});

function initShop(data, parent) {
  data?.forEach((i) => {
    if (i?.composingKey == route.name) {
      if (isEmpty(parent)) {
        shop.name = i.composingKey;
      } else {
        shop.name = parent.composingKey;
        // 对子菜单进行国际化处理
        shop.childrenMenu = parent.children ? translateNavigation(parent.children, t) : [];
      }
    }
    if (!isEmpty(i?.children)) {
      initShop(i.children, i);
    }
  });
}

function onSelect(composingKey) {
  // 从原始菜单数据中查找，避免国际化处理后的数据结构问题
  const originalApp = appMenu.value?.find((app) => app.composingKey === 'shop.admin') || { children: [] };
  const menu = originalApp.children?.find((m) => m.composingKey == composingKey);

  if (!menu || isEmpty(menu.children)) {
    shop.childrenMenu = [];
    toView(composingKey);
  } else {
    // 对子菜单也进行国际化处理
    shop.childrenMenu = translateNavigation(menu.children, t);
  }
}

async function toView(composingKey) {
  let item = {};
  // 使用原始菜单数据进行查找
  const originalApp = appMenu.value?.find((app) => app.composingKey === 'shop.admin') || { children: [] };
  if (originalApp.children) {
    loopType(originalApp.children);
  }
  function loopType(data) {
    data?.forEach((i) => {
      if (i.composingKey == composingKey) {
        item = i;
      }
      if (!isEmpty(i.children)) {
        loopType(i.children);
      }
    });
  }
  // 根据新数据结构处理不同类型的菜单项
  // type: '1' 菜单, '2' 叶子菜单, '3' 页面, '4' 动作
  if (item.type == 'modal') {
    // 保留原有的 modal 类型处理
    let params = {
      title: item.label,
    };
    if (item.url) params = { ...params, ...fromQuery(item.url) };
    useModal(composingKey, params);
  } else if (item.type == '4') {
    // type: '4' 动作类型，可能需要特殊处理
    // 这里可以根据具体需求添加动作处理逻辑
    console.log('执行动作:', item.label, composingKey);
  } else {
    // type: '1' 菜单, '2' 叶子菜单, '3' 页面 - 都进行路由跳转
    if (composingKey != route.name) {
      router.push({
        name: composingKey,
        query: item.url ? fromQuery(item.url) : {},
      });
      appStore.menuCollapse(appBrowser.value.isMini);
    }
  }
}

// 打开设置
function onOpenSetting() {
  // 手机端菜单折叠
  if (navigator.userAgent.includes('Mobile')) {
    appStore.menuCollapse(true);
  }

  useModal(AppSetting, { class: 'app-setting-dialog is-fullscreen', modal: false });
}

onMounted(() => {
  // 使用原始菜单数据进行初始化
  const originalApp = appMenu.value?.find((app) => app.composingKey === 'shop.admin') || { children: [] };
  if (originalApp.children && originalApp.children.length > 0) {
    initShop(originalApp.children, {});
  }
});
</script>

<style lang="scss" scoped>
.shop-menu {
  --el-menu-active-color: var(--el-color-primary);
  --el-menu-text-color: var(--el-text-color-primary);
  --el-menu-hover-text-color: var(--el-color-primary);
  --el-menu-bg-color: transparent; //
  --el-menu-hover-bg-color: transparent; //
  --el-menu-item-height: 56px;
  --el-menu-sub-item-height: calc(var(--el-menu-item-height) - 6px);
  --el-menu-horizontal-sub-item-height: 36px;
  --el-menu-item-font-size: var(--el-font-size-base);
  --el-menu-item-hover-fill: var(--el-color-primary-light-9);
  --el-menu-border-color: var(--el-border-color);
  --el-menu-base-level-padding: 16px; //
  --el-menu-level-padding: 16px; //
  --el-menu-icon-width: 24px;
  --el-menu-icon-transform-closed: none;
  --el-menu-icon-transform-open: rotateZ(180deg);

  height: 100%;
  display: flex;
  background: var(--t-bg-color);

  .el-menu {
    border-right: none;
  }

  .title {
    line-height: 64px;
    padding: 0 12px;
    font-size: 20px;
    font-weight: 500;
    color: var(--sa-subtitle);
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .menu-1 {
    --el-menu-item-height: 48px;
    --el-menu-text-color: #737182;

    /* 移除固定宽度，使用动态宽度 */
    min-width: 104px;
    padding: 0 0 0 8px;
    position: relative;
    flex-shrink: 0;

    .menu-footer {
      position: absolute;
      bottom: 0;
      left: 0;
      right: 0;
      padding: 0 8px 12px;

      .line {
        height: 1px;
        background: var(--sa-border);
        margin: 10px 0;
      }

      .el-menu-item {
        height: 40px;
        line-height: 40px;
        margin-bottom: 4px;
        border-radius: 8px;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;

        &:hover {
          background: var(--el-color-primary-light-9);
          color: var(--el-color-primary);
        }

        .el-menu-tooltip__trigger {
          display: flex;
          align-items: center;
          justify-content: center;
          width: 100%;
          height: 100%;
        }
      }
    }

    :deep() {
      .el-menu-item {
        .sa-icon {
          width: 16px;
          margin-right: 8px;
        }

        &:hover {
          color: var(--el-color-primary);
        }

        &.is-active {
          background: var(--sa-background-assist);
          border-radius: 16px 0 0 16px;
          box-shadow: -8px 0 8px rgba(205, 205, 205, 0.02);

          &::after {
            content: '';
            position: absolute;
            top: -12px;
            right: 0;
            width: 12px;
            height: 12px;
            background: radial-gradient(circle at 0% 0%,
                transparent 12px,
                var(--sa-background-assist) 0);
          }

          &::before {
            content: '';
            position: absolute;
            right: 0;
            bottom: -12px;
            width: 12px;
            height: 12px;
            background: radial-gradient(circle at 0 100%,
                transparent 12px,
                var(--sa-background-assist) 0);
          }
        }
      }
    }
  }

  .menu-2 {
    --el-menu-text-color: var(--sa-subtitle);
    --el-menu-item-height: 40px;

    /* 移除固定宽度，使用动态宽度 */
    min-width: 110px;
    padding: 12px 8px;
    background: var(--sa-background-assist);
    border-radius: 8px 0 0;
    border-right: 1px solid var(--sa-border);
    flex-shrink: 0;

    :deep() {
      .el-menu-item {
        border-radius: 8px;
        margin-bottom: 4px;

        &.is-active,
        &:hover {
          background: var(--t-bg-hover);
        }
      }

      .sa-icon {
        display: none !important;
      }
    }
  }

  /* 响应式设计 */
  @media (max-width: 768px) {
    .menu-1 {
      min-width: 80px;
    }

    .menu-2 {
      min-width: 90px;
    }
  }

  @media (max-width: 480px) {
    .menu-1 {
      min-width: 60px;
    }

    .menu-2 {
      min-width: 80px;
    }
  }
}
</style>
