<template>
  <div class="order-detail g-flex">
    <app-navbar title="详情" />
    <div class="g-flex__body">
      <app-tabs :data-list="chartCycleTypeList" :data-index="1" @change="tabChange">
        <component :is="componentMap.get('echartsTimeline')" goodscode="cu2208"
          v-if="selectedCycleType === ChartCycleType.Time" />
        <component :is="componentMap.get('echartsKline')" goodscode="cu2208" :cycle-type="selectedCycleType" v-else />
      </app-tabs>
    </div>
    <div class="order-detail__footer">
      <Button @click="openComponent('trade')" type="primary" round block>挂牌求购</Button>
    </div>
    <component ref="childComponent" :is="componentMap.get(componentId)" @closed="closeComponent" v-if="componentId" />
  </div>
</template>

<script lang="ts" setup>
import { defineAsyncComponent, ref } from 'vue'
import { onBeforeRouteLeave } from 'vue-router'
import { Button } from 'vant'
import { useComponent } from '@/hooks/component'
import { ChartCycleType, getChartCycleTypeList } from '@/constants/chart'
import AppTabs from '@/components/base/tabs/index.vue'

const componentMap = new Map<string, unknown>([
  ['trade', defineAsyncComponent(() => import('@mobile/components/modules/trade/index.vue'))],
  ['echartsTimeline', defineAsyncComponent(() => import('@mobile/components/modules/echarts-timeline/index.vue'))],
  ['echartsKline', defineAsyncComponent(() => import('@mobile/components/modules/echarts-kline/index.vue'))]
]);

const { componentId, openComponent, closeComponent } = useComponent();
const childComponent = ref();
const selectedCycleType = ref(ChartCycleType.Minutes); // 当前选中的图表周期
const chartCycleTypeList = getChartCycleTypeList();

// 指标切换
const tabChange = (index: number) => {
  selectedCycleType.value = chartCycleTypeList[index].value;
}

onBeforeRouteLeave((to, from, next) => {
  if (componentId.value) {
    childComponent.value?.closed(); // 调用子组件方法
    next(false);
  } else {
    next();
  }
})
</script>

<style lang="less">
@import './index.less';
</style>