<template>
    <view class="common-page">
        <u-form :model="form" :rules="rules" ref="formRef" labelWidth="90px" errorType="toast" :labelStyle="labelStyle">
            <u-form-item label="重量（克）" prop="weight" required>
                <u-input :placeholderStyle="placeholderStyle" :customStyle="customStyle" v-model="form.weight" placeholder="请输入数值" clearable />
            </u-form-item>
            <u-form-item label="ISBN" prop="isbn" required>
                <u-input :placeholderStyle="placeholderStyle" :customStyle="customStyle" v-model="form.isbn" placeholder="请输入编码" clearable />
            </u-form-item>
        </u-form>

        <view class="fixed-bottom">
            <u-button size="large" type="warning" text="扫码" @click="handleScan" />
            <u-button size="large" type="success" text="提交" v-permission="'app:entry:bookWeight:confirm'" @click="submitForm" />
        </view>
    </view>
</template>

<script setup>
import { ref, onUnmounted } from 'vue';
import { onLoad, onShow } from '@dcloudio/uni-app'

const customStyle = {
    height: '100rpx',
    fontSize: '32rpx'
}
const labelStyle = {
    fontSize: '32rpx'
}
const placeholderStyle = ref("fontSize: 32rpx")

const form = ref({
    weight: '',
    isbn: ''
});

const rules = {
    weight: [{
        required: true,
        message: '请输入重量',
        trigger: 'blur'
    },
    {
        type: 'number',
        message: '重量必须是数字',
        trigger: 'blur'
    }
    ],
    isbn: [{
        required: true,
        message: '请输入ISBN',
        trigger: 'blur'
    }]
};

function handleScan() {
    uni.scanCode({
        success: (res) => {
            form.value.isbn = res.result
        }
    })
}

const formRef = ref(null);
const submitForm = () => {
    formRef.value.validate().then((valid) => {
        if (valid) {
            // 提交表单
            uni.$u.http.post('/app/weighChangeLog/add', form.value).then(res => {
                if (res.code == 200) {
                    uni.$u.toast('修改成功');
                    form.value.isbn = ''
                    form.value.weight = ''
                } else {
                    uni.$u.toast(res.msg);
                }
            })
        }
    });
};

onLoad(() => {
    // #ifdef APP-PLUS
    uni.$u.useGlobalEvent((e) => {
        form.value.isbn = e.barcode
    })
    // #endif
})
onShow(() => {
    uni.$u.updateActivePageOnShow()
})
onUnmounted(() => {
    uni.$u.cleanupOnPageUnload();
});
</script>