<template>
    <app-view class="goods-details">
        <template #header>
            <app-navbar title="采购详情" />
        </template>
        <Form ref="formRef" class="goods-details__form" @submit="onSubmit">
            <CellGroup>
                <Field name="THJDeliveryMode" label="交割方式" :rules="formRules.THJDeliveryMode" is-link>
                    <template #input>
                        <app-select v-model="formData.THJDeliveryMode" placeholder="请选择"
                            :options="details.deliverymodes"
                            :optionProps="{ label: 'enumdicname', value: 'enumitemname' }" />
                    </template>
                </Field>
                <Field name="PresaleApplyID" label="交割月份" :rules="formRules.PresaleApplyID" is-link>
                    <template #input>
                        <app-select :options="details.deliverymonth"
                            :optionProps="{ label: 'endmonth', value: 'presaleapplyid' }" @confirm="onMonthChange" />
                    </template>
                </Field>
                <Field name="DepositID" label="支付方式" :rules="formRules.DepositID" is-link
                    v-if="selectedDate?.presaleapplyid">
                    <template #input>
                        <app-select v-model="formData.DepositID" placeholder="请选择" :options="presaleApplyDeposits" />
                    </template>
                </Field>
                <Field label="交割日期" v-if="selectedDate?.presaleapplyid">
                    <template #input>
                        <span>{{ selectedDate.enddate }}</span>
                    </template>
                </Field>
                <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 v-if="selectedDate">≤{{ selectedDate.remainqty }}{{
                                        getGoodsUnitName(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="submitbar">
                <Button type="primary" @click="formRef?.submit" round block>采购下单</Button>
            </div>
            <div class="titlebar" v-if="selectedDate">
                <span>参考价(元/{{ getGoodsUnitName(goodsinfo.unitid) }})</span>
                <span>{{ selectedDate.unitprice ?? 0.00 }}</span>
            </div>
            <template v-if="chartData.price.length">
                <Divider>历史价格走势</Divider>
                <div class="chart">
                    <component :is="componentMap.get('chart')" :loading="loading" :data-list="chartData" />
                </div>
            </template>
            <Divider>商品详情</Divider>
            <div class="gallery">
                <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'))],
    ['chart', defineAsyncComponent(() => import('@mobile/components/modules/echarts-line/index.vue'))],
])

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

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

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

// 当前选中的交割日期
const selectedDate = shallowRef<Model.THJWrstandardDetailRsp['deliverymonth'][number]>()
// 商品信息
const goodsinfo = computed<Partial<Model.THJWrstandardDetailRsp['goodsinfo']>>(() => details.value.goodsinfo ?? {})

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


// 预售申请列表
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).toFixed(2)
    }
    return '0.00'
})

// 是否显示收货信息
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 ?? []
    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('下单成功')
            router.replace({ name: 'my-order' })
        }).catch((err) => {
            Toast.fail(err)
        })
    })
}

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

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