<template>
  <app-view class="order-details">
    <template #header>
      <app-navbar title="详情" />
    </template>
    <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>
    <Button @click="backTo('home')">返回首页</Button>
    <template #footer>
      <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" />
    </template>
  </app-view>
</template>

<script lang="ts" setup>
import { defineAsyncComponent, ref } from 'vue'
import { Button } from 'vant'
import { useNavigation } from '@/hooks/navigation'
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 { backTo, beforeRouteLeave } = useNavigation()
const { componentId, openComponent, closeComponent, hasComponent } = useComponent()
const childComponent = ref()
const selectedCycleType = ref(ChartCycleType.Minutes) // 当前选中的图表周期
const chartCycleTypeList = getChartCycleTypeList()

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

beforeRouteLeave(() => {
  if (hasComponent()) {
    childComponent.value?.closed() // 调用子组件方法
    return false
  }
  return true
})
</script>

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