<!-- 交收操作 -->
<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="交收" @back="closed" />
            </template>
            <Form ref="formRef" class="g-form__container" @submit="onSubmit">
                <CellGroup title="持仓信息" inset v-if="$slots.header">
                    <slot name="header"></slot>
                </CellGroup>
                <CellGroup title="交收信息" inset>
                    <Field name="wrstandardname" label="点选仓单" placeholder="请选择" :rules="formRules.wrstandardname"
                        v-model="checkedRow.wrstandardname" @click="showWarehouseReceipt = true" is-link readonly />
                    <template v-if="checkedRow.deliverygoodsid">
                        <Field label="持有人" v-model="checkedRow.username" readonly />
                        <Field label="仓库" v-model="checkedRow.warehousename" readonly />
                        <Field label="数量" v-model="checkedRow.avalidqty" readonly />
                    </template>
                </CellGroup>
                <CellGroup inset>
                    <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"
                                integer />
                        </template>
                    </Field>
                    <Field label="升贴水">
                        <template #input>
                            {{ discount.toFixed(2) }}
                        </template>
                    </Field>
                    <slot name="form" :discount="discount" :qty="formData.DeliveryQty ?? 0"></slot>
                </CellGroup>
            </Form>
            <template #footer>
                <Button block square type="danger" @click="formRef?.submit">提交</Button>
            </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 } from 'vue'
import { v4 } from 'uuid'
import { CellGroup, Button, FieldRule, Form, Field, Stepper, FormInstance } from 'vant'
import { handleRequestBigNumber } from '@/filters'
import { dialog, fullloading } from '@/utils/vant'
import { ClientType } from '@/constants/client'
import { deliveryOrder } from '@/services/api/trade'
import { useAccountStore } 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 showModal = shallowRef(true)
const refresh = shallowRef(false) // 是否刷新父组件数据
const formRef = shallowRef<FormInstance>()
const checkedRow = shallowRef<Partial<Model.WrDeliveryAvalidHoldLBRsp>>({}) //选中的点选仓单
const showWarehouseReceipt = shallowRef(false)

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

// 可选最大交收数量
const maxQty = computed(() => {
    const avalidqty = checkedRow.value.avalidqty ?? 0
    const enableqty = props.total
    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: [{
        message: '请输入交收数量',
        validator: () => {
            return !!formData.DeliveryQty
        }
    }],
}

// 选择现货仓单
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
            formData.DeliveryOrderDetail = {
                AccountID: item.accountid, // 对手方账号
                Qty: formData.DeliveryQty, // 点选数量
                LadingBillID: item.ladingbillid,// 提单ID
                SubNum: item.subnum, // 提单子单号
                WRFactorTypeID: handleRequestBigNumber(item.wrfactortypeid ?? '0'), // 仓单要素类型ID
            }
            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,
})
</script>