<!-- 编辑弹窗 -->
<template>
    <ele-modal
        form
        :width="960"
        v-model="visible"
        title="申请订单理赔"
        @open="handleOpen"
    >
        <el-row :gutter="12" class="common-row">
            <el-col :span="24">订单编号：{{ orderData.orderId || '-' }}</el-col>
            <el-col :span="24"
                >预估金额：{{ orderData.expectMoney || '0' }}元</el-col
            >
            <el-col :span="24"
                >审核金额：{{ orderData.finalMoney || '0' }}元</el-col
            >
            <el-col :span="24"
                >书籍补款：{{ orderData.backMoney || '0' }}元</el-col
            >
        </el-row>

        <el-form
            ref="formRef"
            :model="form"
            :rules="rules"
            label-width="80px"
            @submit.prevent=""
        >
            <el-form-item label="理赔金额" prop="money">
                <el-input-number
                    v-model="form.money"
                    :controls="false"
                    :min="0"
                    :max="orderData.canBackMoney"
                    :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-radio-group v-model="form.reason">
                    <el-radio
                        v-for="item in reasonList"
                        :key="item"
                        :value="item"
                    >
                        {{ item }}
                    </el-radio>
                </el-radio-group>
            </el-form-item>

            <el-form-item label="理赔记录" prop="records">
                <ele-data-table
                    row-key="id"
                    :columns="columns"
                    :data="claimRecords"
                />
            </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,
        expectMoney: 0,
        finalMoney: 0,
        backMoney: 0,
        canBackMoney: 0
    });

    /** 理赔记录 */
    const claimRecords = ref([]);

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

    /** 表单验证规则 */
    const rules = reactive({
        reason: [
            {
                required: true,
                message: '请选择理赔原因',
                type: 'string',
                trigger: 'change'
            }
        ],
        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: 'reason', width: 100 },
        { label: '操作时间', prop: 'createTime', width: 180 },
        { label: '备注', prop: 'reason' }
    ]);

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

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

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

    /** 获取理赔记录 */
    const reasonList = ref([]);
    const getClaimRecords = (orderId) => {
        proxy.$http
            .get(`/order/orderPayInBack/getPayClaims/${orderId}`)
            .then((res) => {
                if (res.data.code === 200) {
                    let data = res.data.data || [];
                    orderData.value = data;
                    console.log(orderData.value, 'xxx');
                    claimRecords.value = data.backVoList || [];
                    reasonList.value = data.reasonList || [];
                } else {
                    EleMessage.error(res.data.msg || '获取理赔记录失败');
                }
            });
    };

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

    defineExpose({
        handleOpen
    });
</script>
