<template>
    <el-dialog
        class="ba-operate-dialog"
        :close-on-click-modal="false"
        :model-value="['Add', 'Edit'].includes(baTable.form.operate!)"
        @close="baTable.toggleForm"
    >
        <template #header>
            <div class="title" v-drag="['.ba-operate-dialog', '.el-dialog__header']" v-zoom="'.ba-operate-dialog'">
                {{ baTable.form.operate ? t(baTable.form.operate) : '' }}
            </div>
        </template>

        <el-scrollbar v-loading="baTable.form.loading" class="ba-table-form-scrollbar">
            <div
                class="ba-operate-form"
                :class="'ba-' + baTable.form.operate + '-form'"
                :style="config.layout.shrink ? '' : 'width: calc(100% - ' + baTable.form.labelWidth! / 2 + 'px)'"
            >
                <el-form
                    v-if="!baTable.form.loading"
                    ref="formRef"
                    @submit.prevent=""
                    @keyup.enter="baTable.onSubmit(formRef)"
                    :model="baTable.form.items"
                    :label-position="config.layout.shrink ? 'top' : 'right'"
                    :label-width="baTable.form.labelWidth + 'px'"
                    :rules="rules"
                >
                    <!-- PENDING：两页审核流程（PHYSICAL 显示收货信息，其它类型只显示基本信息） -->
                    <template v-if="usePagedActions && page === 1">
                        <FormItem :label="t('mall.order.type')" type="string" v-model="baTable.form.items!.type" prop="type" :input-attr="{ disabled: true }" />
                        <FormItem :label="t('mall.order.status')" type="string" v-model="baTable.form.items!.status" prop="status" :input-attr="{ disabled: true }" />
                        <template v-if="isPhysical">
                            <FormItem
                                :label="t('mall.order.receiver_name')"
                                type="string"
                                v-model="baTable.form.items!.receiver_name"
                                prop="receiver_name"
                                :input-attr="{ disabled: true }"
                            />
                            <FormItem
                                :label="t('mall.order.receiver_phone')"
                                type="string"
                                v-model="baTable.form.items!.receiver_phone"
                                prop="receiver_phone"
                                :input-attr="{ disabled: true }"
                            />
                            <FormItem
                                :label="t('mall.order.receiver_address')"
                                type="string"
                                v-model="baTable.form.items!.receiver_address"
                                prop="receiver_address"
                                :input-attr="{ disabled: true }"
                            />
                        </template>
                    </template>

                    <template v-else-if="usePagedActions">
                        <template v-if="action === 'approveShip' && isPhysical">
                            <FormItem
                                :label="t('mall.order.shipping_company')"
                                type="string"
                                v-model="baTable.form.items!.shipping_company"
                                prop="shipping_company"
                                :placeholder="t('Please input field', { field: t('mall.order.shipping_company') })"
                            />
                            <FormItem
                                :label="t('mall.order.shipping_no')"
                                type="string"
                                v-model="baTable.form.items!.shipping_no"
                                prop="shipping_no"
                                :placeholder="t('Please input field', { field: t('mall.order.shipping_no') })"
                            />
                        </template>
                        <template v-else-if="action === 'reject'">
                            <FormItem
                                v-if="isPhysical"
                                :label="t('mall.order.reject_reason')"
                                type="textarea"
                                v-model="baTable.form.items!.reject_reason"
                                prop="reject_reason"
                                :input-attr="{ rows: 3 }"
                                @keyup.enter.stop=""
                                :placeholder="t('Please input field', { field: t('mall.order.reject_reason') })"
                            />
                            <el-alert v-else type="info" :closable="false" show-icon>
                                确认后将驳回该订单并退回积分（提现订单无需填写驳回原因）。
                            </el-alert>
                        </template>
                    </template>

                    <!-- 其它订单：保留常规可编辑表单 + 保存 -->
                    <template v-else>
                        <FormItem :label="t('mall.order.type')" type="string" v-model="baTable.form.items!.type" prop="type" :input-attr="{ disabled: true }" />
                        <FormItem
                            :label="t('mall.order.status')"
                            type="select"
                            v-model="baTable.form.items!.status"
                            prop="status"
                            :input-attr="{ content: { PENDING: t('mall.order.status PENDING'), COMPLETED: t('mall.order.status COMPLETED'), SHIPPED: t('mall.order.status SHIPPED'), REJECTED: t('mall.order.status REJECTED') } }"
                            :placeholder="t('Please select field', { field: t('mall.order.status') })"
                        />
                        <template v-if="isPhysical">
                            <FormItem
                                :label="t('mall.order.shipping_company')"
                                type="string"
                                v-model="baTable.form.items!.shipping_company"
                                prop="shipping_company"
                                :placeholder="t('Please input field', { field: t('mall.order.shipping_company') })"
                            />
                            <FormItem
                                :label="t('mall.order.shipping_no')"
                                type="string"
                                v-model="baTable.form.items!.shipping_no"
                                prop="shipping_no"
                                :placeholder="t('Please input field', { field: t('mall.order.shipping_no') })"
                            />
                            <FormItem
                                :label="t('mall.order.reject_reason')"
                                type="textarea"
                                v-model="baTable.form.items!.reject_reason"
                                prop="reject_reason"
                                :input-attr="{ rows: 3 }"
                                @keyup.enter.stop=""
                                :placeholder="t('Please input field', { field: t('mall.order.reject_reason') })"
                            />
                        </template>
                    </template>
                </el-form>
            </div>
        </el-scrollbar>

        <template #footer>
            <div :style="'width: calc(100% - ' + baTable.form.labelWidth! / 1.8 + 'px)'">
                <el-button @click="onCancel">{{ t('Cancel') }}</el-button>

                <template v-if="usePagedActions && page === 1">
                    <el-button v-if="canApprove" @click="onApprove" type="success">审核通过</el-button>
                    <el-button @click="goReject" type="danger">驳回</el-button>
                </template>

                <template v-else-if="usePagedActions">
                    <el-button @click="backToFirst">返回</el-button>
                    <el-button
                        v-if="action === 'approveShip'"
                        v-blur
                        :loading="submitting"
                        @click="submitShip"
                        type="success"
                    >
                        提交发货
                    </el-button>
                    <el-button v-if="action === 'reject'" v-blur :loading="submitting" @click="submitReject" type="danger">提交驳回</el-button>
                </template>

                <template v-else>
                    <el-button v-blur :loading="baTable.form.submitLoading" @click="baTable.onSubmit(formRef)" type="primary">
                        {{ baTable.form.operateIds && baTable.form.operateIds.length > 1 ? t('Save and edit next item') : t('Save') }}
                    </el-button>
                </template>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { computed, inject, ref, useTemplateRef, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { useConfig } from '/@/stores/config'
import baTableClass from '/@/utils/baTable'
import FormItem from '/@/components/formItem/index.vue'
import type { FormItemRule } from 'element-plus'
import { ElMessage } from 'element-plus'
import { buildValidatorData } from '/@/utils/validate'
import createAxios from '/@/utils/axios'

const config = useConfig()
const formRef = useTemplateRef('formRef')
const baTable = inject('baTable') as baTableClass
const { t } = useI18n()

const isEdit = computed(() => baTable.form.operate === 'Edit')
const isPending = computed(() => isEdit.value && baTable.form.items?.status === 'PENDING')
const needsReviewType = computed(() => ['PHYSICAL', 'WITHDRAW'].includes(String(baTable.form.items?.type || '')))
const isPhysical = computed(() => baTable.form.items?.type === 'PHYSICAL')
const canApprove = computed(() => isPending.value && needsReviewType.value)
const usePagedActions = computed(() => isPending.value && needsReviewType.value)

const page = ref<1 | 2>(1)
const action = ref<'approveShip' | 'reject' | null>(null)
const submitting = ref(false)

const resetPager = () => {
    page.value = 1
    action.value = null
    submitting.value = false
}

watch(
    () => baTable.form.operate,
    () => {
        resetPager()
    }
)

const onCancel = () => {
    resetPager()
    baTable.toggleForm()
}

const backToFirst = () => {
    page.value = 1
    action.value = null
}

const onApprove = async () => {
    if (!isPending.value) {
        return
    }
    if (isPhysical.value) {
        page.value = 2
        action.value = 'approveShip'
        return
    }
    const id = baTable.form.items?.id
    if (!id) {
        return
    }
    submitting.value = true
    try {
        await createAxios({ url: '/admin/mall.Order/approve', method: 'post', data: { id } }, { showSuccessMessage: true })
        resetPager()
        baTable.toggleForm()
        await baTable.getData()
    } finally {
        submitting.value = false
    }
}

const goReject = () => {
    page.value = 2
    action.value = 'reject'
}

const submitShip = async () => {
    const id = baTable.form.items?.id
    const shippingCompany = (baTable.form.items?.shipping_company || '').toString().trim()
    const shippingNo = (baTable.form.items?.shipping_no || '').toString().trim()
    if (!id || shippingCompany === '' || shippingNo === '') {
        ElMessage.error('请填写物流公司与物流单号')
        return
    }
    submitting.value = true
    try {
        await createAxios(
            { url: '/admin/mall.Order/ship', method: 'post', data: { id, shipping_company: shippingCompany, shipping_no: shippingNo } },
            { showSuccessMessage: true }
        )
        resetPager()
        baTable.toggleForm()
        await baTable.getData()
    } finally {
        submitting.value = false
    }
}

const submitReject = async () => {
    const id = baTable.form.items?.id
    const rejectReason = (baTable.form.items?.reject_reason || '').toString().trim()
    if (!id) {
        return
    }
    if (isPhysical.value && rejectReason === '') {
        ElMessage.error('请填写驳回原因')
        return
    }
    submitting.value = true
    try {
        await createAxios(
            { url: '/admin/mall.Order/reject', method: 'post', data: { id, reject_reason: rejectReason } },
            { showSuccessMessage: true }
        )
        resetPager()
        baTable.toggleForm()
        await baTable.getData()
    } finally {
        submitting.value = false
    }
}

const rules = computed<Partial<Record<string, FormItemRule[]>>>(() => {
    if (!isPhysical.value) {
        return {}
    }
    return {
        shipping_company: [buildValidatorData({ name: 'required', title: t('mall.order.shipping_company') })],
        shipping_no: [buildValidatorData({ name: 'required', title: t('mall.order.shipping_no') })],
        reject_reason: [buildValidatorData({ name: 'required', title: t('mall.order.reject_reason') })],
    }
})
</script>

<style scoped lang="scss"></style>

