<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" :options="details.deliverymodes"
                            :optionProps="{ label: 'enumdicname', value: 'enumitemname' }"
                            @confirm="formRef?.validate('THJDeliveryMode')" />
                    </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 label="到期日期" v-if="selectedDate?.presaleapplyid">
                    <template #input>
                        <span>{{ selectedDate.enddate }}</span>
                    </template>
                </Field>
                <Field name="DepositID" label="支付方式" :rules="formRules.DepositID" is-link
                    v-if="selectedDate?.presaleapplyid">
                    <template #input>
                        <app-select :options="presaleApplyDeposits" @confirm="onDepositChange" />
                    </template>
                </Field>
                <Field label="参考价" v-if="selectedDate">
                    <template #input>
                        <span>{{ `${selectedDate.unitprice ?? 0.00}元/${getGoodsUnitName(goodsinfo.unitid)}` }}</span>
                    </template>
                </Field>
                <Field label="剩余数量" v-if="selectedDate">
                    <template #input>
                        <span>{{ maxQty.toString() + getGoodsUnitName(goodsinfo.unitid) }}</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="必填" />
                            </div>
                        </div>
                    </template>
                </Field>
                <Field label="预付款(含定金)" v-if="selectedDate">
                    <template #input>
                        <span style="color:#999">{{ `${totalAmount}(≤${avaiableMoney.toFixed(2)}元)` }}</span>
                    </template>
                </Field>
                <Field label="收货信息" name="addressInfo" :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__btnbar">
            <Button type="primary" size="small" @click="formRef?.submit" round>采购下单</Button>
        </div>
        <div class="goods-details__content" v-if="chartData.price.length">
            <h2>历史价格走势</h2>
            <component :is="componentMap.get('chart')" :loading="loading" :data-list="chartData" />
        </div>
        <div class="goods-details__content">
            <h2>商品详情</h2>
            <template v-for="(url, index) in goodsImages" :key="index">
                <img :src="url" alt="" />
            </template>
        </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, showSuccessToast, showFailToast, FieldRule } from 'vant'
import { fullloading, dialog } from '@/utils/vant'
import { getFileUrl, parsePercent } from '@/filters'
import { getGoodsUnitName } from '@/constants/unit'
import { useComponent } from '@/hooks/component'
import { useNavigation } from '@/hooks/navigation'
import { accountStore, } from '@/stores'
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 { avaiableMoney } = accountStore.$mapGetters()
const { componentRef, componentId, openComponent, closeComponent } = useComponent()
const { router, getQueryStringToNumber } = useNavigation()

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

const { loading, details, customDeposits, chartData, getWrstandardDetails, getTHJinvesotrdeposit } = 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) => getFileUrl(path))
})

// 定金比例列表，商品定金比例和个性化定金比例进行合并
const presaleApplyDeposits = computed(() => {
    const deposits = details.value.presaleapplydeposits
    const { presaleapplyid, remainqty = 0 } = selectedDate.value ?? {}

    const result = deposits.filter((e) => e.presaleapplyid === presaleapplyid).map((e) => ({
        id: e.depositid,
        label: parsePercent(e.depositrate),
        value: e.depositrate,
        qty: remainqty,
        type: 1, // 定金类型
    }))

    customDeposits.value.forEach((e) => {
        result.push({
            id: '0',
            label: parsePercent(e.depositrate),
            value: e.depositrate,
            qty: e.qty,
            type: 2, // 定金类型
        })
    })

    return result.sort((a, b) => b.value - a.value)
})

// 计算可用数量
const maxQty = computed(() => {
    const { remainqty = 0 } = selectedDate.value ?? {}
    const { type, qty = 0 } = presaleApplyDeposits.value.find((e) => e.value === formData.value.DepositRate) ?? {}
    if (type === 2) {
        return Math.min(qty, remainqty)
    }
    return remainqty
})

// 计算总金额
const totalAmount = computed(() => {
    const { Qty = 0, DepositRate = 0 } = formData.value
    const { unitprice = 0 } = selectedDate.value ?? {}
    return (unitprice * DepositRate * Qty).toFixed(2)
})

// 是否显示收货信息
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 && Number(val)) {
                if (Number(val) <= maxQty.value) {
                    return true
                }
                return `采购数量不能大于 ${maxQty.value} ${getGoodsUnitName(goodsinfo.value.unitid)}`
            }
            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')
    getTHJinvesotrdeposit(value)
}

// 切换支付方式
const onDepositChange = (value: number, index: number) => {
    const item = presaleApplyDeposits.value[index]
    formData.value.DepositID = Long.fromString(item.id)
    formData.value.DepositType = item.type
    formData.value.DepositRate = item.value
    formRef.value?.validate('DepositID')

    if (formData.value.Qty) {
        if (formData.value.Qty > maxQty.value) {
            formData.value.Qty = maxQty.value
        }
        formRef.value?.validate('Qty')
    }
}

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

const onSubmit = () => {
    dialog({
        message: '确认立即下单吗？',
        showCancelButton: true
    }).then(() => {
        fullloading(() => {
            formSubmit().then(() => {
                showSuccessToast('下单成功')
                router.replace({ name: 'my-order' })
            }).catch((err) => {
                showFailToast(err)
            })
        })
    })
}

getWrstandardDetails()
</script>

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