<template>
  <app-view class="home-main">
    <template #header>
      <app-navbar :title="globalStore.getSystemInfo('appName')" :show-back-button="false" />
    </template>
    <Banner :data-list="topBanners" />
    <PullRefresh class="home-main__container" v-model="refreshing" @refresh="onRefresh">
      <app-block>
        <Cell title="通知公告" value="更多" :to="{ name: 'notice-list' }" icon="volume" is-link />
      </app-block>
      <app-block class="home-main__chart" v-if="userStore.accountName && goodsGroup.length">
        <Swipe :show-indicators="false" :loop="false">
          <SwipeItem v-for="(list, i) in goodsGroup" :key="i">
            <ul>
              <template v-for="(item, n) in list" :key="n">
                <li :class="[item.lastColor, item.goodsid === selectedGoods?.goodsid ? 'is-active' : '']"
                  @click="onTabChange(item)">
                  <div>
                    <b style="color: #444;">{{ item.goodsname }}</b>
                  </div>
                  <div>
                    <b>{{ item.last }}</b>
                  </div>
                  <div>
                    <span>{{ item.rise }}</span>
                    <span>{{ item.change }}</span>
                  </div>
                </li>
              </template>
            </ul>
          </SwipeItem>
        </Swipe>
        <component :is="LineChart" :goodscode="selectedGoods.refgoodscode" v-if="showChart && selectedGoods" />
      </app-block>
      <app-block class="home-main__news">
        <CellGroup class="article">
          <Cell class="home-main__titlebar" title="市场资讯" value="更多" icon="fire" :to="{ name: 'news-list' }" is-link />
          <template v-for="(item, index) in newsList" :key="index">
            <Cell class="article-item" :title="item.title" :value="formatDate(item.publishdate, 'MM/DD')"
              :to="{ name: 'news-detail', query: { id: item.id } }" />
          </template>
        </CellGroup>
      </app-block>
    </PullRefresh>
  </app-view>
</template>

<script lang="ts" setup>
import { shallowRef, defineAsyncComponent, computed, nextTick, watch } from 'vue'
import { Cell, CellGroup, PullRefresh, Swipe, SwipeItem } from 'vant'
import { formatDate, parsePercent, handleNumberValue, formatDecimal } from '@/filters'
import { queryQuoteGoodsList } from '@/services/api/swap'
import { queryImageConfigs } from '@/services/api/common'
import { queryNewTitles } from "@/services/api/news"
import { useGlobalStore,  useUserStore, useFuturesStore } from '@/stores'
import quoteSocket from '@/services/websocket/quote'
import Banner from '@mobile/components/base/banner/index.vue'

const LineChart = defineAsyncComponent(() => import('@mobile/components/modules/echarts/line/index.vue'))

const subscribe = quoteSocket.createSubscribe()
const globalStore = useGlobalStore()
const userStore = useUserStore()
const futuresStore = useFuturesStore()
const refreshing = shallowRef(false) // 是否处于加载中状态
const topBanners = shallowRef<string[]>([]) // 轮播图列表
const newsList = shallowRef<Model.NewTitlesRsp[]>([]) // 资讯列表
const goodsList = shallowRef<Model.QuoteGoodsListRsp[]>([]) // 掉期商品列表
const selectedGoods = shallowRef<Model.QuoteGoodsListRsp>() // 选中的掉期商品
const showChart = shallowRef(false)

// 掉期商品组
const goodsGroup = computed(() => {
  const arr = []
  const list = goodsList.value.map(({ goodsid, goodsname, refgoodscode }) => {
    const quote = futuresStore.getGoodsQuote(refgoodscode)
    const { lastColor, last = 0, rise = 0, change, decimalplace } = quote.value ?? {}
    return {
      goodsid,
      goodsname,
      refgoodscode,
      lastColor,
      last: handleNumberValue(formatDecimal(last, decimalplace)),
      rise: handleNumberValue(formatDecimal(rise, decimalplace)),
      change: parsePercent(change)
    }
  })
  // 分割成三个一组
  for (let i = 0; i < list.length; i += 3) {
    arr.push(list.slice(i, i + 3))
  }
  return arr
})

// 切换掉期商品
const onTabChange = (item: unknown) => {
  showChart.value = false
  selectedGoods.value = item as Model.QuoteGoodsListRsp

  nextTick(() => {
    showChart.value = true
  })
}

// 下拉刷新
const onRefresh = () => {
  if (!topBanners.value.length) {
    queryImageConfigs({
      data: {
        imageType: 1,
      }
    }).then((res) => {
      topBanners.value = res.data.map((e) => e.imagepath)
    })
  }
  // 市场资讯
  queryNewTitles({
    data: {
      page: 1,
      pagesize: 10,
    }
  }).then((res) => {
    newsList.value = res.data
  }).finally(() => {
    refreshing.value = false
  })
}

onRefresh()

watch(() => userStore.accountName, (accountName) => {
  if (accountName) {
    if (goodsList.value.length) {
      const goodsCodes = goodsList.value.map((e) => e.refgoodscode)
      subscribe.start(...goodsCodes)
    } else {
      // 掉期商品
      queryQuoteGoodsList({
        data: {
          usertype: userStore.userType ?? 0,
          marketids: userStore.getMarketId('TRADEMODE_TJMD').toString()
        }
      }).then((res) => {
        if (res.data.length) {
          const goodsCodes = res.data.map((e) => e.refgoodscode)
          goodsList.value = res.data
          selectedGoods.value = res.data[0]
          showChart.value = true
          subscribe.start(...goodsCodes)
        }
      })
    }
  }
}, {
  immediate: true
})
</script>

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