<template>
    <view class="common-page" style="padding: 0;" @click="playGlobalSound">
        <!-- 顶部导航栏 -->
        <view class="header">
            <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" v-permission="'app:wms:badIn:submit'"></u-text>
                </template>
            </u-navbar>
        </view>

        <!-- 主要内容区域 -->
        <view class="content">
            <!-- 订单基本信息 -->
            <view class="info-section">
                <u-form :model="formData" ref="formRef" label-width="80px" label-position="left">
                    <u-form-item label="订单总数" required>
                        <span>{{ ordersMap.length }}</span>
                    </u-form-item>
                    <u-form-item label="仓库" required>
                        <view @click="selectWarehouse" style="width: 100%;">
                            <u-input v-model="formData.godownName" readonly custom-style="font-size:32rpx"
                                placeholder="请选择仓库" suffixIcon="arrow-right" />
                        </view>
                    </u-form-item>
                    <u-form-item label="库位" required>
                        <view @click="selectLocation" style="width: 100%;">
                            <u-input v-model="formData.positionCode" readonly custom-style="font-size:32rpx"
                                placeholder="请选择库位" suffixIcon="arrow-right" />
                        </view>
                    </u-form-item>
                </u-form>
            </view>

            <!-- 订单列表 -->
            <view class="order-list">
                <bad-item v-for="(order, index) in ordersMap" :key="index" :data="order" @delete="deleteOrder(index)"
                    @edit="editOrder(index)"></bad-item>
            </view>

            <!-- 底部扫码输入框 -->
            <view class="fixed-bottom pad-20" style="background: #ffffff;">
                <u-search placeholder="请输入物流单号" :searchIconSize="24" bgColor="#f6f7f6"
                    @search="getDetailByCode(waybillCode)" v-model="waybillCode" custom-style="font-size:32rpx"
                    placeholder-style="font-size:32rpx" :clearabled="true" :focus="false" :showAction="false"
                    :height="42"></u-search>

                <u-icon name="scan" size="32" color="#19be6b" @click="openScan"></u-icon>
            </view>
        </view>

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

<script setup>
import {
    ref,
    reactive,
    onMounted,
    onUnmounted,
} from 'vue';
import { onShow } from '@dcloudio/uni-app';
import BadItem from './components/BadItem.vue';
import VolumeTTS from '@/utils/VolumeTTS.js'
import RemarkDialog from './components/RemarkDialog.vue'

const waybillCode = ref()
// 表单数据
const formData = reactive({
    godownName: '',
    godownId: '',
    positionCode: ''
});

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

// 订单列表
const ordersMap = ref([]);
const codeMap = ref([]); // 记录已扫码的物流单号
//根据扫码的物流单号查询订单详情 /app/stock/searchOrder  waybillCode 
function getDetailByCode(code) {
    if (codeMap.value.includes(code)) {
        uni.$u.ttsModule.speak('重复扫描')
        return
    }
    uni.$u.http.get("/app/stock/searchOrder?waybillCode=" + code).then(res => {
        if (res.code == 200) {
            ordersMap.value.unshift(res.data)
            codeMap.value.push(code)
        } else if (res.code == 601) {
            uni.$u.ttsModule.speak(res.msg)
            uni.showModal({
                title: '提示',
                content: res.msg,
                showCancel: false,
                success: () => {
                    playGlobalSound()
                }
            })
        } else {
            uni.$u.toast(res.msg)
        }
    })
}

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

// 方法定义
const goBack = () => {
    if (ordersMap.value.length > 0) {
        uni.showModal({
            title: '退出确认',
            content: '是否确认放弃本次入库？',
            success: (res) => {
                playGlobalSound()
                if (res.confirm) {
                    uni.navigateBack();
                }
            }
        })
    } else {
        uni.navigateBack();
    }
};

const onSubmit = () => {
    if (!formData.godownId || !formData.positionCode) {
        uni.$u.toast('请先选择仓库和库位')
        uni.$u.ttsModule.speak('请先选择仓库和库位')
        return
    }
    uni.showModal({
        title: '提交确认',
        content: '是否确认提交本次入库？',
        success: (res) => {
            playGlobalSound()
            if (res.confirm) {
                handleSubmitConfirm()
            }
        }
    })
}

const handleSubmitConfirm = async () => {
    uni.showLoading({
        title: '提交中...'
    })

    let orderInfo = ordersMap.value.map(item => {
        return {
            orderId: item.orderId,
            waybillCode: item.waybillCode,
            bookNum: item.badNum,
            remark: item.remark
        }
    })
    if (orderInfo.length == 0) {
        uni.hideLoading()
        uni.$u.ttsModule.speak('请添加订单数据')
        return
    }
    // 提交入库
    uni.$u.http.post('/app/stock/addBatch', {
        godownId: formData.godownId,
        positionCode: formData.positionCode,
        orderInfo
    }).then(res => {
        if (res.code == 200) {
            uni.$u.toast('入库成功')
            uni.$u.ttsModule.speak('入库成功')
            clearData()
        } else {
            uni.$u.toast(res.msg)
        }
    }).finally(() => {
        uni.hideLoading()
    })
}

//成功之后，清空数据
const clearData = () => {
    ordersMap.value.length = 0
    waybillCode.value = ''
    formData.godownName = ''
    formData.positionCode = ''
    formData.godownId = ''
}

const editOrder = (index) => {
    // 编辑订单
    openRemarkDialog(index)
};

const openScan = () => {
    // 打开扫码器
    uni.scanCode({
        success: (res) => {
            waybillCode.value = res.result
            getDetailByCode(res.result)
        },
        fail: (err) => {
            uni.showToast({
                title: '扫码失败',
                icon: 'error'
            });
        }
    });
};

//选择库位
function selectLocation() {
    if (!formData.godownId) {
        uni.$u.toast('请先选择仓库')
        uni.$u.ttsModule.speak('请先选择仓库')
        return
    }
    //如果有库位，也带过去
    uni.navigateTo({
        url: "/pages/index/wms/location-select?godownId=" + formData.godownId + "&positionCode=" + formData.positionCode
    })
}

// 删除订单
const deleteOrder = (index) => {
    ordersMap.value.splice(index, 1);
};

onMounted(() => {
    // #ifdef APP-PLUS
    uni.$u.useGlobalEvent((e) => {
        if (e.barcode) {
            waybillCode.value = e.barcode
            getDetailByCode(e.barcode)
        }
    })
    // #endif

    // 监听库位选择
    uni.$on('updateLocation', (locationCode) => {
        formData.positionCode = locationCode
    })

    // 监听仓库选择
    uni.$on('updateWarehouse', (data) => {
        formData.godownName = data.godownName
        formData.godownId = data.id
    })
})
onShow(() => {
    uni.$u.updateActivePageOnShow()
})

// 记得在页面卸载时移除事件监听
onUnmounted(() => {
    uni.$off('updateLocation')
    uni.$off('updateWarehouse')
})

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

// 处理备注确认
const handleRemarkConfirm = (remark) => {
    if (currentEditIndex.value >= 0) {
        ordersMap.value[currentEditIndex.value].remark = remark
    }
    currentEditIndex.value = -1
    currentRemark.value = ''
}

// 打开仓库选择页面
const selectWarehouse = () => {
    uni.navigateTo({
        url: '/pages/index/wms/warehouse-select?godownId=' + formData.godownId
    })
}
</script>

<style scoped>
.content {
    padding-top: 44px;
    border-radius: 0;
    /* #ifdef APP-PLUS */
    padding-top: 100px;
    /* #endif */
}

.info-section {
    background-color: #ffffff;
    padding: 15px 20px;
    padding-bottom: 5px;
    margin-bottom: 12px;
    box-sizing: border-box;
}

.order-list {
    margin-bottom: 60px;
}
</style>