<template>
    <app-view class="goods-details">
        <template #header>
            <app-navbar title="转让详情" />
        </template>
        <Form ref="formRef" class="goods-details__form">
            <CellGroup>
                <Field label="交收月份" is-link>
                    <template #input>
                        <app-select v-model="selectedMonth" :options="deliveryMonths" />
                    </template>
                </Field>
                <Field label="到期日期" v-if="selectedMonth">
                    <template #input>
                        <span>{{ formatDate(selectedMonth, 'YYYY-MM-DD') }}</span>
                    </template>
                </Field>
                <Field label="预付比例" is-link v-if="selectedMonth">
                    <template #input>
                        <app-select v-model="selectedRate" :options="depositRates" />
                    </template>
                </Field>
                <Field label="参考价格" v-if="tableList.length">
                    <template #input>
                        <span>{{ tableList[0].tradeprice.toFixed(2) }}</span>
                    </template>
                </Field>
                <Field label="预付金" v-if="tableList.length">
                    <template #input>
                        <span>{{ (tableList[0].tradeprice * selectedRate).toFixed(2) }}</span>
                    </template>
                </Field>
            </CellGroup>
        </Form>
        <div class="goods-details__table" v-if="tableList.length">
            <app-list :columns="columns" :data-list="tableList">
                <template #operate="{ row }">
                    <Button type="primary" size="small" @click="onSubmit(row)">摘牌</Button>
                </template>
            </app-list>
        </div>
        <div class="goods-details__content">
            <template v-if="chartData.price.length">
                <Divider>历史价格走势</Divider>
                <div class="chart">
                    <component :is="componentMap.get('chart')" :loading="loading" :data-list="chartData" />
                </div>
            </template>
            <Divider>商品详情</Divider>
            <div class="gallery">
                <template v-for="(url, index) in goodsImages" :key="index">
                    <img :src="url" alt="" />
                </template>
            </div>
        </div>
    </app-view>
</template>

<script lang="ts" setup>
import { shallowRef, reactive, computed, defineAsyncComponent } from 'vue'
import { CellGroup, Button, Field, Form, FormInstance, showSuccessToast, showFailToast, Divider } from 'vant'
import { fullloading, dialog } from '@/utils/vant'
import { getFileUrl, formatDate, parsePercent } from '@/filters'
import { useNavigation } from '@/hooks/navigation'
import { useRequest } from '@/hooks/request'
import { queryTHJPurchaseTransferDetail } from '@/services/api/contract'
import { useSpotPresaleTransferDesting } from '@/business/trade'
import AppSelect from '@mobile/components/base/select/index.vue'
import AppList from '@mobile/components/base/list/index.vue'
import Long from 'long'

const componentMap = new Map<string, unknown>([
    ['chart', defineAsyncComponent(() => import('@mobile/components/modules/echarts-line/index.vue'))],
])

const { router, getQueryStringToNumber } = useNavigation()
const { formData, destingSubmit } = useSpotPresaleTransferDesting()
const formRef = shallowRef<FormInstance>()

// 图表数据
const chartData = reactive<{ price: number[]; date: string[]; }>({
    price: [],
    date: []
})

const columns: Model.TableColumn[] = [
    { prop: 'transferprice', label: '转让价格' },
    { prop: 'tradeqty', label: '数量' },
    { prop: 'operate', label: '操作' },
]

const { loading, data: details } = useRequest(queryTHJPurchaseTransferDetail, {
    params: {
        wrstandardid: getQueryStringToNumber('wrstandardid')
    },
    onSuccess: (res) => {
        res.data.spotgoodspricelogs.forEach(({ spotgoodsprice, tradedate }) => {
            chartData.price.push(spotgoodsprice)
            chartData.date.push(tradedate)
        })
    }
})

// 当前选中的交割月份
const selectedMonth = shallowRef('')
// 当前选中的定金比例
const selectedRate = shallowRef(0)
// 商品信息
const goodsinfo = computed(() => details.value?.goodsinfo)

// 商品图片列表
const goodsImages = computed(() => {
    const pictureurls = goodsinfo.value?.pictureurls ?? ''
    return pictureurls.split(',').map((path) => getFileUrl(path))
})

// 交割月份列表
const deliveryMonths = computed(() => {
    const list = details.value?.deliverydate ?? []
    const monthMap = new Map<string, { label: string, value: string; }>()
    // 日期去重
    list.forEach(({ enddate, endmonth }) => {
        if (!monthMap.has(enddate)) {
            monthMap.set(enddate, {
                label: endmonth,
                value: enddate,
            })
        }
    })
    return [...monthMap.values()]
})

// 定金比例列表
const depositRates = computed(() => {
    const list = details.value?.deliverydate ?? []
    const rateMap = new Map<number, { label: string, value: number; }>()
    // 比例去重
    list.forEach(({ enddate, depositrate }) => {
        if (enddate === selectedMonth.value) {
            if (!rateMap.has(depositrate)) {
                rateMap.set(depositrate, {
                    label: parsePercent(depositrate),
                    value: depositrate,
                })
            }
        }
    })
    return [...rateMap.values()]
})

// 表格数据
const tableList = computed(() => {
    const list = details.value?.deliverydate ?? []
    return list.filter((e) => e.enddate === selectedMonth.value && e.depositrate === selectedRate.value).sort((a, b) => a.transferprice - b.transferprice)
})

const onSubmit = (item: Model.THJPurchaseTransferDetailRsp['deliverydate'][number]) => {
    dialog({
        message: '确认立即摘牌吗？',
        showCancelButton: true
    }).then(() => {
        formData.TransferID = Long.fromString(item.transferid)
        fullloading(() => {
            destingSubmit().then(() => {
                showSuccessToast('摘牌成功')
                router.replace({ name: 'my-order' })
            }).catch((err) => {
                showFailToast(err)
            })
        })
    })
}
</script>

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