<!-- 交收操作 -->
<template>
    <app-modal direction="right-top" height="100%" width="100%" v-model:show="showModal" :refresh="refresh">
        <app-view class="g-form">
            <template #header>
                <app-navbar :title="$t('operation.delivery')" @back="closed" />
            </template>
            <Form ref="formRef" class="g-form__container" @submit="onSubmit">
                <CellGroup :title="$t('position.order.subtitle')" inset v-if="$slots.header">
                    <slot name="header"></slot>
                </CellGroup>
                <CellGroup :title="$t('position.order.subtitle2')" inset>
                    <Field name="wrstandardname" label="点选仓单" :placeholder="$t('common.choice')" input-align="right"
                        :rules="formRules.wrstandardname" v-model="checkedRow.wrstandardname"
                        @click="showWarehouseReceipt = true" is-link readonly />
                    <template v-if="checkedRow.deliverygoodsid">
                        <Cell title="持有人" :value="checkedRow.username" />
                        <Cell title="仓库" :value="checkedRow.warehousename" />
                        <Cell title="数量" :value="checkedRow.avalidqty + (deliveryRelation?.enumdicname ?? '')" />
                    </template>
                </CellGroup>
                <CellGroup inset>
                    <Cell title="可交收数量" :value="(total * qtyStep) + (deliveryRelation?.enumdicname ?? '')" />
                    <Field name="DeliveryQty" type="digit" :rules="formRules.DeliveryQty" label="交收数量">
                        <template #input>
                            <Stepper v-model="formData.DeliveryQty" theme="round" button-size="22" :min="0"
                                :max="maxQty" :step="qtyStep" integer />
                        </template>
                    </Field>
                    <Cell title="所需合约量" :value="formData.DeliveryQty ? (formData.DeliveryQty / qtyStep) : 0" />
                    <Cell title="升贴水" :value="discount.toFixed(2)" />
                    <slot name="form" :discount="discount" :qty="formData.DeliveryQty ?? 0"></slot>
                </CellGroup>
            </Form>
            <template #footer>
                <div class="g-form__footer inset">
                    <Button block square type="danger" @click="formRef?.submit">{{ $t('operation.delivery') }}</Button>
                </div>
            </template>
        </app-view>
        <component :is="WarehouseReceipt" v-model:show="showWarehouseReceipt" :goods-id="goodsId" @change="onChange" />
    </app-modal>
</template>

<script lang="ts" setup>
import { reactive, shallowRef, computed, defineAsyncComponent, onMounted } from 'vue'
import { v4 } from 'uuid'
import { CellGroup, Cell, Button, FieldRule, Form, Field, Stepper, FormInstance } from 'vant'
import { handleRequestBigNumber } from '@/filters'
import { dialog, fullloading } from '@/utils/vant'
import { useRequest } from '@/hooks/request'
import { ClientType } from '@/constants/client'
import { deliveryOrder } from '@/services/api/trade'
import { queryDeliveryRelation } from '@/services/api/goods'
import { useAccountStore, useFuturesStore } from '@/stores'
import moment from 'moment'
import AppModal from '@/components/base/modal/index.vue'

const props = defineProps({
    goodsId: {
        type: Number,
        required: true,
    },
    total: {
        type: Number,
        required: true,
    }
})

const WarehouseReceipt = defineAsyncComponent(() => import('./warehouse-receipt.vue'))

const accountStore = useAccountStore()
const futuresStore = useFuturesStore()
const showModal = shallowRef(true)
const refresh = shallowRef(false) // 是否刷新父组件数据
const formRef = shallowRef<FormInstance>()
const checkedRow = shallowRef<Partial<Model.WrDeliveryAvalidHoldLBRsp>>({}) //选中的点选仓单
const showWarehouseReceipt = shallowRef(false)
const quote = futuresStore.getGoodsQuote(props.goodsId) // 商品实时盘面

const formData = reactive<Partial<Proto.DeliveryOrderReq>>({
    ClientType: ClientType.Web,
    AccountID: accountStore.currentAccountId,
    XGoodsID: props.goodsId
})

// 查询商品交割关系
const { data: deliveryRelation } = useRequest(queryDeliveryRelation, {
    params: {
        goodsid: props.goodsId,
    },
    onSuccess: (res) => {
        deliveryRelation.value = res.data[0]
    }
})

// 数量步长
const qtyStep = computed(() => {
    const { agreeunit = 0 } = quote.value ?? {}
    const { mindeliveryqty = 0, rratio1 = 0, rratio2 = 0 } = deliveryRelation.value ?? {}
    if (rratio2 && rratio1) {
        return agreeunit * mindeliveryqty * (rratio2 / rratio1)
    }
    return 0
})

// 可选最大交收数量
const maxQty = computed(() => {
    const avalidqty = checkedRow.value.avalidqty ?? 0
    const enableqty = props.total * qtyStep.value
    return avalidqty > enableqty ? enableqty : avalidqty
})

// 升贴水
const discount = computed(() => (checkedRow.value.pricemove ?? 0) * (formData.DeliveryQty ?? 0))

// 表单验证规则
const formRules: { [key: string]: FieldRule[] } = {
    wrstandardname: [{
        message: '请选择点选仓单',
        validator: () => {
            return !!checkedRow.value.deliverygoodsid
        }
    }],
    DeliveryQty: [{
        validator: () => {
            if (formData.DeliveryQty) {
                return formData.DeliveryQty % qtyStep.value === 0 ? true : '数量只能是' + qtyStep.value + '的整数倍'
            }
            return '请输入交收数量'
        }
    }],
}

// 选择现货仓单
const onChange = (item: Model.WrDeliveryAvalidHoldLBRsp) => {
    checkedRow.value = item
    showWarehouseReceipt.value = false
}

const onSubmit = () => {
    dialog({
        message: '确认要交收吗？',
        showCancelButton: true,
    }).then(() => {
        fullloading((hideLoading) => {
            const item = checkedRow.value
            formData.DeliveryGoodsID = item.deliverygoodsid
            formData.XQty = (formData.DeliveryQty ?? 0) / qtyStep.value
            formData.DeliveryOrderDetail = {
                AccountID: item.accountid, // 对手方账号
                Qty: formData.DeliveryQty, // 点选数量
                LadingBillID: handleRequestBigNumber(item.ladingbillid ?? '0'),// 提单ID
                SubNum: item.subnum, // 提单子单号
                WRFactorTypeID: handleRequestBigNumber(item.wrfactortypeid ?? '0'), // 仓单要素类型ID
                WarehouseID: item.warehouseid
            }
            formData.ClientSerialNo = v4()
            formData.ClientOrderTime = moment(new Date()).format('YYYY-MM-DD HH:mm:ss')

            deliveryOrder({
                data: formData
            }).then(() => {
                hideLoading('交收成功', 'success')
                closed(true)
            }).catch((err) => {
                hideLoading(err, 'fail')
            })
        })
    })
}

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

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

onMounted(() => {
    if (!quote.value) {
        console.warn(`商品 ${props.goodsId} 不存在`)
    }
})
</script>