<!-- 出库操作弹窗 -->
<template>
    <ele-modal
        form
        :width="500"
        v-model="visible"
        title="出库"
        @closed="handleClosed"
    >
        <el-form
            ref="formRef"
            :model="formData"
            :rules="rules"
            label-width="80px"
        >
            <el-form-item label="出库仓库" prop="repositoryId">
                <el-input
                    :model-value="repositoryName"
                    placeholder="请选择仓库"
                    readonly
                />
            </el-form-item>

            <el-form-item label="ISBN" prop="isbn">
                <el-input
                    v-model="formData.isbn"
                    placeholder="请输入ISBN"
                    readonly
                />
            </el-form-item>

            <el-form-item label="书名" prop="bookName">
                <el-input
                    v-model="formData.bookName"
                    placeholder="请输入书名"
                    readonly
                />
            </el-form-item>

            <el-form-item label="数量" prop="num">
                <el-input-number
                    v-model="formData.num"
                    :min="numMin"
                    :max="numMax"
                    :precision="0"
                    placeholder="请输入数量"
                    style="width: 200px"
                    @change="handleNumChange"
                />
                <span class="stock-tip">当前仓库可用库存：{{ maxStock }}</span>
            </el-form-item>

            <el-form-item label="单价" prop="price">
                <el-input-number
                    v-model="formData.price"
                    :min="0"
                    :precision="2"
                    placeholder="请输入单价"
                    style="width: 200px"
                />
            </el-form-item>

            <el-form-item label="备注" prop="remark">
                <el-input
                    v-model="formData.remark"
                    type="textarea"
                    :rows="3"
                    placeholder="请输入备注"
                />
            </el-form-item>
        </el-form>

        <template #footer>
            <el-button @click="handleCancel">取消</el-button>
            <el-button
                type="success"
                :loading="loading"
                @click="handleGenerateLink"
            >
                生成链接
            </el-button>
        </template>
    </ele-modal>
</template>

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

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

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

    /** 加载状态 */
    const loading = ref(false);

    /** 表单数据 */
    const formData = reactive({
        repositoryId: null,
        isbn: '',
        bookName: '',
        num: 1,
        price: 0,
        remark: ''
    });

    /** 当前书籍信息 */
    const currentBook = ref(null);
    const repositoryName = ref('');
    const maxStock = computed(() => Number(currentBook.value?.stockNum || 0));
    // InputNumber 要求 min <= max，库存为 0 时避免 min(1) > max(0)
    const numMin = computed(() => (maxStock.value > 0 ? 1 : 0));
    const numMax = computed(() => Math.max(maxStock.value, 0));

    /** 表单验证规则 */
    const rules = reactive({
        repositoryId: [
            { required: true, message: '请先选择仓库', trigger: 'change' }
        ],
        num: [
            { required: true, message: '请输入数量', trigger: 'blur' },
            {
                type: 'number',
                min: 1,
                message: '数量必须大于0',
                trigger: 'blur'
            },
            {
                validator: (rule, value, callback) => {
                    if (!Number.isInteger(value)) {
                        callback(new Error('数量必须是整数'));
                    } else if (value > maxStock.value) {
                        callback(
                            new Error(
                                '此次出库超出库存数量，请减少数量后重试！'
                            )
                        );
                    } else {
                        callback();
                    }
                },
                trigger: 'blur'
            }
        ],
        price: [
            { required: true, message: '请输入单价', trigger: 'blur' },
            {
                type: 'number',
                min: 0,
                message: '单价不能小于0',
                trigger: 'blur'
            }
        ]
    });

    /** 出库结果数据 */
    const outStockResult = ref(null);

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

    /** 弹窗关闭事件 */
    const handleClosed = () => {
        // 重置表单
        formRef.value?.resetFields();
        Object.assign(formData, {
            repositoryId: null,
            isbn: '',
            bookName: '',
            num: 1,
            price: 0,
            remark: ''
        });
        currentBook.value = null;
        repositoryName.value = '';
        outStockResult.value = null;
        loading.value = false;
    };

    /** 数量变化处理 */
    const handleNumChange = (value) => {
        if (value > maxStock.value) {
            EleMessage.warning('此次出库超出库存数量，请减少数量后重试！');
            formData.num = maxStock.value || 1;
            return;
        }

        if (currentBook.value) {
            // 数量大于1时使用批发价，否则使用零售价
            if (value > 1) {
                formData.price = currentBook.value.wholesalePrice || 0;
            } else {
                formData.price = currentBook.value.retailPrice || 0;
            }
        }
    };

    /** 生成链接 */
    const handleGenerateLink = async () => {
        await formRef.value?.validate();

        if (!formData.repositoryId) {
            EleMessage.warning('出库只能出当前仓库的，请先选择仓库');
            return;
        }
        if (formData.num > maxStock.value) {
            EleMessage.warning('此次出库超出库存数量，请减少数量后重试！');
            return;
        }

        loading.value = true;

        request
            .post('/activation/bookActivationInfo/outStock', {
                repositoryId: formData.repositoryId,
                isbn: formData.isbn,
                num: formData.num,
                price: formData.price,
                remark: formData.remark
            })
            .then((response) => {
                if (response.data.code === 200) {
                    outStockResult.value = response.data.data;
                    EleMessage.success('出库成功');
                    visible.value = false;
                    emit('openActivationModal', {
                        ...formData,
                        repositoryName: repositoryName.value,
                        ...response.data.data
                    });
                    emit('success');
                } else {
                    EleMessage.error(
                        response.data.msg ||
                            '此次出库超出库存数量，请减少数量后重试！'
                    );
                }
            })
            .finally(() => {
                loading.value = false;
            });
    };

    /** 弹窗打开事件 */
    const handleOpen = (bookInfo, warehouse) => {
        if (!warehouse?.id) {
            EleMessage.warning('出库只能出当前仓库的，请先在上方选择仓库');
            return;
        }
        if (!bookInfo) return;

        const stock = Number(bookInfo.stockNum || 0);
        if (stock <= 0) {
            EleMessage.warning('当前仓库可用库存为0，无法出库');
            return;
        }

        currentBook.value = bookInfo;
        repositoryName.value = warehouse.name || '';
        formData.repositoryId = warehouse.id;
        formData.isbn = bookInfo.isbn || '';
        formData.bookName = bookInfo.bookName || '';
        formData.num = 1;
        formData.price = bookInfo.retailPrice || 0;
        formData.remark = '';
        visible.value = true;
    };

    /** 定义事件 */
    const emit = defineEmits(['openActivationModal', 'success']);

    defineExpose({
        handleOpen
    });
</script>

<style scoped>
    .el-form-item {
        margin-bottom: 20px;
    }

    .stock-tip {
        margin-left: 12px;
        color: #909399;
        font-size: 13px;
    }
</style>
