<template>
    <view class="container" @click="playGlobalSound">
        <!-- 顶部导航栏 -->
        <u-navbar title="下架任务" :border="false" fixed safe-area-inset-top>
            <template #left>
                <u-icon name="arrow-left" color="#333333" size="20" @click="goBack"></u-icon>
            </template>
            <template #right>
                <u-text type="primary" text="提交" @click="onSubmit"></u-text>
            </template>
        </u-navbar>

        <!-- 任务进度 -->
        <view class="progress-section">
            <u-alert title="当前任务" type="info" center></u-alert>
            <view class="flex flex-j-c pad-10" style="padding-right: 40rpx">
                <!-- <view class="next-task" @click="handleNextTask">
                    <text>上一个</text>
                </view> -->
                <view class="flex-c">
                    <text
                        >{{ currentTask }}<text class="progress-text font-20 color-green">/{{ totalTasks }}</text></text
                    >
                </view>
                <!-- <view class="color-green" @click="handleNextTask">
                    <text>下一个</text>
                </view> -->
            </view>
        </view>
        <!-- 库位信息 -->
        <view class="flex flex-j-b pad-10 next-location" style="padding-right: 40rpx; align-items: center">
            <view class="font-14 mb-20">{{ currentTask + 1 }}/{{ totalTasks }}</view>
            <view class="flex-d">
                <view class="font-20 text-center">
                    {{ curTaskInfo.positionCode }}
                </view>
                <view class="location-detail font-13 mt-10" v-if="nextLocation"
                    >下一库位 {{ nextLocation || "无" }}</view
                >
            </view>
            <image
                v-if="!curTaskInfo.isValid"
                src="/static/img/location.png"
                mode="widthFix"
                style="width: 70rpx; height: 70rpx"
            ></image>
            <image
                v-else
                src="/static/img/location-active.png"
                mode="widthFix"
                style="width: 70rpx; height: 70rpx"
            ></image>
        </view>

        <!-- 订单信息 -->
        <view class="order-info">
            <view class="info-item">订单编号：{{ curTaskInfo.orderId }}</view>
            <view class="info-item">物流单号：{{ curTaskInfo.waybillCode || "-" }}</view>
            <view class="info-item">不良数量：{{ curTaskInfo.badNum }}</view>
        </view>

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

        <!-- 底部搜索框 -->
        <view class="fixed-bottom pad-20" style="background: #ffffff">
            <u-search
                v-model="searchText"
                placeholder="请输入订单编号/物流单号/库位号"
                :show-action="false"
                :clearabled="true"
                @search="checkScanText(searchText)"
                height="40"
            >
            </u-search>
            <u-icon name="scan" size="28" color="#19be6b" @click="openScan"></u-icon>
        </view>
    </view>
</template>

<script setup>
import { ref, onMounted } from "vue";
import BadOutCard from "@/pages/index/wms/components/BadOutCard.vue";
import { onLoad, onUnload, onShow } from "@dcloudio/uni-app";

// 任务进度
const currentTask = ref(0);
const totalTasks = ref(0);
const curTaskInfo = ref({});
const nextLocation = ref("");

// 订单信息
const orderList = ref([]);
const ttsModule = ref(null);
const taskCode = ref("");

onUnload(() => {
    uni.$u.ttsModule.stop();
    uni.$u.cleanupOnPageUnload();
});

// 点击全局音效
function playGlobalSound(){
    uni.$u.playClickSound()
}

// 搜索文本
const searchText = ref("");

// 极差商品列表 - 使用detailVoList中的数据
const badList = ref([]);

// 处理下一个任务
const handleNextTask = () => {
    if (currentTask.value < totalTasks.value) {
        currentTask.value++;

        if (currentTask.value == totalTasks.value) {
            uni.$u.ttsModule.speak("任务完成");
        } else {
            curTaskInfo.value = orderList.value[currentTask.value];
            badList.value = curTaskInfo.value.detailVoList || [];

            let nextInfo = orderList.value[currentTask.value + 1];
            nextLocation.value = nextInfo.positionCode;
        }
    }
};

// 搜索处理
const onSearch = () => {
    // TODO: 调用API获取订单详情
    uni.$u.http.get(`/app/appstock/getStockTaskDetail?taskCode=${taskCode.value}`).then((res) => {
        if (res.code == 200) {
            orderList.value = res.data;
            totalTasks.value = res.data.length;

            //默认选中第一个任务
            curTaskInfo.value = res.data[currentTask.value];
            badList.value = curTaskInfo.value.detailVoList || [];
        }
    });
};

// 确认下架任务
const confirmStockTask = () => {
    const params = {
        positionCode: curTaskInfo.value.positionCode,
        orderId: curTaskInfo.value.orderId,
        taskCode: taskCode.value,
    };

    uni.$u.http.post("/app/appstock/setStockTask", params).then((res) => {
        if (res.code === 200) {
            curTaskInfo.value.isCompleted = true;
            orderList.value[currentTask.value] = curTaskInfo.value;

            handleNextTask();
            isFirstScan.value = false;
            uni.$u.ttsModule.speak("下架成功");
        } else {
            uni.showToast({
                title: res.msg,
                icon: "error",
            });
        }
    });
};

//解锁任务
const unlockTask = () => {
    uni.$u.http.post("/app/appstock/unlockStockTask?taskCode=" + taskCode.value).then((res) => {
        if (res.code == 200) {
            uni.showToast({
                title: "解锁成功",
                icon: "success",
            });
        } else {
            uni.showToast({
                title: res.msg || "解锁失败",
                icon: "error",
            });
        }
    });
};

// 提交处理
const onSubmit = () => {
    uni.showModal({
        title: "确认提示",
        content: "是否确认提交本次下架？",
        success: (res) => {
            playGlobalSound()
            if (res.confirm) {
                uni.navigateBack();
                uni.$u.ttsModule.speak("任务已提交");
                unlockTask();
            }
        },
    });
};

function goBack() {
    uni.showModal({
        title: "确认提示",
        content: "是否确认放弃本次下架？",
        success: (res) => {
            playGlobalSound()
            if (res.confirm) {
                uni.navigateBack();
                uni.$u.ttsModule.speak("任务已放弃");
                unlockTask();
            }
        },
    });
}
let isFirstScan = ref(false); //是否验证了库位号
//扫码首先校验库位号，如果库位号不正确，则提示库位号不正确 如果正确，curTaskInfo.isValid = true
//正确后继续校验物流号或者订单号，如果正确，则调用
//库位号格式 字母+数字+横杠-  物流号格式 必须有字母+数字组合  订单号 数字
const checkScanText = (scanText) => {
    console.log(scanText, "scanText");
    let length = scanText ? scanText.length : 0;
    //先判断扫描到的scanText是库位号还是物流号或者订单号
    let isPositionCode = scanText.indexOf("-") > -1 && length == 9;
    let isWaybillCode = /^(?=.*[A-Z])(?=.*\d)[A-Z0-9]+$/.test(scanText);
    let isOrderId = /^\d+$/.test(scanText);

    //库位号校验
    if (isPositionCode) {
        let positionCode = curTaskInfo.value.positionCode;
        if (positionCode != scanText) {
            uni.showToast({
                title: "库位号不正确",
                icon: "error",
            });
        } else {
            isFirstScan.value = true;
            curTaskInfo.value.isValid = true;
        }
    }
    if (!isFirstScan.value) {
        uni.$u.ttsModule.speak("请先校验库位号");
        return;
    }

    //物流号或者订单号校验
    if (isWaybillCode || isOrderId) {
        let waybillCode = curTaskInfo.value.waybillCode;
        let orderId = curTaskInfo.value.orderId;
        if (waybillCode == scanText || orderId == scanText) {
            confirmStockTask();
        } else {
            uni.showToast({
                title: "订单号或物流号不匹配",
                icon: "error",
            });
            curTaskInfo.value.isValid = true;
        }
    }
};

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

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

onLoad((opts) => {
    taskCode.value = opts.taskCode;
    onSearch();
    // #ifdef APP-PLUS

    uni.$u.useGlobalEvent((e) => {
        if (e.barcode) {
            searchText.value = e.barcode;
            checkScanText(e.barcode);
        }
    });
    // #endif
});
onShow(() => {
    uni.$u.updateActivePageOnShow();
});
</script>

<style scoped>
.progress-section {
    background-color: #fff;
    display: flex;
    flex-direction: column;
    justify-content: center;
    padding: 10rpx;
    padding-top: 56px;
}

.next-location {
    background-color: #fff;
    border-bottom: 1rpx solid #f0f0f0;
    border-top: 1rpx solid #f0f0f0;
    padding: 20rpx;
}

.color-green {
    color: #4caf50;
}

.location-info {
    background-color: #fff;
    padding: 20rpx;
    margin-top: 2rpx;
}

.location-detail {
    color: #666;
}

.order-info {
    background-color: #fff;
    padding: 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;
}
.container {
    /* #ifdef H5 */
    padding-bottom: 70px;
    /* #endif */
}
</style>
