<template>
    <app-popup class="supply-demand-listing" :title="buyorsell === BuyOrSell.Sell ? '我要卖' : '我要买'"
        v-model:show="showModal">
        <Form class="supply-demand-listing__form" ref="formRef" @submit="onSubmit">
            <Field name="FixedPrice" :rules="formRules.FixedPrice" label="价格">
                <template #input>
                    <Stepper v-model="formData.FixedPrice" :default-value="quote.spotgoodsprice" theme="round"
                        button-size="22" />
                </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 } 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 { useHdWROrder } 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
    },
    buyorsell: {
        type: Number,
        required: true
    }
})

const { getFirstAccountId } = useLoginStore()
const { avaiableMoney } = useAccountStore()
const { formData, listingSubmit, amount } = useHdWROrder()
const formRef = shallowRef<FormInstance>()
const showModal = shallowRef(true)
const dataList = shallowRef<Model.HoldLBRsp[]>([]) //现货仓单列表
const selectedRow = shallowRef<Model.HoldLBRsp>() //选择的仓单

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

// 表单验证规则
const formRules: { [key in keyof Proto.HdWROrderReq]?: FieldRule[] } = {
    FixedPrice: [{
        message: '请输入价格',
        validator: () => {
            return !!formData.FixedPrice
        }
    }],
    WRFactorTypeId: [{
        message: '请选择现货仓单',
        validator: () => {
            return !!selectedRow.value
        }
    }],
    OrderQty: [{
        message: '请输入数量',
        validator: (val) => {
            if (val) {
                const { qty = 0, freezerqty = 0 } = selectedRow.value ?? {}
                const available = qty - freezerqty // 可用数量
                if (props.buyorsell === BuyOrSell.Buy || val <= available) {
                    return true
                }
                return available ? '数量不能大于 ' + available : '可用数量不足'
            }
            return false
        }
    }],
}

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

// 提交挂牌
const onSubmit = () => {
    formData.BuyOrSell = props.buyorsell

    if (formData.BuyOrSell === BuyOrSell.Buy) {
        const { wrstandardid, deliverygoodsid, wrfactortypeid = '0' } = props.quote ?? {}
        formData.WRStandardID = wrstandardid
        formData.DeliveryGoodsID = deliverygoodsid
        formData.WRFactorTypeId = Long.fromString(wrfactortypeid)
    } else {
        const { wrstandardid, subnum, deliverygoodsid, ladingbillid = '0', wrfactortypeid = '0' } = selectedRow.value ?? {}
        formData.WRStandardID = wrstandardid
        formData.DeliveryGoodsID = deliverygoodsid
        formData.LadingBillId = Long.fromString(ladingbillid)
        formData.WRFactorTypeId = Long.fromString(wrfactortypeid)
        formData.SubNum = subnum
    }

    fullloading((hideLoading) => {
        listingSubmit().then(() => {
            hideLoading()
            dialog('挂牌提交成功。').then(() => closed())
        }).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>