<template>
    <view class="container">
        <!-- 搜索框 -->
        <u-sticky>
            <view class="search-area flex-c mb-20">
                <u-search
                    v-model="searchText"
                    :placeholder="searchType == '1' ? '请输入订单编号' : '请输入运单号'"
                    :show-action="false"
                    :clearabled="true"
                    @search="onSearch"
                    height="40"
                >
                </u-search>
                <u-icon name="scan" size="28" color="#19be6b" @click="openScan"></u-icon>
            </view>
        </u-sticky>

        <view class="content">
            <!-- 错误提示 -->
            <view v-if="errorMsg" class="error-section">
                <u-icon name="info-circle" color="#fa3534" size="20"></u-icon>
                <text class="error-text">{{ errorMsg }}</text>
            </view>

            <!-- 基本信息 -->
            <template v-if="hasData">
                <view class="info-section">
                    <view class="info-item">库位：{{ locationInfo.positionCode }}</view>
                    <view class="info-item">物流单号：{{ locationInfo.waybillCode || "-" }}</view>
                    <view class="info-item">退回物流：{{ locationInfo.refundWaybillCode || "-" }}</view>
                    <view class="info-item">订单编号：{{ locationInfo.orderId }}</view>
                    <view class="info-item">订单商品：{{ locationInfo.badNum }}</view>
                    <view class="info-item">备注信息：{{ locationInfo.remark || "-" }}</view>
                </view>

                <!-- 极差商品列表 -->
                <view class="bad-list">
                    <view class="list-title mb-6">极差</view>
                    <view v-for="(item, index) in badList" :key="index">
                        <BadOutCard :item="item" :index="index" />
                    </view>
                </view>
            </template>
        </view>

        <!-- 底部按钮 -->
        <view class="fixed-bottom">
            <u-button size="large" type="warning" text="反馈" @click="openRemarkDialog" />
            <u-button size="large" type="primary" text="确定出库" @click="onConfirm" />
        </view>

        <!-- 备注弹窗 -->
        <remark-dialog
            v-model:visible="remarkVisible"
            :initial-value="currentRemark"
            @confirm="handleRemarkConfirm"
        ></remark-dialog>
    </view>
</template>

<script setup>
import { ref, onMounted } from "vue";
import BadOutCard from "./components/BadOutCard.vue";
import RemarkDialog from "./components/RemarkDialog.vue";
import VolumeTTS from "@/utils/VolumeTTS.js";
import { onLoad } from "@dcloudio/uni-app";

const searchText = ref("");
const searchType = ref("1");
const errorMsg = ref("");
const hasData = ref(false);

// 位置信息
const locationInfo = ref({
    positionCode: "",
    waybillCode: "",
    orderId: "",
    badNum: "",
    remark: "",
    refundWaybillCode: "",
});

// 极差商品列表
const badList = ref([]);

onLoad((options) => {
    searchType.value = options.searchType || "1";
    if (options.searchText) {
        searchText.value = options.searchText;
        onSearch();
    }
});

// 判断搜索类型
const getSearchType = (text) => {
    // 这里可以根据实际业务逻辑调整判断条件
    // 假设订单号都是纯数字，物流号包含字母
    return /^[0-9]+$/.test(text) ? 1 : 2;
};

// 搜索处理
const onSearch = async () => {
    if (!searchText.value) {
        errorMsg.value = "请输入运单号或订单编号";
        hasData.value = false;
        return;
    }

    try {
        const res = await uni.$u.http.post("/app/stock/findOrderOutStock", {
            search: searchText.value,
            searchType: searchType.value,
        });
        if (res.code == 200) {
            const data = res.data;
            errorMsg.value = "";
            hasData.value = true;
            // 更新页面数据
            locationInfo.value = {
                positionCode: data.positionCode || "",
                waybillCode: data.waybillCode || "",
                orderId: data.orderId || "",
                badNum: data.badNum || "",
                remark: data.remark || "",
                refundWaybillCode: data.refundWaybillCode || "",
            };
            badList.value = data.detailVoList || [];
        } else {
            errorMsg.value = res.msg || "未找到相关数据";
            hasData.value = false;
            return;
        }
    } catch (error) {
        errorMsg.value = error.message || "获取数据失败";
        hasData.value = false;
        uni.showToast({
            title: "获取数据失败",
            icon: "none",
        });
    }
};

// 打开扫码
const openScan = () => {
    // #ifdef APP-PLUS || MP-WEIXIN
    uni.scanCode({
        success: (res) => {
            searchText.value = res.result;
            onSearch();
        },
        fail: (err) => {
            uni.showToast({
                title: "扫码失败",
                icon: "error",
            });
        },
    });
    // #endif

    // #ifdef H5
    uni.showToast({
        title: "H5环境不支持扫码",
        icon: "none",
    });
    // #endif
};

// 确认出库
const onConfirm = () => {
    uni.showModal({
        title: "确认提示",
        content: "是否确认出库？",
        success: async (res) => {
            if (res.confirm) {
                uni.$u.http
                    .post("/app/stock/outStock", {
                        orderId: locationInfo.value.orderId,
                        positionCode: locationInfo.value.positionCode,
                        outputRemark: locationInfo.value.remark,
                    })
                    .then((res) => {
                        if (res.code == 200) {
                            uni.showToast({
                                title: "出库成功",
                                icon: "success",
                            });
                            uni.$u.ttsModule.speak("出库成功");

                            // 清空数据
                            searchText.value = "";
                            locationInfo.value = {
                                positionCode: "",
                                waybillCode: "",
                                orderId: "",
                                badNum: "",
                                remark: "",
                            };
                            badList.value = [];
                        } else {
                            uni.showToast({
                                title: res.msg,
                                icon: "none",
                            });
                            uni.$u.ttsModule.speak(res.msg);
                        }
                    });
            }
        },
    });
};

// 备注弹窗相关
const remarkVisible = ref(false);
const currentRemark = ref("");
const currentEditIndex = ref(-1);

// 打开备注弹窗
const openRemarkDialog = (index, remark = "") => {
    currentEditIndex.value = index;
    currentRemark.value = remark;
    remarkVisible.value = true;
};

// 处理备注确认
const handleRemarkConfirm = (remark) => {
    if (currentEditIndex.value >= 0) {
        orders.value[currentEditIndex.value].remark = remark;
    }
    currentEditIndex.value = -1;
    currentRemark.value = "";
};
</script>

<style scoped>
.container {
    padding-bottom: 120rpx;
}

.error-section {
    background-color: #fef0f0;
    padding: 20rpx;
    border-radius: 8rpx;
    margin-bottom: 20rpx;
    display: flex;
    align-items: center;
}

.error-text {
    color: #fa3534;
    margin-left: 10rpx;
    font-size: 28rpx;
}

.info-section {
    background-color: #fff;
    padding: 20rpx;
    border-radius: 8rpx;
    margin-bottom: 20rpx;
}

.info-item {
    line-height: 1.8;
}

.list-title {
    font-size: 32rpx;
    font-weight: bold;
    background-color: rgb(222, 134, 143, 0.5);
    padding: 10rpx 0;
    padding-left: 30rpx;
}

.bad-list {
    margin-bottom: 20rpx;
}

.footer {
    position: fixed;
    bottom: 100rpx;
    left: 0;
    right: 0;
    background-color: #fff;
    padding: 20rpx;
}

.btn-group {
    display: flex;
    justify-content: space-around;
}

.search-wrapper {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    background-color: #fff;
    padding: 20rpx;
    box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
}
</style>
