<template>
  <template v-if="model.menuNodeType === 'Branch'">
    <a-sub-menu :key="model.key" :title="menuTitle">
      <template #icon>
        <i :class="model.icon" />
      </template>
      <template v-for="item in model.children" :key="item.key">
        <menu-node :model="item" />
      </template>
    </a-sub-menu>
  </template>

  <a-menu-item v-else :key="model.key" @click="handleClick">
    <template #icon>
      <star-filled v-if="model.favorite" class="favorite-icon" @click.stop="toggleFavorite" />
      <star-outlined v-else class="favorite-icon" @click.stop="toggleFavorite" />
    </template>
    {{ menuTitle }}
  </a-menu-item>
</template>

<script>
import { StarOutlined, StarFilled } from '@ant-design/icons-vue';
import Common from '../common/Common.js';
import Language from '../common/Language.js';
import RouteUtil from '../common/RouteUtil.js';
import { Notify, Uuid } from 'pc-component-v3';
import CurdWindowResourceV2 from '../api/dic/CurdWindowResourceV2.js';
import HtmlWindowResource from '../api/dic/HtmlWindowResource.js';
import CustomerWindowResource from '../api/dic/CustomerWindowResource.js';
import UserMenuClickCountResource from '../api/system/UserMenuClickCountResource.js';
import UserMenuResource from '../api/system/UserMenuResource.js';
import { menuClickedEvent } from '../common/eventBus.js';

export default {
  name: 'MenuNode',
  components: {
    StarOutlined,
    StarFilled,
  },
  props: {
    model: {
      type: Object,
      required: true,
    },
  },
  emits: ['selectNode'],
  computed: {
    menuTitle() {
      return Language.getMenuNameTrl(this.$i18n.locale, this.model);
    },
  },
  methods: {
    // 处理菜单点击
    async handleClick() {
      const menuInfo = {
        title: this.menuTitle,
        menuNodeType: this.model.menuNodeType,
        no: this.model.no,
      };

      this.clickMenuNode(menuInfo);
      this.changeUserMenuClickCount();
    },

    // 打开对应菜单窗口
    async clickMenuNode(menuInfo) {
      console.log(menuInfo, 'menuInfo');
      const nodeType = this.model.menuNodeType;
      if (!nodeType || nodeType === 'NONE') return;

      const routeMap = {
        Report: () =>
          this.$router.push(
            `/desktop/process-report/${this.model.processReportNo}`,
          ),
        Process: () =>
          this.$router.push(
            `/desktop/process-report/${this.model.processReportNo}`,
          ),
        Window: this.handleWindowType,
        SheetWindow: () =>
          this.$router.push(
            `/desktop/sheetWindow/${this.model.sheetCurdWindowNo
            }?uuid=${Uuid.createUUID()}`,
          ),
        Info: () =>
          this.$router.push(`/desktop/info/${this.model.infoWindowNo}`),
        Customer: this.handleCustomerWindow,
        HTML: this.handleHtmlWindow,
        LOWCODE: () =>
          this.$router.push(
            `/desktop/lowcode-example/${this.model.lowcodeWindowNo}`,
          ),
      };

      if (routeMap[nodeType]) {
        await routeMap[nodeType]();
        
        // 使用 nextTick 和 setTimeout 确保在路由变化完成后获取正确的路径
        this.$nextTick(() => {
          // 给路由一点时间完成更新
          setTimeout(() => {
            // 触发事件
            menuClickedEvent.value = {
              path: this.$route.fullPath,
              menuInfo: menuInfo,
            };
          }, 50);
        });
      }

    },

    // 处理Window类型
    async handleWindowType() {
      try {
        const res = await CurdWindowResourceV2.uniqueByNoAccessControl(
          this.model.curdWindowNo,
        );
        if (res.errorCode !== 0) {
          Notify.error(
            this.$t('lang.Notify.errorOpeningCURDWindow'),
            res.errorMessage,
            false,
          );
          return;
        }

        const versionRes = await CurdWindowResourceV2.uniqueByNoVersionNumber(
          this.model.curdWindowNo,
        );
        const routeVersion = versionRes.data === -1 ? 'window' : 'window1';
        this.$router.push(
          `/desktop/${routeVersion}/${this.model.curdWindowNo
          }?uuid=${Uuid.createUUID()}`,
        );
      } catch (error) {
        Common.processException(error);
      }
    },

    // 处理客户窗口
    async handleCustomerWindow() {
      try {
        const res = await CustomerWindowResource.uniqueByNo(
          this.model.customerWindowNo,
        );
        if (res.errorCode === 0) {
          const windowType = res.data.windowType;
          if(windowType == 'DYNAMIC_FORM'){
            const formKey = JSON.parse(res.data.dynamicFormConfig).formKey;
            this.$router.push('/desktop/launch?key=' + formKey);
            return;
          }
          this.$router.push(res.data.routeUrl);
        } else {
          Notify.error(this.$t('lang.Notify.error'), res.errorMessage, true);
        }
      } catch (error) {
        Common.processException(error);
      }
    },

    // 处理HTML窗口
    async handleHtmlWindow() {
      try {
        const res = await HtmlWindowResource.uniqueByNo(
          this.model.htmlWindowNo,
        );
        if (res.errorCode === 0) {
          let htmlFileName = res.data.htmlFileName;
          if (htmlFileName?.includes('{URL}')) {
            htmlFileName = htmlFileName.replace(
              '{URL}',
              Common.getHostPageBaseURL(),
            );
          }
          window.open(htmlFileName);
        } else {
          Notify.error(
            this.$t('lang.Notify.dataDictionaryError'),
            res.errorMessage,
            true,
          );
        }
      } catch (error) {
        Common.processException(error);
      }
    },

    // 切换收藏状态
    toggleFavorite() {
      var _self = this;
      UserMenuResource.addToFavoriteList(_self.model.no).then(
        successData => {
          _self.model.favorite = !_self.model.favorite;
        },
        errorData => {
          Common.processException(errorData);
        },
      );
    },

    // 更新菜单点击统计
    async changeUserMenuClickCount() {
      if (!this.model.children?.length) {
        try {
          await UserMenuClickCountResource.changeUserMenuClickCount(
            this.model.no,
          );
        } catch (error) {
          Common.processException(error);
        }
      }
    },
  },
};
</script>

<style scoped>
.favorite-icon {
  color: #ffd666;
  margin-right: 8px;
  transition: color 0.3s;
}

.favorite-icon:hover {
  color: #ffc53d;
}

:deep(.ant-menu-item) {
  display: flex;
  align-items: center;
  transition: all 0.3s;
  padding-left: 54px !important;
}

:deep(.ant-menu-item:hover) {
  background: var(--menu-select-color) !important;
}

:deep(.ant-menu-submenu-title:hover) {
  background: var(--menu-select-color) !important;
}
</style>
