<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 }" />
        <Tabs v-model:active="tabIndex" @click="onRefresh" style="margin-top: .2rem;">
            <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 #orderprice="{ row }">
                    <span :class="quote?.lastColor">{{ row.pricemode === 3 ? estimateprice(row) : row.orderprice
                    }}</span>
                </template>
                <template #username="{ row }">
                    <span>{{ row.userid }}/{{ row.username }}</span>
                </template>
                <template #operate="{ row }">
                    <Button size="small" type="primary" :disabled="isDisable(row)" @click="onDelisting(row)">
                        {{ getDelistingButtonTitles(tabIndex, row) }}
                    </Button>
                </template>
            </app-list>
        </div>
        <Empty description="暂无数据" v-else />
        <component :is="Tik" v-bind="{ goodsCode }" />
        <component ref="componentRef" :is="componentMap.get(componentId)" v-bind="{ selectedRow, tabIndex, item }"
            @closed="closeComponent" v-if="componentId" />
    </app-view>
</template>

<script lang="ts" setup>
import { shallowRef, defineAsyncComponent, computed } from 'vue'
import { Tab, Tabs, Button, showToast,Empty } 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 AppList from '@mobile/components/base/list/index.vue'
import { getUserId } from '@/services/methods/user'
import { formatDecimal } from '@/filters'

const Price = defineAsyncComponent(() => import('@mobile/components/modules/quote/price/index.vue'))
const Chart = defineAsyncComponent(() => import('@mobile/components/modules/hqchart/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 loginStore = useLoginStore()
const { getGlobalUrlParams, router } = useNavigation()
const item: Model.QuoteGoodsListRsp = getGlobalUrlParams()
const tabIndex = shallowRef(0)
const selectedRow = 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(() => onRefresh())

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

/// 估算价格
const estimateprice = (row: Model.TjmdTradeOrderDetailRsp) => {
    const decimalplace = (item.decimalplace ?? 2.0)
    return formatDecimal((row.marketmaxsub + (quote.value?.last ?? 0.0)), decimalplace)
}

const isDisable = (row: Model.TjmdTradeOrderDetailRsp) => {
    return row.userid === getUserId() || (status(row) === 2 || status(row) === 3)
}

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

const { dataList, run } = useRequest(queryTjmdTradeOrderDetail, {
    params: {
        goodsid: item.goodsid,
        buyorsell: tabIndex.value
    }
})

const getDelistingButtonTitles = (tab: number, row: Model.TjmdTradeOrderDetailRsp) => {
    /// 如果是机构自己的单 不能签署
    if (row.userid === getUserId()) {
        return '摘牌'
    }
    switch (status(row)) {
        case 1:
            return '签署'
        case 2:
            return '待审核'
        case 3:
            return '待审核'
        default:
            return '摘牌'
    }
}

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

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

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>