<template>
    <app-view class="goods-details">
        <template #header>
            <app-navbar title="转让详情" />
        </template>
        <Form ref="formRef" class="goods-details__form" @submit="onSubmit">
            <CellGroup>
                <Field name="TransferID" label="交收月份" :rules="formRules.TransferID" is-link>
                    <template #input>
                        <app-select :options="deliveryDate" @confirm="onDateChange" />
                    </template>
                </Field>
                <Field label="到期日期" v-if="selectedDate?.enddate">
                    <template #input>
                        <span>{{ formatDate(selectedDate.enddate, 'YYYY-MM-DD') }}</span>
                    </template>
                </Field>
                <Field label="原定金价" v-if="selectedDate?.tradeprice">
                    <template #input>
                        <span>{{ selectedDate.tradeprice }}</span>
                    </template>
                </Field>
                <Field label="数量" v-if="selectedDate?.tradeqty">
                    <template #input>
                        <span>{{ selectedDate.tradeqty }}</span>
                    </template>
                </Field>
                <Field label="转让价格" v-if="selectedDate?.transferprice">
                    <template #input>
                        <span>{{ selectedDate.transferprice }}</span>
                    </template>
                </Field>
                <Field label="转让金额" v-if="selectedDate?.transferamount">
                    <template #input>
                        <span>{{ selectedDate.transferamount }}</span>
                    </template>
                </Field>
            </CellGroup>
        </Form>
        <div class="goods-details__content">
            <div class="submitbar">
                <Button type="primary" @click="formRef?.submit" round block>摘牌</Button>
            </div>
            <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, computed, defineAsyncComponent } from 'vue'
import { CellGroup, Button, Field, Form, FormInstance, Toast, FieldRule, Divider } from 'vant'
import { fullloading } from '@/utils/vant'
import { getImageUrl, formatDate, parsePercent } from '@/filters'
import { useNavigation } from '@/hooks/navigation'
import { useContractDetails } from '@/business/contract'
import { useSpotPresaleTransferDesting } from '@/business/trade'
import AppSelect from '@mobile/components/base/select/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 wrstandardid = getQueryStringToNumber('wrstandardid')
const formRef = shallowRef<FormInstance>()

const { loading, details, chartData, getContractDetails } = useContractDetails(wrstandardid)
const { formData, destingSubmit } = useSpotPresaleTransferDesting()

// 当前选中的交割日期
const selectedDate = shallowRef<Model.THJPurchaseTransferDetailRsp['deliverydate'][number]>()
// 商品信息
const goodsinfo = computed<Partial<Model.THJPurchaseTransferDetailRsp['goodsinfo']>>(() => details.value.goodsinfo ?? {})

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

// 表单验证规则
const formRules: { [key in keyof Proto.SpotPresaleTransferDestingReq]?: FieldRule[] } = {
    TransferID: [{
        message: '请选择到期日期',
        validator: () => {
            return !formData.TransferID?.equals(0)
        }
    }],
}

// 交割日期列表
const deliveryDate = computed(() => {
    const list = details.value.deliverydate ?? []
    return list.map((e) => ({
        label: `${formatDate(e.enddate, 'YYYY-MM')} ${parsePercent(e.depositrate)}`,
        value: e.transferid,
    }))
})

// 切换交割日期
const onDateChange = (value: string) => {
    const list = details.value.deliverydate ?? []
    selectedDate.value = list.find((e) => e.transferid === value)

    formData.TransferID = Long.fromString(value)
    formRef.value?.validate('TransferID')
}

const onSubmit = () => {
    fullloading(() => {
        destingSubmit().then(() => {
            Toast.success('摘牌成功')
            router.replace({ name: 'my-order' })
        }).catch((err) => {
            Toast.fail(err)
        })
    })
}

getContractDetails()
</script>

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