<template>
    <app-popup class="supply-demand-listing" :title="buyorsell === BuyOrSell.Sell ? '卖出' : '买入'"
        v-model:show="showModal" :refresh="refresh">
        <Form class="supply-demand-listing__form" ref="formRef" @submit="onSubmit">
            <Field label="挂牌方">
                <template #input>
                    <span>{{ quoteDetail.username }}</span>
                </template>
            </Field>
            <Field label="挂牌价格">
                <template #input>
                    <span>{{ quoteDetail.fixedprice }}</span>
                </template>
            </Field>
            <Field label="剩余数量">
                <template #input>
                    <span>{{ quoteDetail.orderqty }}</span>
                </template>
            </Field>
            <Field name="WRFactorTypeId" :rules="formRules.WRFactorTypeId" label="现货仓单" is-link
                v-if="buyorsell === BuyOrSell.Sell">
                <template #input>
                    <app-select :options="dataList" :optionProps="{ label: 'wrholdeno', value: 'wrid' }"
                        @confirm="onConfirm" />
                </template>
            </Field>
            <Field name="OrderQty" :rules="formRules.OrderQty" label="摘牌数量">
                <template #input>
                    <Stepper v-model="formData.OrderQty" theme="round" button-size="22" integer />
                </template>
            </Field>
            <Field label="货款金额">
                <template #input>
                    <span>{{ amount }}</span>
                </template>
            </Field>
            <Field label="可用资金" v-if="buyorsell === BuyOrSell.Buy">
                <template #input>
                    <span>{{ avaiableMoney.toFixed(2) }}</span>
                </template>
            </Field>
        </Form>
        <template #footer>
            <Button type="primary" block round @click="formRef?.submit">确定</Button>
        </template>
    </app-popup>
</template>

<script lang="ts" setup>
import { shallowRef, PropType, computed } from 'vue'
import { Form, Field, Stepper, Button, Toast, FieldRule, FormInstance } from 'vant'
import { fullloading, dialog } from '@/utils/vant'
import { useLoginStore, useAccountStore } from '@/stores'
import { BuyOrSell } from '@/constants/order'
import { queryHoldLB } from '@/services/api/order'
import { useHdWRDealOrder } from '@/business/trade'
import Long from 'long'
import AppPopup from '@mobile/components/base/popup/index.vue'
import AppSelect from '@mobile/components/base/select/index.vue'

const props = defineProps({
    quote: {
        type: Object as PropType<Model.OrderQuoteRsp>,
        required: true
    },
    quoteDetail: {
        type: Object as PropType<Model.OrderQuoteDetailRsp>,
        required: true
    },
    buyorsell: {
        type: Number,
        required: true
    }
})

const { getFirstAccountId } = useLoginStore()
const { avaiableMoney } = useAccountStore()
const { formData, formSubmit } = useHdWRDealOrder()
const formRef = shallowRef<FormInstance>()
const refresh = shallowRef(false) // 是否刷新父组件数据
const showModal = shallowRef(true)
const dataList = shallowRef<Model.HoldLBRsp[]>([]) //现货仓单列表
const selectedRow = shallowRef<Model.HoldLBRsp>() //选择的仓单

// 货款金额
const amount = computed(() => {
    const { OrderQty = 0 } = formData
    const { fixedprice = 0 } = props.quoteDetail
    return (OrderQty * fixedprice).toFixed(2)
})

// 关闭弹窗
const closed = (isRefresh = false) => {
    refresh.value = isRefresh
    showModal.value = false
}

// 表单验证规则
const formRules: { [key in keyof Proto.HdWRDealOrderReq]?: FieldRule[] } = {
    WRFactorTypeId: [{
        message: '请选择现货仓单',
        validator: () => {
            return !!selectedRow.value
        }
    }],
}

// 选择仓单
const onConfirm = (value: string) => {
    selectedRow.value = dataList.value.find((e) => e.wrid === value)
    formRef.value?.validate('WRFactorTypeId')
    formRef.value?.validate('OrderQty')
}

// 提交摘牌
const onSubmit = () => {
    const { wrfactortypeid = '0' } = props.quote ?? {}
    const { wrtradeorderid = '0', marketid } = props.quoteDetail ?? {}

    formData.Header = {
        AccountID: getFirstAccountId(),
        MarketID: marketid
    }
    formData.BuyOrSell = props.buyorsell
    formData.RelatedWRTradeOrderID = Long.fromString(wrtradeorderid)
    formData.WRFactorTypeId = Long.fromString(wrfactortypeid)

    if (formData.BuyOrSell === BuyOrSell.Sell) {
        const { subnum, ladingbillid = '0', wrfactortypeid = '0' } = selectedRow.value ?? {}
        formData.LadingBillId = Long.fromString(ladingbillid)
        formData.SubNum = subnum
        formData.WRFactorTypeId = Long.fromString(wrfactortypeid)
    }

    fullloading((hideLoading) => {
        formSubmit().then(() => {
            hideLoading()
            dialog('摘牌提交成功。').then(() => closed(true))
        }).catch((err) => {
            Toast.fail(err)
        })
    })
}

queryHoldLB({
    data: {
        accountid: getFirstAccountId(),
        wrstandardid: props.quote.wrstandardid
    },
    success: (res) => {
        dataList.value = res.data
    }
})

// 暴露组件属性给父组件调用
defineExpose({
    closed,
})
</script>

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