<template>
    <ele-modal
        :width="500"
        title="编辑价格"
        v-model="visible"
        @closed="handleClosed"
    >
        <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
            <el-form-item label="商品标题">
                <span>{{ rowData?.bookName || '-' }}</span>
            </el-form-item>
            <el-form-item label="ISBN">
                <span>{{ rowData?.isbn || '-' }}</span>
            </el-form-item>
            <el-form-item label="一般品售价" prop="productPrice">
                <el-input-number
                    v-model="form.productPrice"
                    :min="0"
                    :precision="2"
                    :step="0.1"
                    style="width: 100%"
                />
            </el-form-item>
        </el-form>

        <template #footer>
            <el-button @click="visible = false">取消</el-button>
            <el-button type="primary" @click="handleSubmit" :loading="loading"
                >提交</el-button
            >
        </template>
    </ele-modal>
</template>

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

    const emit = defineEmits(['done']);
    // const visible = defineModel({ type: Boolean });
    const visible = ref(false);
    const loading = ref(false);
    const rowData = ref({});
    const formRef = ref(null);

    const form = reactive({
        productPrice: 0
    });

    const rules = {
        productPrice: [
            { required: true, message: '请输入售价', trigger: 'blur' }
        ]
    };

    // 打开弹窗
    const open = (row) => {
        rowData.value = row;
        form.productPrice = Number(row.productPrice) || 0;
        visible.value = true;
    };

    const handleSubmit = () => {
        formRef.value?.validate(async (valid) => {
            if (!valid) return;

            loading.value = true;
            try {
                request
                    .post('/shop/shopbook/setInfo', {
                        isbn: rowData.value.isbn,
                        productPrice: form.productPrice
                    })
                    .then((res) => {
                        if (res.data.code === 200) {
                            EleMessage.success('价格更新成功');
                            visible.value = false;
                            emit('done');
                        } else {
                            EleMessage.error(res.data.msg || '更新失败');
                        }
                    });
            } catch (e) {
                EleMessage.error(e.message || '更新失败');
            } finally {
                loading.value = false;
            }
        });
    };

    const handleClosed = () => {
        rowData.value = {};
        form.productPrice = 0;
        formRef.value?.resetFields();
    };

    defineExpose({ open });
</script>
