<template>
    <app-modal direction="right" height="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="formSubmit">
                <CellGroup inset>
                    <Field label="商品" readonly>
                        <template #input>
                            {{ selectedRow.wrstandardname }}
                        </template>
                    </Field>
                    <Field label="仓库" readonly>
                        <template #input>
                            {{ selectedRow.warehousename }}
                        </template>
                    </Field>
                    <Field name="OrderQty" label="提货数量" v-model="orderQty" placeholder="请输入提货数量"
                        :rules="formRules.orderQty" />

                    <Field label="提货方式" readonly>
                        <template #input>
                            <RadioGroup v-model="checked" direction="horizontal">
                                <Radio :name="3">代办运输</Radio>
                                <Radio :name="2">自提</Radio>
                            </RadioGroup>
                        </template>
                    </Field>
                    <Field name="ContractName" label="联系人" v-model="formData.ContactName" placeholder="请输入联系人"
                        :rules="formRules.ContactName">
                        <template #button>
                            <Button size="normal" icon="add-o" @click="showContact = true" />
                        </template>
                    </Field>
                    <Field name="ContactNum" label="联系方式" v-model="formData.ContactNum" placeholder="请输入联系方式"
                        :rules="formRules.ContactNum" />
                    <Field name="Address" label="目的地地址" v-model="formData.Address" placeholder="请输入目的地地址"
                        :rules="formRules.Address" v-if="checked === 3" />
                    <Field name="AppointmentRemark" label="发票信息" rows="10" autosize v-model="formData.AppointmentRemark"
                        placeholder="请填入发票信息" :rules="formRules.AppointmentRemark">
                        <template #button>
                            <Button size="normal" icon="add-o" @click="showReceipt = true" />
                        </template>
                    </Field>
                </CellGroup>
            </Form>
            <template #footer>
                <div class="g-form__footer">
                    <Button type="primary" round block @click="formRef?.submit()">提货</Button>
                </div>
            </template>
        </app-view>
        <app-contact v-model:show="showContact" @change="contactChange" />
        <app-receipt v-model:show="showReceipt" @change="receiptChange" />
    </app-modal>
</template>

<script lang="ts" setup>
import { shallowRef, PropType } from 'vue'
import { CellGroup, Button, Field, Form, FormInstance, FieldRule, showFailToast, Radio, RadioGroup } from 'vant'
import { useWrOutInApply } from "@/business/trade";
import { fullloading, dialog } from '@/utils/vant'
import { getReceiptTypeName } from '@/constants/receipt'
import { validateRules } from '@/constants/regex'
import AppModal from '@/components/base/modal/index.vue'
import AppContact from '@mobile/components/modules/contact/index.vue'
import AppReceipt from '@mobile/components/modules/receipt/index.vue'

const props = defineProps({
    selectedRow: {
        type: Object as PropType<Model.HoldLBRsp>,
        required: true
    }
})

const formRef = shallowRef<FormInstance>()
const showContact = shallowRef(false) // 显示联系人选择列表
const showReceipt = shallowRef(false) // 显示发票选择列表
const showModal = shallowRef(true)
const refresh = shallowRef(false) // 是否刷新父组件数据

const { formData, applySubmit, orderQty, checked } = useWrOutInApply(props.selectedRow)

// 表单验证规则
const formRules: { [key in keyof Proto.WROutApplyReq | 'orderQty']?: FieldRule[] } = {
    orderQty: [{
        required: true,
        message: '请输入提货数量',
    }],
    ContactName: [{
        required: true,
        message: '请输入联系人',
    }],
    ContactNum: [{
        required: true,
        message: '请输入联系方式',
        validator: (val) => {
            if (validateRules.phone.validate(val)) {
                return true
            }
            return validateRules.phone.message
        }
    }],
    Address: [{
        required: checked.value === 3,
        message: '请输入目的地地址',
    }],
    AppointmentRemark: [{
        required: true,
        message: '请输入发票信息',
    }],
}

// 选择联系信息
const contactChange = (item: Model.UserReceiveInfoRsp) => {
    formData.ContactName = item.receivername
    formData.ContactNum = item.phonenum

    if (checked.value === 3) {
        formData.Address = [item.provincename, item.cityname, item.districtname, item.address].join(' ')
    } else {
        formData.Address = ''
    }
}

// 选择发票信息
const receiptChange = (item: Model.WrUserReceiptInfoRsp) => {
    formData.AppointmentRemark = ''
    Object.entries(item).forEach(([key, value]) => {
        if (value !== '') {
            switch (key) {
                case 'receipttype': {
                    formData.AppointmentRemark += '发票类型:' + getReceiptTypeName(Number(value)) + '\n'
                    break
                }
                case 'username': {
                    formData.AppointmentRemark += '发票抬头:' + value + '\n'
                    break
                }
                case 'taxpayerid': {
                    formData.AppointmentRemark += '税号:' + value + '\n'
                    break
                }
                case 'receiptbank': {
                    formData.AppointmentRemark += '开户银行:' + value + '\n'
                    break
                }
                case 'receiptaccount': {
                    formData.AppointmentRemark += '银行账号:' + value + '\n'
                    break
                }
                case 'address': {
                    formData.AppointmentRemark += '企业地址:' + value + '\n'
                    break
                }
                case 'contactinfo': {
                    formData.AppointmentRemark += '企业电话:' + value + '\n'
                    break
                }
                case 'email': {
                    formData.AppointmentRemark += '邮箱:' + value + '\n'
                    break
                }
            }
        }
    })
}

const formSubmit = () => {
    fullloading((hideLoading) => {
        applySubmit().then(() => {
            hideLoading()
            dialog('提货申请提交成功。').then(() => {
                closed(true)
            })
        }).catch((err) => {
            showFailToast(err)
        })
    })
}

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

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