<script>
import { KUBERNETES, PROJECT } from '@shell/config/labels-annotations';
import { FLEET, NAMESPACE, MANAGEMENT, HELM } from '@shell/config/types';
import ButtonGroup from '@shell/components/ButtonGroup';
// import { BadgeState } from '@components/BadgeState';
import DotState from '@shell/components/DotState.vue';
import { Banner } from '@components/Banner';
import { get } from '@shell/utils/object';
import { NAME as FLEET_NAME } from '@shell/config/product/fleet';
import { HIDE_SENSITIVE } from '@shell/store/prefs';
import {
  AS, _DETAIL, _CONFIG, _YAML, MODE, _CREATE, _EDIT, _VIEW, _UNFLAG, _GRAPH
} from '@shell/config/query-params';
import { ExtensionPoint, PanelLocation } from '@shell/core/types';
import ExtensionPanel from '@shell/components/ExtensionPanel';
import TabTitle from '@shell/components/TabTitle';
import ActionMenu from '@shell/components/ActionMenuShell.vue';
import { useRuntimeFlag } from '@shell/composables/useRuntimeFlag';
import { useStore } from 'vuex';
import { harvesterhci2cloud, cloud2harvesterhci } from '@shell/utils/router'

// i18n-uses resourceDetail.header.*

/**
 * Resource Detail Masthead component.
 *
 * ToDo: this component seem to be picking up a lot of logic from special cases, could be simplified down to parameters and then customized per use-case via wrapper component
 */
export default {

  name: 'MastheadResourceDetail',

  components: {
    // BadgeState,
    DotState,
    Banner,
    ButtonGroup,
    ExtensionPanel,
    TabTitle,
    ActionMenu,
  },
  props: {
    value: {
      type:    Object,
      default: () => {
        return {};
      }
    },

    mode: {
      type:    String,
      default: 'create'
    },

    realMode: {
      type:    String,
      default: 'create'
    },

    as: {
      type:    String,
      default: _YAML,
    },

    hasGraph: {
      type:    Boolean,
      default: false
    },

    hasDetail: {
      type:    Boolean,
      default: false
    },

    hasEdit: {
      type:    Boolean,
      default: false
    },

    storeOverride: {
      type:    String,
      default: null,
    },

    resource: {
      type:    String,
      default: null,
    },

    resourceSubtype: {
      type:    String,
      default: null,
    },

    parentRouteOverride: {
      type:    String,
      default: null,
    },

    canViewYaml: {
      type:    Boolean,
      default: false,
    }
  },

  setup() {
    const store = useStore();
    const { featureDropdownMenu } = useRuntimeFlag(store);

    return { featureDropdownMenu };
  },

  data() {
    return {
      DETAIL_VIEW:       _DETAIL,
      extensionType:     ExtensionPoint.PANEL,
      extensionLocation: PanelLocation.DETAILS_MASTHEAD,
      Svg:               require('~shell/assets/images/API.svg')
    };
  },

  computed: {
    dev() {
      return this.$store.getters['prefs/dev'];
    },

    schema() {
      const inStore = this.storeOverride || this.$store.getters['currentStore'](this.resource);

      return this.$store.getters[`${ inStore }/schemaFor`]( this.resource );
    },

    isView() {
      return this.mode === _VIEW;
    },

    isEdit() {
      return this.mode === _EDIT;
    },

    isCreate() {
      return this.mode === _CREATE;
    },

    isNamespace() {
      return this.schema?.id === NAMESPACE;
    },

    isProject() {
      return this.schema?.id === MANAGEMENT.PROJECT;
    },

    isProjectHelmChart() {
      return this.schema?.id === HELM.PROJECTHELMCHART;
    },

    hasMultipleNamespaces() {
      return !!this.value.namespaces;
    },

    namespace() {
      if (this.value?.metadata?.namespace) {
        return this.value?.metadata?.namespace;
      }

      return null;
    },

    detailsAction() {
      return this.value?.detailsAction;
    },

    shouldHifenize() {
      return (this.mode === 'view' || this.mode === 'edit') && this.resourceSubtype?.length && this.value?.nameDisplay?.length;
    },

    namespaceLocation() {
      if (!this.isNamespace) {
        return this.value.namespaceLocation || {
          name:   'c-cluster-product-resource-id',
          params: {
            cluster:  this.$route.params.cluster,
            product:  this.$store.getters['productId'],
            resource: NAMESPACE,
            id:       this.$route.params.namespace
          }
        };
      }

      return null;
    },

    isWorkspace() {
      return this.$store.getters['productId'] === FLEET_NAME && !!this.value?.metadata?.namespace;
    },

    workspaceLocation() {
      return {
        name:   'c-cluster-product-resource-id',
        params: {
          cluster:  this.$route.params.cluster,
          product:  this.$store.getters['productId'],
          resource: FLEET.WORKSPACE,
          id:       this.$route.params.namespace
        }
      };
    },

    project() {
      if (this.isNamespace) {
        const cluster = this.$store.getters['currentCluster'];

        if (cluster) {
          const id = (this.value?.metadata?.labels || {})[PROJECT];

          return this.$store.getters['management/byId'](MANAGEMENT.PROJECT, `${ cluster.id }/${ id }`);
        }
      }

      return null;
    },

    banner() {
      if (this.value?.stateObj?.error) {
        const defaultErrorMessage = this.t('resourceDetail.masthead.defaultBannerMessage.error', undefined, true);

        return {
          color:   'error',
          message: this.value.stateObj.message || defaultErrorMessage
        };
      }

      if (this.value?.spec?.paused) {
        return {
          color:   'info',
          message: this.t('asyncButton.pause.description')
        };
      }

      if (this.value?.stateObj?.transitioning) {
        const defaultTransitioningMessage = this.t('resourceDetail.masthead.defaultBannerMessage.transitioning', undefined, true);

        return {
          color:   'info',
          message: this.value.stateObj.message || defaultTransitioningMessage
        };
      }

      return null;
    },

    parent() {
      const displayName = this.value?.parentNameOverride || this.$store.getters['type-map/labelFor'](this.schema);
      const product = this.$store.getters['currentProduct'].name;

      const defaultLocation = {
        name:   'c-cluster-product-resource',
        params: {
          resource: harvesterhci2cloud(this.resource),
          product,
        }
      };

      const location = this.value?.parentLocationOverride || defaultLocation;

      if (this.parentRouteOverride) {
        location.name = this.parentRouteOverride;
      }

      const typeOptions = this.$store.getters[`type-map/optionsFor`]( this.resource );
      const out = {
        displayName, location, ...typeOptions
      };

      return out;
    },

    hideSensitiveData() {
      return this.$store.getters['prefs/get'](HIDE_SENSITIVE);
    },

    sensitiveOptions() {
      return [
        {
          tooltipKey: 'resourceDetail.masthead.sensitive.hide',
          icon:       'icon-hide',
          value:      true,
        },
        {
          tooltipKey: 'resourceDetail.masthead.sensitive.show',
          icon:       'icon-show',
          value:      false
        }
      ];
    },

    viewOptions() {
      const out = [];

      if ( this.hasDetail ) {
        out.push({
          labelKey: 'resourceDetail.masthead.detail',
          value:    _DETAIL,
        });
      }

      if ( this.hasEdit && this.parent?.showConfigView !== false) {
        out.push({
          labelKey: 'resourceDetail.masthead.config',
          value:    _CONFIG,
        });
      }

      if ( this.hasGraph ) {
        out.push({
          labelKey: 'resourceDetail.masthead.graph',
          value:    _GRAPH,
        });
      }

      if ( this.canViewYaml ) {
        out.push({
          labelKey: 'resourceDetail.masthead.yaml',
          value:    _YAML,
        });
      }

      if ( out.length < 2 ) {
        return null;
      }

      return out;
    },

    currentView: {
      get() {
        return this.as;
      },

      set(val) {
        switch ( val ) {
        case _DETAIL:
          this.$router.applyQuery({
            [MODE]: _UNFLAG,
            [AS]:   _UNFLAG,
          });
          break;
        case _CONFIG:
          this.$router.applyQuery({
            [MODE]: _UNFLAG,
            [AS]:   _CONFIG,
          });
          break;
        case _GRAPH:
          this.$router.applyQuery({
            [MODE]: _UNFLAG,
            [AS]:   _GRAPH,
          });
          break;
        case _YAML:
          this.$router.applyQuery({
            [MODE]: _UNFLAG,
            [AS]:   _YAML,
          });
          break;
        }
      },
    },

    showSensitiveToggle() {
      return !!this.value.hasSensitiveData && this.mode === _VIEW && this.as !== _YAML;
    },

    managedWarning() {
      const { value } = this;
      const labels = value?.metadata?.labels || {};

      const managedBy = labels[KUBERNETES.MANAGED_BY] || '';
      const appName = labels[KUBERNETES.MANAGED_NAME] || labels[KUBERNETES.INSTANCE] || '';

      return {
        show:    this.mode === _EDIT && !!managedBy,
        type:    value?.kind || '',
        hasName: appName ? 'yes' : 'no',
        appName,
        managedBy,
      };
    },

    displayName() {
      let displayName = this.value.nameDisplay;

      if (this.isProjectHelmChart) {
        displayName = this.value.projectDisplayName;
      }

      return this.shouldHifenize ? ` - ${ displayName }` : displayName;
    },

    demoDisplay() {
      const product = this.$store.getters['productId'];

      const productId = this.$store.getters['type-map/groupForBasicType'](this.$store.getters['productId'], this.location.params.resource);

      if (productId === undefined) {
        return '';
      }
      const parts = productId.split('::');
      const newString = 'root';

      if (!parts?.includes(newString)) {
        parts.unshift(newString); // 将字符串添加到数组第一位
      }

      const partsEn = parts.map((item) => {
        return this.$store.getters['i18n/t'](`typeLabel."${ item.toLowerCase() }"`);
      });

      return partsEn;
    },
    menuIcon() {
      const product = this.$store.getters['productId'];

      return this.$store.getters['type-map/groupsForVirTypes'](product, cloud2harvesterhci(this.location.params.resource));
    },

    location() {
      const { parent } = this;

      return parent?.location;
    },

    hideNamespaceLocation() {
      return this.$store.getters['currentProduct'].hideNamespaceLocation || this.value.namespaceLocation === null;
    },

    resourceExternalLink() {
      return this.value.resourceExternalLink;
    },
  },

  methods: {
    get,

    showActions() {
      this.$store.commit('action-menu/show', {
        resources: this.value,
        elem:      this.$refs.actions,
      });
    },

    toggleSensitiveData(e) {
      this.$store.dispatch('prefs/set', { key: HIDE_SENSITIVE, value: !!e });
    },

    invokeDetailsAction() {
      const action = this.detailsAction;

      if (action) {
        const fn = this.value[action.action];

        if (fn) {
          fn.apply(this.value, []);
        }
      }
    }
  }
};
</script>

<template>

  <!-- 顶部区域的容器 -->
  <div class="masthead">
    <div class="title">

      <!-- 面包屑导航（创建 API 密钥时不显示） -->
      <div
        v-if="!(parentRouteOverride === 'account' && resource=== 'token')"
        class="excram-list"
      >

        <!-- 遍历 demoDisplay 生成面包屑路径 -->
        <span
          v-for="(item,index) in demoDisplay"
          :key="index"
        >
          <span v-if="item">{{ item }}</span>
          <span v-if="item">/</span>
        </span>

        <!-- 最后一个面包屑显示当前操作（查看/编辑/创建）+ 父资源名称 -->
        <span class="excram-last-name">
          {{ (realMode === 'view'? '查看': realMode === 'edit' ? '编辑':'创建') + parent.displayName }}
        </span>
      </div>

      <header>
        <div class="title">
          <div class="primaryheader">
            <span class="primary-title">
                
                <!-- 图标区 -->
                <span v-if="menuIcon && !(parentRouteOverride === 'account' && resource=== 'token')" class="detailIcon-span">
                  <!-- 如果是账户 API token，则显示图片，否则显示 icon -->
                  <img
                    v-if="parentRouteOverride === 'account' && resource=== 'token'"
                    :src="Svg"
                    style="margin-top: 4px; margin-left: 5px;"
                  >
                  <i
                    v-else
                    :class="'icon-'+ menuIcon + ' detailIcon'"
                  />
                </span>

                <!-- 资源标题（创建时只显示“创建+名称”，否则显示“名称:”） -->
                <span class="detailIcon-span-title">{{ realMode=== 'create'? '创建': '' }}{{ parent.displayName }}{{ realMode=== 'create'? '': '名称:' }}</span>
                
                <!-- 如果不是创建模式，显示操作描述 -->
                <span v-if="realMode !== 'create'">

                  <!-- 如果有覆盖方法，优先显示覆盖内容 -->
                  <span v-if="value.detailPageHeaderActionOverride && value.detailPageHeaderActionOverride(realMode)">{{ value.detailPageHeaderActionOverride(realMode) }}</span>
                  
                  <!-- 否则用 t 组件国际化显示 -->
                  <t
                    v-else
                    :k="'resourceDetail.header.' + realMode"
                    :subtype="resourceSubtype"
                    :name="displayName"
                    :escapehtml="false"
                  />
                </span>

                <!-- 状态点（DotState 组件） -->
                <DotState
                  v-if="!isCreate && parent.showState"
                  class="masthead-state"
                  :value="value"
                />

                <!-- Istio 注入状态 -->
                <span
                  v-if="!isCreate && value.injectionEnabled"
                  class="masthead-istio"
                >
                  <i
                    v-clean-tooltip="t('projectNamespaces.isIstioInjectionEnabled')"
                    class="icon icon-sm icon-istio"
                  />
                </span>
              </span>

              <!-- 如果有返回路径，显示分隔符和“返回”链接 -->
              <span
                v-if="location"
                class="valid"
              >|</span>
              <router-link
                v-if="location"
                :to="location"
              >
                返回
              </router-link>
          </div>
        </div>

        <!-- 右侧操作按钮区域（支持通过 slot 覆盖） -->
        <slot name="right">
          <div class="actions-container align-start" style="padding-right: 15px;">
            <div class="actions">

              <!-- 详情模式下的主操作按钮 -->
              <button
                v-if="detailsAction && currentView === DETAIL_VIEW && isView"
                type="button"
                class="btn role-primary actions mr-10"
                :disabled="!detailsAction.enabled"
                @click="invokeDetailsAction"
              >
                {{ detailsAction.label }}
              </button>

              <!-- 敏感信息显示/隐藏切换 -->
              <ButtonGroup
                v-if="showSensitiveToggle"
                :value="!!hideSensitiveData"
                icon-size="lg"
                :options="sensitiveOptions"
                class="mr-10"
                @update:value="toggleSensitiveData"
              />

              <!-- 视图切换按钮 -->
              <ButtonGroup
                v-if="viewOptions && isView"
                v-model:value="currentView"
                :options="viewOptions"
                class="mr-10"
              />

              <!-- 功能菜单：优先使用 ActionMenu 组件 -->
              <template v-if="featureDropdownMenu">
                <ActionMenu
                  v-if="isView"
                  button-role="multiAction"
                  button-size="compact"
                  :resource="value"
                  data-testid="masthead-action-menu"
                />
              </template>

              <!-- 如果没有 featureDropdownMenu，则使用普通的多操作按钮 -->
              <template v-else>
                <button
                  v-if="isView"
                  ref="actions"
                  data-testid="masthead-action-menu"
                  aria-haspopup="true"
                  type="button"
                  class="btn role-multi-action actions"
                  @click="showActions"
                >
                  <i class="icon icon-actions" />
                </button>
              </template>
            </div>
          </div>
        </slot>
      </header>

      <!-- 扩展区域 -->
      <ExtensionPanel
        :resource="value"
        :type="extensionType"
        :location="extensionLocation"
      />

      <!-- 顶部状态 Banner -->
      <Banner
        v-if="banner && isView && !parent.hideBanner"
        class="state-banner mb-10"
        :color="banner.color"
        :label="banner.message"
      />

      <!-- 管理警告 Banner -->
      <Banner
        v-if="managedWarning.show"
        color="warning"
        class="mb-20"
        :label="t('resourceDetail.masthead.managedWarning', managedWarning)"
      />

      <!-- 内容插槽 -->
      <slot />
    </div>
  </div>
</template>

<style lang='scss' scoped>
  .masthead {
    padding-bottom: 10px;
    /* border-bottom: 1px solid var(--border); */
    margin-bottom: 10px;
  }

  HEADER {
    margin: 0;
  }

  .primaryheader {
    display: flex;
    flex-direction: row;
    align-items: center;
    font-size:14px;
    height: 50px;

    h1 {
      margin: 0;
    }
  }

  .subheader{
    display: flex;
    flex-direction: row;
    color: var(--input-label);
    & > * {
      margin: 5px 20px 5px 0px;
    }

    .live-data {
      color: var(--body-text)
    }
  }

  .state-banner {
    margin: 3px 0 0 0;
  }

  .masthead-state {
    font-size: initial;
    display: inline-block;
    position: relative;
    /* top: -2px; */
    font-size: 12px;
    margin-left: 5px;
  }

  .masthead-istio {
    .icon {
      vertical-align: middle;
      color: var(--primary);
    }
  }

  .left-right-split {
    display: grid;
    align-items: center;

    .left-half {
      grid-column: 1;
    }

    .right-half {
      grid-column: 2;
    }
  }

  .resource-external {
    font-size: 18px;
  }
  .excram-list{
    font-size: 14px;
    margin-bottom: 20px;
  }
  .excram-last-name{
    color: var(--link);
  }
  .valid{
    color: #d7d7d7;
    margin: 0px 10px;
  }
  .detailIcon-span{
    width: 24px;
    height: 24px;
    display: inline-block;
    position: relative;
    background: var(--primary);
    margin-right: 10px;
  }
  .detailIcon{
    position: absolute;
    color: #fff;
    font-size: 38px;
    left: 4px;
    top: -2px;
  }
  .primary-title{
    display: flex;
    align-items: center;
  }
  .detailIcon-span-title{
    font-weight: bold;
  }
</style>
