<template>
    <simple-form-modal :title="title" :items="formItems" ref="editRef" label-width="110px"
        :submit-handler="handleSubmit" @success="handleSuccess">
        <template #isbn="{ model }">
            <el-input v-model="model.isbn" placeholder="请输入" @blur="() => checkIsbn(model)" />
        </template>
    </simple-form-modal>
</template>

<script setup>
import { ref, computed } from 'vue';
import { ElMessage } from 'element-plus';
import SimpleFormModal from '@/components/CommonPage/SimpleFormModal.vue';
import request from '@/utils/request';

const emit = defineEmits(['success']);
const editRef = ref(null);
const title = ref('添加图书');
const currentId = ref(null);

const formItems = computed(() => [
    {
        type: 'isbn', // Custom slot
        label: 'ISBN：',
        prop: 'isbn',
        required: true
    },
    {
        type: 'checkbox',
        label: '易投诉平台：',
        prop: 'platformList',
        required: true,
        options: [
            { label: '拼多多', value: '拼多多' },
            { label: '淘宝', value: '淘宝' },
            { label: '小程序', value: '小程序' },
            { label: '孔网', value: '孔网' }
        ]
    },
    {
        type: 'checkbox',
        label: '易投诉原因：',
        prop: 'reasonList',
        required: true,
        options: [
            { label: '出版社投诉', value: '出版社投诉' },
            { label: '价格投诉', value: '价格投诉' },
            { label: '质量投诉', value: '质量投诉' }
        ]
    }
]);

const checkIsbn = (model) => {
    // Mock check removed or implement real check if needed
};

const handleOpen = (row) => {
    if (row) {
        title.value = '编辑图书';
        currentId.value = row.id;
        // Fetch details if needed or use row data
        // API doc says /shop/complaintBook/getInfo/{id} for details, but row might have enough info.
        // Let's implement getInfo as per requirement.
        request.get(`/shop/complaintBook/getInfo/${row.id}`).then(res => {
            const data = res.data;
            editRef.value?.handleOpen({
                id: data.id,
                isbn: data.isbn,
                platformList: data.platformList || [],
                reasonList: data.reasonList || []
            });
        });
    } else {
        title.value = '添加图书';
        currentId.value = null;
        editRef.value?.handleOpen({
            isbn: '',
            platformList: [],
            reasonList: []
        });
    }
};

const handleSubmit = (model) => {
    return request.post('/shop/complaintBook/setComplaintBook', {
        id: currentId.value,
        isbn: model.isbn,
        platformList: model.platformList,
        reasonList: model.reasonList
    });
};

const handleSuccess = () => {
    emit('success');
};

defineExpose({
    handleOpen
});
</script>
