import { IModal, ViewMode } from '@ibiz-template/runtime';
import {
  getViewName,
  useNamespace,
  useRoute,
  useRouter,
  useTabExpViewController,
} from '@ibiz-template/vue-util';
import {
  computed,
  defineComponent,
  getCurrentInstance,
  PropType,
  h,
  ref,
} from 'vue';
import './tab-exp-view.scss';

export const TabExpView = defineComponent({
  props: {
    context: Object as PropType<IContext>,
    params: { type: Object as PropType<IParams> },
    modelPath: { type: String, required: true },
    modal: { type: Object as PropType<IModal> },
    noLoadDefault: { type: Boolean, required: false },
  },
  setup(props) {
    const { proxy } = getCurrentInstance()!;
    const ns = useNamespace('view-detabexpview');
    const c = useTabExpViewController(proxy, props.modelPath);
    const lazyList = ref<string[]>([]);
    const activeTab = ref('');
    // 使分页都不激活
    const deactivateAll = ref(false);
    const router = useRouter(proxy);

    const tabExpPagesHistory: {
      [page: string]: string;
    } = {};

    // 点击回调
    const onTabClick = async (name: string) => {
      const route = useRoute(proxy);
      // 标签切换前缓存当前路径
      const fullPath = route.fullPath;
      tabExpPagesHistory[activeTab.value] = fullPath;

      // 找到对应分页模型并初始化分页视图模型
      const page = c.model.tabExpPanel.tabExpPages.find(
        item => item.name === name,
      );
      // 分页面板视图延迟初始化
      if (page?.embedView.initialized === false) {
        await page.embedView.init();
      }

      if (c.context.isRouter) {
        // 先让已有的分页变为不活跃
        deactivateAll.value = true;
        // 路由模式下变更路由
        if (tabExpPagesHistory[name]) {
          // 如果缓存过了路径直接跳路径
          router.push(tabExpPagesHistory[name]);
        } else {
          const tempContext = Object.assign(c.context.clone(), {
            toRouteLevel: c.modal.level! + 1,
          });
          ibiz.openView.root(page!.embedView.source, tempContext, c.params);
        }
        setTimeout(() => {
          deactivateAll.value = false;
          activeTab.value = name;
        }, 0);
      } else if (!lazyList.value.includes(name)) {
        lazyList.value.push(name);
        activeTab.value = name;
      }
    };

    // 处理默认展示分页，预置是第一个分页
    c.nerve.self.evt.on('created', () => {
      const route = useRoute(proxy);
      const { tabExpPages } = c.model.tabExpPanel;
      // 路由呈现下，处理默认打开的标签页
      if (c.context.isRouter) {
        const tabLevel = props.modal!.level! + 1;
        const tabViewName = route.params[`view${tabLevel}`];
        if (tabViewName) {
          const page = tabExpPages.find(item => {
            return getViewName(item.embedView.source) === tabViewName;
          });
          if (page) {
            activeTab.value = page.name;
          }
        }
      }

      // 路由没有打开的分页时，默认打开第一个分页
      if (tabExpPages.length && !activeTab.value) {
        const defaultTab = tabExpPages[0].name;
        onTabClick(defaultTab);
      }
    });

    const keyHistory = computed(() => {
      return Object.values(c.tabExpPages).map(item => item.key);
    });

    const embedViewModal = { mode: ViewMode.EMBED };

    return {
      c,
      ns,
      onTabClick,
      lazyList,
      deactivateAll,
      activeTab,
      keyHistory,
      embedViewModal,
    };
  },
  render() {
    const isRouter = this.c.context.isRouter === true;
    return (
      <view-base
        class={[this.ns.b(), isRouter ? this.ns.m('route') : '']}
        controller={this.c}
      >
        {this.c.complete && [
          <i-tabs
            class={this.ns.e('tab')}
            name={this.c.model.codeName}
            model-value={this.activeTab}
            on-on-click={this.onTabClick}
          >
            {this.c.model.tabExpPanel.tabExpPages.map(page => {
              const tabExpPage = this.c.tabExpPages[page.name];
              if (!tabExpPage) {
                return;
              }
              return (
                <i-tab-pane
                  class={this.ns.e('tab-item')}
                  tab={this.c.model.codeName}
                  label={page.source.caption}
                  name={page.name}
                >
                  {this.lazyList.includes(page.name) &&
                    h('ViewShell', {
                      attrs: {
                        context: this.c.context,
                        params: this.c.params,
                        modal: this.embedViewModal,
                        modelPath: page.embedView.source.modelPath,
                      },
                      on: {
                        neuronInit: this.c.nerve.onNeuronInit(page.name),
                      },
                      key: tabExpPage.key,
                    })}
                </i-tab-pane>
              );
            })}
          </i-tabs>,
          isRouter && this.activeTab && (
            <div class={this.ns.e('route-content')}>
              <router-view
                // manualKey={this.c.tabExpPages[this.activeTab].key}
                key={this.c.tabExpPages[this.activeTab].key}
                on-neuron-init={this.c.nerve.onNeuronInit(this.activeTab)}
              >
                {({ Component }: { Component: string }) => {
                  return (
                    Component && (
                      <appKeepAlive keyList={this.keyHistory}>
                        <Component />
                      </appKeepAlive>
                    )
                  );
                }}
              </router-view>
            </div>
          ),
        ]}
      </view-base>
    );
  },
});
