<template>
    <view class="container">
        <!-- 底部按钮 -->
        <view class="footer">
            <!-- 查询区域 -->
            <view class="query-section">
                <view class="search-box">
                    <u-input
                        custom-style="font-size:32rpx"
                        placeholder-style="fong-size:32rpx"
                        v-model="formData.search"
                        placeholder="扫描/输入物流单号"
                        border="surround"
                        clearable
                    >
                    </u-input>
                    <u-button color="#c8c8c8" text="查询" @click="handleSubmit" />
                </view>
            </view>

            <u-divider></u-divider>

            <view style="display: flex">
                <u-button size="large" type="success" text="扫码" @click="handleScan" />
            </view>
        </view>
    </view>
</template>

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

const formData = ref({
    search: "",
});

// 处理查询
const handleSubmit = async () => {
    if (!formData.value.search) {
        uni.$u.toast("请扫描/输入物流单号");
        return;
    }
    
    try {
        const res = await uni.$u.http.get("/app/workOrder/scanWorkOrder", {
            params: {
                waybillCode: formData.value.search,
                type: 1
            }
        });
        
        if (res.code === 200) {
            if (res.data && res.data.id) {
                // 存在历史工单，跳转到历史工单页面
                uni.navigateTo({
                    url: `/pages/index/work-order/history?workOrderId=${res.data.id}&type=1&waybillCode=${res.data.waybillCode || formData.value.search}&orderId=${res.data.orderId || ''}`,
                });
            } else {
                // 不存在历史工单，跳转到创建工单页面，携带回填信息
                const orderId = res.data?.orderId || '';
                const waybillCode = res.data?.waybillCode || formData.value.search;
                const expressType = res.data?.expressType || '';
                uni.navigateTo({
                    url: `/pages/order/mall/created?waybillCode=${waybillCode}&orderId=${orderId}&expressType=${expressType}&readonly=1`,
                });
            }
        } else {
            uni.$u.toast(res.msg || "查询失败");
        }
    } catch (error) {
        console.error(error);
        uni.$u.toast("查询失败");
    }
};

// 处理扫码
const handleScan = () => {
    uni.scanCode({
        success: (res) => {
            formData.value.search = res.result;
            handleSubmit();
        },
    });
};

// 全局监听事件
// #ifdef APP-PLUS
const { unregister } = uni.$u.useEventListener((e) => {
    formData.value.search = e.barcode;
    handleSubmit();
});
// #endif

onUnmounted(() => {
    // #ifdef APP-PLUS
    unregister();
    // #endif
});

</script>

<style lang="scss" scoped>
@import "../components/common.scss";
</style>
