<template>
    <app-view class="goods-details">
        <template #header>
            <app-navbar title="采购详情" />
        </template>
        <Form ref="formRef" class="goods-details__form" @submit="onSubmit">
            <CellGroup>
                <app-select v-model="formData.THJDeliveryMode" name="THJDeliveryMode" label="交割方式"
                    :rules="formRules.THJDeliveryMode" :options="details.deliverymodes"
                    :optionProps="{ label: 'enumdicname', value: 'enumitemname' }" />
                <Field label="交割月份" name="PresaleApplyID" :rules="formRules.PresaleApplyID">
                    <template #input>
                        <div class="form-month">
                            <app-select placeholder="开始月份" :options="deliveryMonths" :is-link="false"
                                @confirm="onMonthChange" />
                            <app-select placeholder="结束日期" :options="deliveryDays"
                                :optionProps="{ label: 'enddate', value: 'presaleapplyid' }" :is-link="false"
                                @confirm="onDayChange" />
                        </div>
                    </template>
                </Field>
                <app-select v-model="formData.DepositID" name="DepositID" label="支付方式" :rules="formRules.DepositID"
                    :options="presaleApplyDeposits" v-if="selectedDate?.presaleapplyid" />
                <Field v-model="formData.Qty" name="Qty" type="digit" label="采购数量" :rules="formRules.Qty">
                    <template #input>
                        <div class="form-qty">
                            <div class="form-qty__input">
                                <input type="number" v-model="formData.Qty" placeholder="必填" />
                                <span>≤{{ selectedDate?.remainqty ?? 0
                                }}{{ getGoodsUnitName(details.goodsinfo?.unitid) }}</span>
                            </div>
                            <div class="form-qty__label">
                                <span>定金{{ deposit }}元</span>
                            </div>
                        </div>
                    </template>
                </Field>
                <Field label="收货信息" :rules="formRules.addressInfo" @click="openComponent('address')" is-link
                    v-if="showAddressInfo">
                    <template #input>
                        <div class="form-address">
                            <template v-if="validatorAddressInfo">
                                <span>联系人：{{ formData.ContactName }}</span>
                                <span>联系方式：{{ formData.ContactInfo }}</span>
                                <span v-if="formData.THJDeliveryMode === 3">目的地：{{ formData.DesAddress }}</span>
                                <span v-if="formData.ReceiptInfo">发票信息：{{ formData.ReceiptInfo }}</span>
                            </template>
                            <template v-else>
                                <span class="form-address__placeholder">必填</span>
                            </template>
                        </div>
                    </template>
                </Field>
            </CellGroup>
        </Form>
        <div class="goods-details__content">
            <div class="">
                <Button type="primary" @click="formRef?.submit" round block>采购下单</Button>
            </div>
            <div class="" v-if="selectedDate">
                <span>参考价(元/{{ getGoodsUnitName(details.goodsinfo?.unitid) }})</span>
                <span>{{ selectedDate.unitprice }}</span>
            </div>
            <Divider>历史价格走势</Divider>
            <div class="">
                走势图
            </div>
            <Divider>商品详情</Divider>
            <div class="">
                <template v-for="(url, index) in goodsImages" :key="index">
                    <img :src="url" alt="" />
                </template>
            </div>
        </div>
        <component ref="componentRef" :is="componentMap.get(componentId)" v-bind="{ formData }" @updated="updateForm"
            @closed="closeComponent" v-if="componentId" />
    </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 } from '@/filters'
import { getGoodsUnitName } from '@/constants/unit'
import { useComponent } from '@/hooks/component'
import { useNavigation } from '@/hooks/navigation'
import { useWrstandardDetails } from '@/business/goods'
import { usePurchaseOrderDesting } from '@/business/trade'
import AppSelect from '@mobile/components/base/select/index.vue'
import Long from 'long'

const componentMap = new Map<string, unknown>([
    ['address', defineAsyncComponent(() => import('./components/address/index.vue'))],
])

const { componentRef, componentId, openComponent, closeComponent, closeComponentEach } = useComponent()
const { getQueryStringToNumber, beforeRouteLeave } = useNavigation()

const wrstandardid = getQueryStringToNumber('wrstandardid')
const formRef = shallowRef<FormInstance>()

const { details, getWrstandardDetails } = useWrstandardDetails(wrstandardid)
const { formData, formSubmit } = usePurchaseOrderDesting()

// 交割日期列表
const deliveryDays = shallowRef<Model.THJWrstandardDetailRsp['deliverymonth']>([])
// 当前选中的交割日期
const selectedDate = shallowRef<Model.THJWrstandardDetailRsp['deliverymonth'][number]>()

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

// 交割月份列表
const deliveryMonths = computed(() => {
    const months = details.value.deliverymonth ?? []
    const monthMap = new Map<string, { label: string, value: string; }>()
    months.forEach(({ endmonth }) => {
        if (!monthMap.has(endmonth)) {
            monthMap.set(endmonth, {
                label: endmonth,
                value: endmonth,
            })
        }
    })
    return [...monthMap.values()]
})

// 预售申请列表
const presaleApplyDeposits = computed(() => {
    const deposits = details.value.presaleapplydeposits ?? []
    const presaleApplyId = selectedDate.value?.presaleapplyid

    return deposits.filter((e) => e.presaleapplyid === presaleApplyId).map(({ depositid, depositrate }) => ({
        label: `${depositrate * 100}%`,
        value: depositid
    }))
})

// 计算定价
const deposit = computed(() => {
    const { Qty = 0, DepositID } = formData.value
    const { presaleapplydeposits } = details.value
    const { unitprice = 0 } = selectedDate.value ?? {}
    const apply = presaleapplydeposits?.find((e) => e.depositid === DepositID) // 选中的支付方式

    if (apply) {
        return unitprice * apply.depositrate * Qty
    }
    return 0
})

// 是否显示收货信息
const showAddressInfo = computed(() => {
    const { THJDeliveryMode } = formData.value
    return THJDeliveryMode === 2 || THJDeliveryMode === 3
})

// 验证收货信息
const validatorAddressInfo = computed(() => {
    const { THJDeliveryMode, ContactName, ContactInfo, DesAddress } = formData.value
    switch (THJDeliveryMode) {
        case 2: {
            if (ContactName && ContactInfo) return true
            return false
        }
        case 3: {
            if (ContactName && ContactInfo && DesAddress) return true
            return false
        }
    }
    return true
})

// 表单验证规则
const formRules: { [key in keyof Proto.SpotPresaleDestingOrderReq | 'addressInfo']?: FieldRule[] } = {
    THJDeliveryMode: [{
        message: '请选择交割方式',
        validator: () => {
            return !!formData.value.THJDeliveryMode
        }
    }],
    PresaleApplyID: [
        {
            message: '请选择交割日期',
            validator: () => {
                return !!formData.value.PresaleApplyID
            }
        }
    ],
    DepositID: [{
        message: '请选择支付方式',
        validator: () => {
            return !!formData.value.DepositID
        }
    }],
    Qty: [{
        message: '请输入采购数量',
        validator: (val) => {
            if (val) {
                const qty = Number(val)
                const { remainqty = 0 } = selectedDate.value ?? {}
                if (qty > 0 && qty <= remainqty) {
                    return true
                }
                return '采购数量不正确'
            }
            return false
        }
    }],
    addressInfo: [{
        message: '请输入收货信息',
        validator: () => {
            return validatorAddressInfo.value
        }
    }],
}

// 切换交割月份
const onMonthChange = (value: string) => {
    const months = details.value.deliverymonth ?? []
    deliveryDays.value = months.filter((e) => e.endmonth === value) // 重新过滤交割日期列表
    selectedDate.value = undefined // 清除选中的交割日期
    formData.value.PresaleApplyID = undefined
    formRef.value?.validate('PresaleApplyID')
}

// 切换交割日期
const onDayChange = (value: string) => {
    const months = details.value.deliverymonth ?? []
    selectedDate.value = months.find((e) => e.presaleapplyid === value)
    formData.value.PresaleApplyID = Long.fromString(value)
    formData.value.DepositID = undefined
    formRef.value?.validate('PresaleApplyID')
}

// 更新表单数据
const updateForm = (formValue: Proto.SpotPresaleDestingOrderReq) => {
    formData.value = formValue
}

const onSubmit = () => {
    fullloading(() => {
        formSubmit().then(() => {
            Toast.success('下单成功')
        }).catch((err) => {
            Toast.fail(err)
        })
    })
}

getWrstandardDetails()
beforeRouteLeave(() => closeComponentEach())
</script>

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