<!-- 编辑弹窗 -->
<template>
    <ele-modal
        form
        :width="960"
        v-model="visible"
        title="售后补款"
        @open="handleOpen"
    >
        <el-row :gutter="12" class="common-row">
            <el-col :span="12"
                >书籍总数：{{ orderData.totalNum || 0 }}本</el-col
            >
            <el-col :span="12">不良数量：{{ orderData.badNum || 0 }}本</el-col>
            <el-col :span="12"
                >预估书款：{{ orderData.expectMoney || 0 }}元</el-col
            >
            <el-col :span="12"
                >预估运费：{{ orderData.expressMoney || 0 }}元</el-col
            >
            <el-col :span="12"
                >审核书款：{{ orderData.finalMoney || 0 }}元</el-col
            >
            <el-col :span="12"
                >运费补贴：{{ orderData.expressSubsidy || 0 }}元</el-col
            >
        </el-row>

        <el-form
            ref="formRef"
            :model="form"
            :rules="rules"
            label-width="80px"
            @submit.prevent=""
        >
            <el-form-item label="补款类型" prop="type">
                <el-radio-group v-model="form.type">
                    <el-radio label="1">书籍补款</el-radio>
                    <el-radio label="2">运费补款</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="补款金额" prop="money">
                <el-input-number
                    v-model="form.money"
                    :controls="false"
                    :max="orderData.canBackMoney"
                    :min="0"
                    :precision="2"
                    placeholder="补款金额"
                />
                <el-text style="margin: 0 16px 0 5px">元</el-text>
                <el-text size="small" type="info">
                    剩余可补款金额：<span style="color: red"
                        >{{ orderData.canBackMoney }}元</span
                    >
                    书籍补款金额≤预估金额-审核金额-理赔金额。大于0，可精确到小数点后两位。</el-text
                >
            </el-form-item>
            <el-form-item label="补款备注" prop="reason">
                <el-input
                    :rows="4"
                    type="textarea"
                    v-model="form.reason"
                    placeholder="请输入补款备注"
                />
            </el-form-item>
            <el-form-item label="补款记录" prop="records">
                <ele-data-table
                    row-key="id"
                    :columns="columns"
                    :data="orderData.backVoList"
                />
            </el-form-item>
        </el-form>

        <template #footer>
            <el-button @click="handleCancel">关闭</el-button>
            <el-button type="primary" @click="handleSubmit">确定</el-button>
        </template>
    </ele-modal>
</template>

<script setup>
    import { ref, reactive, nextTick, getCurrentInstance } from 'vue';
    import { EleMessage } from 'ele-admin-plus/es';

    const { proxy } = getCurrentInstance();
    const emit = defineEmits(['success']);

    /** 弹窗是否打开 */
    const visible = defineModel({ type: Boolean });

    /** 表单引用 */
    const formRef = ref();

    /** 订单数据 */
    const orderData = ref({
        orderId: null,
        totalNum: 0,
        badNum: 0,
        expectMoney: 0,
        expressMoney: 0,
        finalMoney: 0,
        expressSubsidy: 0,
        backVoList: []
    });

    const form = reactive({
        orderId: null,
        type: 1,
        reason: '',
        money: 0
    });

    /** 表单验证规则 */
    const rules = reactive({
        type: [
            {
                required: true,
                message: '请选择补款类型',
                type: 'string',
                trigger: 'change'
            }
        ],
        reason: [
            {
                required: true,
                message: '请输入备注信息',
                type: 'string',
                trigger: 'blur'
            }
        ],
        money: [
            {
                required: true,
                message: '请输入补款金额',
                type: 'number',
                trigger: 'change'
            },
            {
                validator: (rule, value, callback) => {
                    if (value <= 0) {
                        callback(new Error('补款金额必须大于0'));
                    } else if (value > orderData.value.canBackMoney) {
                        callback(new Error('补款金额不能大于可补款金额'));
                    } else {
                        callback();
                    }
                },
                trigger: 'change'
            }
        ]
    });

    // 表格数据
    const columns = reactive([
        { label: '操作人', prop: 'operator', width: 100 },
        {
            label: '金额',
            prop: 'money',
            width: 100,
            formatter: (row) => {
                return '￥' + row.money;
            }
        },
        {
            label: '类型',
            prop: 'type',
            width: 100,
            formatter: (row) => {
                return row.type == 1 ? '书籍补款' : '运费补款';
            }
        },
        { label: '操作时间', prop: 'createTime', width: 180 },
        { label: '备注', prop: 'reason' }
    ]);

    /** 关闭弹窗 */
    const handleCancel = () => {
        visible.value = false;
        resetForm();
    };

    /** 重置表单 */
    const resetForm = () => {
        form.orderId = null;
        form.type = 1;
        form.reason = '';
        form.money = 0;
        formRef.value?.resetFields();
    };

    /** 弹窗打开事件 */
    const handleOpen = (row) => {
        if (row && row.orderId) {
            visible.value = true;
            form.orderId = row.orderId;
            getPayInBackInfo(row.orderId);
        }
    };

    /** 获取补款信息 */
    const getPayInBackInfo = (orderId) => {
        proxy.$http
            .get(`/order/orderPayInBack/getPayInBack/${orderId}`)
            .then((res) => {
                if (res.data.code === 200) {
                    let data = res.data.data || {};
                    orderData.value = {
                        ...data,
                        backVoList: data.backVoList || []
                    };
                } else {
                    EleMessage.error(res.data.msg || '获取补款信息失败');
                }
            });
    };

    /** 提交表单 */
    const handleSubmit = () => {
        formRef.value?.validate(async (valid) => {
            if (!valid) return;
            proxy.$http
                .post('/order/orderPayInBack/addPayInBack', {
                    orderId: form.orderId,
                    type: form.type,
                    reason: form.reason,
                    money: form.money
                })
                .then((res) => {
                    if (res.data.code == 200) {
                        EleMessage.success('补款申请成功');
                        emit('success');
                        handleCancel();
                    } else {
                        EleMessage.error(res.data.msg || '补款申请失败');
                    }
                });
        });
    };

    defineExpose({
        handleOpen
    });
</script>
