<template>
    <app-view class="swap-detail">
        <template #header>
            <app-navbar :title="item.goodscode + '/' + item.goodsname">
                <template #right>
                    <div class="button-more" v-if="userStore.userType != 5" @click="onListing">
                        <span>挂牌</span>
                    </div>
                </template>
            </app-navbar>
        </template>
        <component :is="Price" v-bind="{ goodsCode }" />
        <component :is="Chart" v-bind="{ goodsCode }" />
        <component :is="Tik" v-bind="{ goodsCode }" />
        <app-pull-refresh ref="pullRefreshRef" v-model:loading="loading" v-model:error="error" v-model:pageIndex="pageIndex"
            :page-count="pageCount" @refresh="onRefresh">
            <Tabs v-model:active="tabIndex" @click="onTabChange">
                <Tab title="买大厅" :name="BuyOrSell.Buy" />
                <Tab title="卖大厅" :name="BuyOrSell.Sell" />
            </Tabs>
            <div class="trade-section sell" v-if="dataList.length">
                <app-list :columns="columns" :data-list="dataList">
                    <template #username="{ row }">
                        <span>{{ row.userid }}/{{ row.username }}</span>
                    </template>
                    <template #operate="{ row }">
                        <Button size="small" type="primary" :disabled="status(row) === 2 || status(row) === 3 " round @click="onDelisting(row)">
                            {{ getDelistingButtonTitles(tabIndex, row) }}
                        </Button>
                    </template>
                </app-list>
            </div>
        </app-pull-refresh>
        <component ref="componentRef" :is="componentMap.get(componentId)" v-bind="{ selectedRow, tabIndex, item, memberUserId }"
            @closed="closeComponent" v-if="componentId" />
    </app-view>
</template>

<script lang="ts" setup>
import { shallowRef, defineAsyncComponent, computed } from 'vue'
import { Tab, Tabs, Button, showToast } from 'vant'
import { useRequest } from '@/hooks/request'
import { useNavigation } from '@mobile/router/navigation'
import { useComponent } from '@/hooks/component'
import { BuyOrSell } from '@/constants/order'
import { queryTjmdTradeOrderDetail, queryMdUserSwapProtocol } from '@/services/api/swap'
import { useFuturesStore } from '@/stores'
import { useLoginStore, useUserStore } from '@/stores'
import AppPullRefresh from '@mobile/components/base/pull-refresh/index.vue'
import AppList from '@mobile/components/base/list/index.vue'
import { getUserId } from '@/services/methods/user'

const Price = defineAsyncComponent(() => import('@mobile/components/modules/quote/price/index.vue'))
const Chart = defineAsyncComponent(() => import('@mobile/components/modules/quote/chart/index.vue'))
const Tik = defineAsyncComponent(() => import('@mobile/components/modules/quote/tik/index.vue'))

const componentMap = new Map<string, unknown>([
    ['delisting', defineAsyncComponent(() => import('./components/delisting/Index.vue'))],
    ['listing', defineAsyncComponent(() => import('./components/listing/Index.vue'))],
])

const pullRefreshRef = shallowRef()
const loginStore = useLoginStore()
const { getGlobalUrlParams, router } = useNavigation()
const item: Model.QuoteGoodsListRsp = getGlobalUrlParams()
const tabIndex = shallowRef(0)
const selectedRow = shallowRef<Model.TjmdTradeOrderDetailRsp>()
const error = shallowRef(false)
const dataList = shallowRef<Model.TjmdTradeOrderDetailRsp[]>([])
const futuresStore = useFuturesStore()
const quote = futuresStore.getGoodsQuote(item.refgoodsid)
const goodsCode = computed(() => quote.value?.goodscode ?? '')
const userStore = useUserStore()

const { componentRef, componentId, openComponent, closeComponent } = useComponent(() => onTabChange())

/// 查询用户掉期协议签署表
const { dataList: protocolList} = useRequest(queryMdUserSwapProtocol, {
    params: {
        userId: getUserId()
    }
})

const status = (row: Model.TjmdTradeOrderDetailRsp) => {
    return protocolList.value.find((e) => e.areauserid === row.userid)?.protocolstatus ?? 1
}

const { pageIndex, loading, run, pageCount } = useRequest(queryTjmdTradeOrderDetail, {
    params: {
        pagesize: 20,
        goodsid: item.goodsid,
        buyorsell: tabIndex.value
    },
    onSuccess: (res) => {
        if (pageIndex.value === 1) {
            dataList.value = []
        }
        dataList.value.push(...res.data)
    },
    onError: () => {
        error.value = true
    }
})

const getDelistingButtonTitles = (tab: number, row: Model.TjmdTradeOrderDetailRsp) => {
    switch (status(row)) {
        case 1:
            return '签署'
        case 2:
            return '待审核'
        case 3:
            return '待审核'
        default:
            return tab === BuyOrSell.Buy ? '卖出' : '买入'
    }
}

/// 每隔 30 秒去刷新请求数据信息
setTimeout(() => {
    // 获取买卖大厅数据
    run()
}, 30*1000)

const onRefresh = () => {
    run({
        buyorsell: tabIndex.value,
    })
}

const onTabChange = () => {
    /// 重置为1
    pageIndex.value = 1
    onRefresh()
}

const columns: Model.TableColumn[] = [
    { prop: 'orderprice', label: '价格' },
    { prop: 'orderqty', label: '数量' },
    { prop: 'username', label: '挂牌方' },
    { prop: 'operate', label: '摘牌' },
]

const onDelisting = (row: Model.TjmdTradeOrderDetailRsp) => {
    selectedRow.value = row
    /// 不能与自己成交
    if (row.userid === loginStore.userId) {
        showToast('不能与自己成交')
        return
    }
    switch (status(row)) {
        case 4: /// 已签署
            openComponent('delisting')
            break;
        case 1:  /// 未签署
            /// 传对应的机构 ID
            /// 进行下一步
            router.push({name: 'account-protocol', query: { memberUserId: row.userid.toString() }})
            break; 
        default: /// 其他状态
            break;
    }
}

const onListing = () => {
    openComponent('listing')
}

</script>