<template>
    <view class="common-page" style="padding: 0;">
        <!-- 顶部导航栏 -->
        <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"></u-text>
                </template>
            </u-navbar>
        </view>

        <!-- 主要内容区域 -->
        <view class="content">
            <!-- 订单基本信息 -->
            <view class="info-section">
                <u-form :model="formData" ref="formRef" label-width="70px">
                    <u-form-item label="订单总数" required>
                        <u-input v-model="formData.totalOrders" disabled />
                    </u-form-item>
                    <u-form-item label="仓库" required>
                        <u-input v-model="formData.warehouse" @click="selectWarehouse" />
                    </u-form-item>
                    <u-form-item label="库位" required>
                        <u-input v-model="formData.location" @click="selectLocation" />
                    </u-form-item>
                </u-form>
            </view>

            <!-- 订单列表 -->
            <view class="order-list">
                <bad-item v-for="(order, index) in orders" :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="请输入/扫描条码" v-model="scanCode" @confirm="onScanConfirm" :show-action="false"
                    custom-style="margin-right:10px"></u-search>
                <u-icon name="scan" size="28" 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 BadItem from './components/BadItem.vue';
import VolumeTTS from '@/utils/VolumeTTS.js'
import RemarkDialog from './components/RemarkDialog.vue'

// 表单数据
const formData = reactive({
    totalOrders: '3',
    warehouse: '河南仓',
    location: 'K001-0111'
});

// 订单列表
const orders = ref([{
    orderNo: '000001',
    badCount: '5',
    logisticsNo: 'DPK202444118877',
    checkDate: '2024-11-14',
    operator: '李程雪'
}, {
    orderNo: '000001',
    badCount: '5',
    logisticsNo: 'DPK202444118877',
    checkDate: '2024-11-14',
    operator: '李程雪'
},]);

const scanCode = ref('');

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

// 方法定义
const goBack = () => {
    uni.navigateBack();
};

const onSubmit = () => {
    uni.showModal({
        title: '提交确认',
        content: '是否确认提交本次入库？',
        success: (res) => {
            if (res.confirm) {
                handleSubmitConfirm()
            }
        }
    })
}

const handleSubmitConfirm = async () => {
    try {
        uni.showLoading({
            title: '提交中...'
        })
        
        // TODO: 这里添加实际的提交逻辑
        await new Promise(resolve => setTimeout(resolve, 1000)) // 模拟请求
        
        uni.hideLoading()
        uni.showToast({
            title: '提交成功',
            icon: 'success'
        })
        
        // 提交成功后返回上一页
        setTimeout(() => {
            uni.navigateBack()
        }, 1500)
        
    } catch (error) {
        uni.hideLoading()
        uni.showToast({
            title: '提交失败',
            icon: 'error'
        })
    }
}

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

const onScanConfirm = () => {
    // 扫码确认逻辑
    // #ifdef APP-PLUS || MP-WEIXIN
    uni.scanCode({
        scanType: ['barCode'], // 支持条形码和二维码
        success: (res) => {
            scanCode.value = res.result;
        },
        fail: (err) => {
            uni.showToast({
                title: '扫码失败',
                icon: 'error'
            });
        }
    });
    // #endif

    // #ifdef H5
    uni.showToast({
        title: 'H5环境不支持扫码，请手动输入',
        icon: 'none'
    });
    // #endif
};

const openScan = () => {
    // 打开扫码器
};

//选择库位
function selectLocation() {
    uni.navigateTo({
        url: "/pages/index/wms/location-select"
    })
}

// 删除订单
const deleteOrder = (index) => {
    orders.value.splice(index, 1);
    // 更新总数
    formData.totalOrders = orders.value.length.toString();
};

const ttsModule = ref(null);
onMounted(() => {
    ttsModule.value = new VolumeTTS();

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

    // 监听仓库选择
    uni.$on('updateWarehouse', (warehouseName) => {
        formData.warehouse = warehouseName
    })
})

// 记得在页面卸载时移除事件监听
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) {
        orders.value[currentEditIndex.value].remark = remark
    }
    currentEditIndex.value = -1
    currentRemark.value = ''
}

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

<style scoped>
.content {
    padding-top: 44px;
    border-radius: 0;
}

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

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