<template>
    <div class="app-container">
        <!-- 权限验证组件 -->
        <PermissionVerify ref="permissionVerify" />

        <template v-if="isAuthenticated">
            <!-- 顶部标题与用户信息 -->
            <div class="header-section">
                <div class="header-content">
                    <div class="title-area" @click="navigateHome">
                        <h1 class="page-title">返修上线</h1>
                        <p class="page-subtitle">Repair Upline</p>
                    </div>
                    <div class="header-actions">
                        <div style="display: flex; align-items: center; color: #fff; opacity: 0.95;">
                            登录人：{{ loginUserName }}
                        </div>
                        <el-button type="danger" icon="SwitchButton" @click="handleLogout" size="small"
                            style="height: 30px;">
                            退出登录
                        </el-button>
                    </div>
                </div>
            </div>

            <!-- 内容滚动区域 -->
            <div class="scroll-container">
                <!-- MQTT连接状态提示 -->
                <div class="mqtt-status-bar" v-if="mqttStatus.show" :class="mqttStatus.type">
                    <div class="mqtt-status-content">
                        <el-icon class="status-icon">
                            <component :is="mqttStatus.icon" />
                        </el-icon>
                        <span>{{ mqttStatus.message }}</span>
                    </div>
                </div>

                <!-- 上半部分：扫码与产品信息 -->
                <div class="top-section">
                    <div class="card">
                        <div class="form">
                            <div class="form-row">
                                <div class="form-item">
                                    <label class="form-label">产品扫码：</label>
                                    <el-input v-model.trim="scanCode" placeholder="支持 Model/PACK/箱体 码"
                                        @keyup.enter="handleScan" clearable prefix-icon="Scanner" />
                                </div>
                                <div class="form-item form-actions">
                                    <!-- <el-button type="primary" :loading="loadingScan" @click="handleScan"
                                        icon="Search">查询返修信息</el-button> -->
                                </div>
                            </div>
                            <div class="form-row">
                                <div class="form-item">
                                    <label class="form-label">订单号：</label>
                                    <el-input v-model="formData.orderNo" disabled prefix-icon="Tickets" />
                                </div>
                                <div class="form-item">
                                    <label class="form-label">产品编号：</label>
                                    <el-input v-model="formData.productNo" disabled prefix-icon="Memo" />
                                </div>
                                <div class="form-item">
                                    <label class="form-label">产品型号：</label>
                                    <el-input v-model="formData.productType" disabled prefix-icon="Document" />
                                </div>
                            </div>

                            <div class="form-row">
                                <div class="form-item">
                                    <label class="form-label">不合格工位：</label>
                                    <el-input v-model="formData.ngStation" disabled prefix-icon="Tools" />
                                </div>
                                <div class="form-item">
                                    <label class="form-label">不合格时间：</label>
                                    <el-input v-model="formData.ngTime" disabled prefix-icon="Clock" />
                                </div>
                            </div>
                            <div class="form-row">
                                <div class="form-item form-item-tag">
                                    <label class="form-label">返修状态：</label>
                                    <el-tag v-if="repairStatusInfo.status !== null" :type="repairStatusInfo.type">
                                        {{ repairStatusInfo.text }}
                                    </el-tag>
                                    <span v-else class="empty-text">-</span>
                                </div>
                                <div class="form-item">
                                    <label class="form-label">返修上线口：</label>
                                    <el-input :model-value="repairUplineStationLabel" disabled prefix-icon="Rank" />
                                </div>
                                <div class="form-item">
                                    <label class="form-label">返修上线时间：</label>
                                    <el-input v-model="formData.repairUplineTime" disabled prefix-icon="Clock" />
                                </div>
                            </div>
                            <div class="form-row">
                                <div class="form-item">
                                    <label class="form-label">当前再起始工位：</label>
                                    <el-input :model-value="selectedRestartStationLabel" disabled
                                        prefix-icon="Location" />
                                </div>
                                <div class="form-item">
                                    <label class="form-label">再起始工位到达时间：</label>
                                    <el-input v-model="formData.restartArriveTime" disabled prefix-icon="Clock" />
                                </div>
                            </div>

                            <!-- MOM产品状态显示区域 -->
                            <div class="form-row" v-if="formData.productNo">
                                <div class="form-item">
                                    <label class="form-label">MOM产品状态：</label>
                                    <div style="display: flex; align-items: center; gap: 8px; flex: 1;">
                                        <el-tag v-if="momProductStatus.loading" type="info">
                                            <el-icon class="is-loading">
                                                <Refresh />
                                            </el-icon> 查询中...
                                        </el-tag>
                                        <el-tag v-else-if="momProductStatus.success && momProductStatus.productStatus"
                                            :type="momProductStatus.productStatus === '排队中' ? 'success' : 'warning'">
                                            {{ momProductStatus.productStatus }}
                                        </el-tag>
                                        <el-tag v-else-if="momProductStatus.errorMsg" type="danger">
                                            查询失败
                                        </el-tag>
                                        <span v-else class="empty-text">-</span>
                                        <el-button type="primary" link :loading="momProductStatus.loading"
                                            @click="fetchMomProductStatus" :disabled="!formData.productNo">
                                            <el-icon>
                                                <Refresh />
                                            </el-icon> 刷新状态
                                        </el-button>
                                    </div>
                                </div>
                                <div class="form-item">
                                    <label class="form-label">MOM再起始工位：</label>
                                    <div style="display: flex; align-items: center; gap: 8px; flex: 1;">
                                        <el-tag v-if="momProductStatus.loading" type="info">
                                            <el-icon class="is-loading">
                                                <Refresh />
                                            </el-icon> 查询中...
                                        </el-tag>
                                        <el-tag v-else-if="momProductStatus.success && momProductStatus.opStation"
                                            :type="momProductStatus.stationNotInList ? 'danger' : 'success'">
                                            {{ momProductStatus.opStation }}
                                            <span v-if="momProductStatus.stationNotInList"> (不在清单中)</span>
                                        </el-tag>
                                        <el-tag v-else-if="momProductStatus.errorMsg" type="danger">
                                            查询失败
                                        </el-tag>
                                        <span v-else class="empty-text">-</span>
                                    </div>
                                </div>
                            </div>
                            <!-- MOM状态警告提示 -->
                            <div class="status-hint" v-if="formData.productNo && momProductStatus.errorMsg">
                                <el-alert :title="`MOM状态查询失败：${momProductStatus.errorMsg}，请手动选择再起始工位`" type="warning"
                                    show-icon :closable="false" />
                            </div>
                            <div class="status-hint"
                                v-if="formData.productNo && momProductStatus.stationNotInList && !momProductStatus.errorMsg">
                                <el-alert
                                    :title="`MOM返回的工位【${momProductStatus.opStation}】不在当前返修上线口的再起始工位清单中，请手动选择或更换返修上线口`"
                                    type="warning" show-icon :closable="false" />
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 下半部分：再起始工位与返修上线口选择 -->
                <div class="bottom-section">
                    <div class="card">
                        <div class="form">
                            <div class="form-row">
                                <div class="form-item">
                                    <label class="form-label">返修上线口：</label>
                                    <el-input v-model.trim="repairUplineInput" placeholder="扫描返修上线口二维码"
                                        @keyup.enter="handleQueryRepairUpline" @input="handleRepairUplineInput"
                                        @blur="handleRepairUplineBlur" clearable @clear="handleClearRepairUpline"
                                        class="w-100">
                                        <template #prefix>
                                            <el-icon>
                                                <Rank />
                                            </el-icon>
                                        </template>
                                    </el-input>
                                </div>
                                <div class="form-item">
                                    <label class="form-label">再起始工位：</label>
                                    <el-select v-model="selectedRestartStation" placeholder="请选择再起始工位" filterable
                                        clearable class="w-100">
                                        <template #prefix>
                                            <el-icon>
                                                <Location />
                                            </el-icon>
                                        </template>
                                        <el-option v-for="item in stationList" :key="item.value" :label="item.label"
                                            :value="item.value" />
                                    </el-select>
                                </div>
                                <div class="form-item">
                                    <label class="form-label">返修描述：</label>
                                    <el-input v-model.trim="formData.repairDesc" placeholder="请输入返修描述" clearable
                                        prefix-icon="EditPen" />
                                </div>
                                <div class="form-item form-actions">
                                    <!-- <el-button type="success" :disabled="!canEmptyUpline" @click="handleEmptyUplineClick" icon="Box">空托盘上线</el-button> -->
                                    <el-button type="warning" @click="handleOpenCreateRepairDialog"
                                        icon="Plus">创建返修记录</el-button>
                                    <el-button type="primary" :disabled="!canUpline" @click="handleUplineClick"
                                        icon="Upload">返修上线</el-button>
                                </div>
                            </div>
                            <div class="status-hint" v-if="statusNotice">
                                <el-alert :title="statusNotice" type="warning" show-icon :closable="false" />
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 二次确认弹窗 -->
            <el-dialog v-model="confirmDialog.visible" title="返修上线确认" width="560px" :close-on-click-modal="false">
                <el-descriptions :column="1" border>
                    <el-descriptions-item label="产品编号">{{ formData.productNo }}</el-descriptions-item>
                    <el-descriptions-item label="订单号">{{ formData.orderNo }}</el-descriptions-item>
                    <el-descriptions-item label="产品型号">{{ formData.productType }}</el-descriptions-item>
                    <el-descriptions-item label="不合格工位">{{ formData.ngStation }}</el-descriptions-item>
                    <el-descriptions-item label="不合格时间">{{ formData.ngTime }}</el-descriptions-item>
                    <el-descriptions-item label="返修状态">
                        <template v-if="repairStatusInfo.status !== null">
                            <el-tag :type="repairStatusInfo.type">{{ repairStatusInfo.text }}</el-tag>
                        </template>
                        <template v-else>-</template>
                    </el-descriptions-item>
                    <el-descriptions-item label="返修上线时间">{{ formData.repairUplineTime || '-' }}</el-descriptions-item>
                    <el-descriptions-item label="再起始工位到达时间">{{ formData.restartArriveTime || '-'
                    }}</el-descriptions-item>
                    <el-descriptions-item label="返修描述">{{ formData.repairDesc || '-' }}</el-descriptions-item>
                    <el-descriptions-item label="再起始工位">{{ selectedRestartStationLabel }}</el-descriptions-item>
                    <el-descriptions-item label="返修上线口">{{ selectedRepairUplineStationLabel }}</el-descriptions-item>
                </el-descriptions>
                <template #footer>
                    <div style="display:flex; justify-content:flex-end; gap:8px;">
                        <el-button @click="confirmDialog.visible = false" icon="Close">取 消</el-button>
                        <el-button type="primary" :loading="confirmDialog.loading" @click="confirmPublish"
                            icon="Upload">确 认 上 线</el-button>
                    </div>
                </template>
            </el-dialog>

            <!-- 创建返修记录弹窗 -->
            <el-dialog v-model="createRepairDialog.visible" title="创建返修记录" width="500px" :close-on-click-modal="false">
                <el-form :model="createRepairForm" label-width="100px">
                    <el-form-item label="产品码值">
                        <el-input v-model.trim="createRepairForm.codeValue" placeholder="请扫描或输入产品码值" clearable
                            prefix-icon="Scanner" @keyup.enter="handleCreateRepairSubmit" />
                    </el-form-item>
                    <el-form-item label="不合格工位">
                        <el-select v-model="createRepairForm.ngStation" placeholder="请选择不合格工位" filterable clearable
                            class="w-100" :loading="createRepairStationLoading">
                            <el-option v-for="item in createRepairStationList" :key="item.value" :label="item.label"
                                :value="item.value" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="返修状态">
                        <el-select v-model="createRepairForm.repairStatus" placeholder="请选择返修状态" class="w-100">
                            <el-option label="未下线" :value="0" />
                            <el-option label="已下线" :value="1" />
                        </el-select>
                    </el-form-item>
                </el-form>
                <template #footer>
                    <div style="display:flex; justify-content:flex-end; gap:8px;">
                        <el-button @click="createRepairDialog.visible = false" icon="Close">取 消</el-button>
                        <el-button type="primary" :loading="createRepairDialog.loading"
                            @click="handleCreateRepairSubmit" icon="Check">确 认 创 建</el-button>
                    </div>
                </template>
            </el-dialog>

            <!-- 空托盘上线确认弹窗 -->
            <el-dialog v-model="emptyUplineDialog.visible" title="空托盘上线确认" width="450px" :close-on-click-modal="false">
                <el-alert title="确认在该返修上线口进行空托盘上线操作？" type="info" show-icon :closable="false" />
                <el-descriptions :column="1" border style="margin-top: 16px;">
                    <el-descriptions-item label="返修上线口">{{ selectedRepairUplineStationLabel }}</el-descriptions-item>
                </el-descriptions>
                <template #footer>
                    <div style="display:flex; justify-content:flex-end; gap:8px;">
                        <el-button @click="emptyUplineDialog.visible = false" icon="Close">取 消</el-button>
                        <el-button type="success" :loading="emptyUplineDialog.loading" @click="confirmEmptyUpline"
                            icon="Box">确 认 上 线</el-button>
                    </div>
                </template>
            </el-dialog>
        </template>

        <div v-else class="auth-loading">
            <i class="el-icon-loading"></i>
            <p>正在进行权限验证...</p>
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, inject, computed, onBeforeUnmount, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import PermissionVerify from '@/components/PermissionVerify.vue'
import Cookie from 'js-cookie'
import { useRouter } from 'vue-router'
import { Location, Rank, Tickets, Memo, Document, Clock, EditPen, Upload, Close, Box, CircleCheck, CircleClose, Warning, Plus, Check, Refresh } from '@element-plus/icons-vue'
import axios from 'axios'
import { Mqtt } from '@/utils/mqtt.js'

// 注入后端执行方法
const ExecDatabaseByParam = inject('ExecDatabaseByParam')
const CreateData = inject('CreateData')
const ExecDatabase = inject('ExecDatabase')

// 路由
const router = useRouter()

// 返回导航首页
const navigateHome = () => {
    router.push('/')
}

// 权限
const isAuthenticated = ref(false)
const permissionVerify = ref(null)
const userInfo = ref({})
const loginUserName = computed(() => Cookie.get('userName') || userInfo.value.姓名 || userInfo.value.userName || '-')

// 表单与数据
const scanCode = ref('')
const loadingScan = ref(false)
const formData = reactive({
    id: null,
    orderNo: '',
    productNo: '',
    productType: '',
    productTypeCode: null,
    ngStation: '',
    ngTime: '',
    repairDesc: '',
    repairStatus: null,
    repairUplineStation: '',
    repairUplineTime: '',
    restartArriveTime: ''
})

// 下拉与选择
const stationList = ref([]) // 再起始工位下拉
const uplineStationList = ref([]) // 返修上线口下拉
const selectedRestartStation = ref('')
const selectedRepairUplineStation = ref('')
const repairUplineInput = ref('')

// MOM产品状态查询相关
const momProductStatus = reactive({
    loading: false,
    success: false,
    productStatus: '',  // 产品状态（如：排队中、活动等）
    opStation: '',      // 工位号
    errorMsg: '',       // 错误信息
    stationNotInList: false  // 工位是否不在返修上线工位清单中
})

const statusMeta = {
    0: { text: '未下线', type: 'danger' },
    1: { text: '已下线', type: 'warning' },
    2: { text: '回流中', type: 'info' },
    3: { text: '已完成', type: 'success' }
}

const repairStatusInfo = computed(() => {
    const rawStatus = formData.repairStatus
    if (rawStatus === null || rawStatus === undefined || rawStatus === '') {
        return { status: null, text: '-', type: 'info' }
    }
    const numericStatus = Number(rawStatus)
    const meta = statusMeta[numericStatus] || { text: `未知状态(${rawStatus})`, type: 'info' }
    return { status: numericStatus, ...meta }
})

const getLabelByValue = (listRef, value) => {
    if (!value) return ''
    const item = listRef.value.find(x => String(x.value) === String(value))
    return item ? item.label : value
}

const repairUplineStationLabel = computed(() => getLabelByValue(uplineStationList, formData.repairUplineStation))
const selectedRestartStationLabel = computed(() => getLabelByValue(stationList, selectedRestartStation.value))
const selectedRepairUplineStationLabel = computed(() => getLabelByValue(uplineStationList, selectedRepairUplineStation.value))

const statusNotice = computed(() => {
    if (!formData.productNo) return ''
    const info = repairStatusInfo.value
    if (info.status === null) return ''
    if (info.status !== 1) {
        return `当前返修状态为【${info.text}】，无法进行返修上线操作。`
    }
    if (!selectedRestartStation.value || !selectedRepairUplineStation.value) {
        return '请选择再起始工位与返修上线口后再操作。'
    }
    return ''
})

const canUpline = computed(() => {
    const statusOk = repairStatusInfo.value.status === 1
    return statusOk && !!(formData.productNo && selectedRestartStation.value && selectedRepairUplineStation.value)
})

const canEmptyUpline = computed(() => {
    return !!selectedRepairUplineStation.value
})

// 获取MOM产品状态
const fetchMomProductStatus = async () => {
    if (!formData.productNo) {
        return
    }

    momProductStatus.loading = true
    momProductStatus.success = false
    momProductStatus.errorMsg = ''
    momProductStatus.stationNotInList = false

    try {
        const response = await axios.post(
            `${window.g.API_MES_Controller_URL}/GetSfcStatusAndOperation`,
            {
                MsgId: Date.now().toString(),
                Barcode: formData.productNo
            },
            { timeout: 10000 }
        )

        const data = response.data
        if (data.Code === '200' || data.Code === 200) {
            momProductStatus.success = true
            momProductStatus.productStatus = data.ProductStatus || ''
            momProductStatus.opStation = data.OpStation || ''

            // 检查返回的工位是否在再起始工位列表中
            if (momProductStatus.opStation && stationList.value.length > 0) {
                const found = stationList.value.some(x => String(x.value) === String(momProductStatus.opStation))
                if (!found) {
                    momProductStatus.stationNotInList = true
                    ElMessage.warning(`MOM返回的工位【${momProductStatus.opStation}】不在当前返修上线口的再起始工位清单中，请手动选择或更换返修上线口`)
                } else {
                    // 自动设置再起始工位
                    selectedRestartStation.value = momProductStatus.opStation
                }
            } else if (momProductStatus.opStation) {
                // 工位列表还没加载，先记录，后面会检查
                momProductStatus.stationNotInList = true
            }
        } else {
            momProductStatus.success = false
            momProductStatus.errorMsg = data.Message || '查询失败'
            ElMessage.warning(`获取MOM产品状态失败：${momProductStatus.errorMsg}，请手动选择再起始工位`)
        }
    } catch (e) {
        console.error('获取MOM产品状态失败:', e)
        momProductStatus.success = false
        momProductStatus.errorMsg = e.message || '网络请求失败'
        ElMessage.warning(`获取MOM产品状态失败：${momProductStatus.errorMsg}，请手动选择再起始工位`)
    } finally {
        momProductStatus.loading = false
    }
}

// 重置MOM产品状态
const resetMomProductStatus = () => {
    momProductStatus.loading = false
    momProductStatus.success = false
    momProductStatus.productStatus = ''
    momProductStatus.opStation = ''
    momProductStatus.errorMsg = ''
    momProductStatus.stationNotInList = false
}

// MQTT连接状态
const mqttStatus = reactive({
    show: false,
    type: 'success', // success, error, warning
    message: '',
    icon: 'CircleCheck'
})

// MQTT
let mqttTimeout = null
let mqttClient = null
const mqttConnection = reactive({
    host: window.g.mqttIP,
    port: window.g.mqttPortNumber,
    endpoint: '/mqtt',
    clean: true,
    connectTimeout: 4000,
    reconnectPeriod: 4000,
    clientId: '',
    username: '',
    password: ''
})
const publication = reactive({ topic: window.g.mqttPublishTopic, qos: 0, payload: '' })
const subscription = reactive({ topic: '', qos: 0 })

const createMqttConnection = () => {
    try {
        if (mqttClient) {
            mqttClient.destroyConnection()
        }

        // 显示连接中状态
        mqttStatus.show = true
        mqttStatus.type = 'warning'
        mqttStatus.icon = 'Warning'
        mqttStatus.message = 'MQTT连接中...'

        mqttClient = new Mqtt(mqttConnection)
        mqttClient.createConnection()

        mqttClient.client.on('connect', () => {
            console.log('MQTT connected in repairOnline')
            mqttStatus.show = true
            mqttStatus.type = 'success'
            mqttStatus.icon = 'CircleCheck'
            mqttStatus.message = 'MQTT已连接'
            // 3秒后自动隐藏成功提示
            setTimeout(() => {
                if (mqttStatus.type === 'success') {
                    mqttStatus.show = false
                }
            }, 3000)
        })

        mqttClient.client.on('reconnect', () => {
            console.log('MQTT reconnecting...')
            mqttStatus.show = true
            mqttStatus.type = 'warning'
            mqttStatus.icon = 'Warning'
            mqttStatus.message = 'MQTT重新连接中...'
        })

        mqttClient.client.on('disconnect', () => {
            console.log('MQTT disconnected')
            mqttStatus.show = true
            mqttStatus.type = 'error'
            mqttStatus.icon = 'CircleClose'
            mqttStatus.message = 'MQTT连接已断开，请检查网络或联系管理员'
        })

        mqttClient.client.on('offline', () => {
            console.log('MQTT offline')
            mqttStatus.show = true
            mqttStatus.type = 'error'
            mqttStatus.icon = 'CircleClose'
            mqttStatus.message = 'MQTT离线，请检查网络连接'
        })
        // 订阅专属主题：MES/InstantMessaging/CATL_PDC
        subscription.topic = window.g.mqttSubscriptionTopic
        mqttClient.doSubscribe(subscription)
        mqttClient.client.on('error', err => {
            console.log('MQTT error:', err)
            mqttStatus.show = true
            mqttStatus.type = 'error'
            mqttStatus.icon = 'CircleClose'
            mqttStatus.message = `MQTT连接错误: ${err.message || '未知错误'}，请联系管理员`
        })
        mqttClient.client.on('message', (topic, message) => {
            console.log('MQTT message:', message.toString())
            const parts = message.toString().split('|')
            const source = parts[0]
            const command = parts[1]
            if (command !== 'HeartBeatPLC') {
                console.log('MQTT message:', message.toString())
            }
            if (source === 'MES' && command === 'RepairUplineMES') {
                const returnedUplineStation = (parts[2] || '').trim()
                const returnedProductNo = (parts[3] || '').trim()
                if (
                    returnedUplineStation === String(selectedRepairUplineStation.value || '').trim() &&
                    returnedProductNo === String(formData.productNo || '').trim()
                ) {
                    onMqttRepairUplineSuccess()
                }
            }
            if (source === 'MES' && command === 'EmptyUplineMES') {
                const returnedUplineStation = (parts[2] || '').trim()
                const returnedValue = (parts[3] || '').trim()
                if (
                    returnedUplineStation === String(selectedRepairUplineStation.value || '').trim() &&
                    returnedValue === '999'
                ) {
                    onMqttEmptyUplineSuccess()
                }
            }
        })
    } catch (e) {
        console.error('createMqttConnection error:', e)
        mqttStatus.show = true
        mqttStatus.type = 'error'
        mqttStatus.icon = 'CircleClose'
        mqttStatus.message = `MQTT初始化失败: ${e.message || '未知错误'}，请刷新页面或联系管理员`
    }
}

const onMqttRepairUplineSuccess = async () => {
    try {
        clearTimeout(mqttTimeout)
        confirmDialog.loading = false
        confirmDialog.visible = false

        // 成功回执后，调用存储过程：MES_工位返修记录_上线口增加
        // 参数定义: @ID, @返修上线口, @再起始工位, @返修描述
        const param = []
        param[0] = ['ID', formData.id || 0]
        param[1] = ['返修上线口', selectedRepairUplineStation.value || '']
        param[2] = ['再起始工位', selectedRestartStation.value || '']
        param[3] = ['返修描述', formData.repairDesc || '']

        const data = CreateData('12', 'MES_工位返修记录_上线口增加', param)
        const res = await ExecDatabase(data)
        if (res.data && res.data.length >= 0) {
            if (res.data[0].result === "1") {
                ElMessage.success('返修上线成功，已记录数据库')
            } else {
                ElMessage.error('返修上线成功，记录数据库失败 请重发请求上线操作！')
            }
            resetForm(false)
        } else {
            ElMessage.warning('返修上线成功，但数据库记录返回异常，请重发请求上线操作！')
        }
    } catch (e) {
        ElMessage.error('数据库记录失败，请联系管理员')
    }
}

const onMqttEmptyUplineSuccess = async () => {
    try {
        clearTimeout(mqttTimeout)
        emptyUplineDialog.loading = false
        emptyUplineDialog.visible = false
        ElMessage.success('空托盘上线成功')
    } catch (e) {
        console.error('空托盘上线回执处理失败:', e)
    }
}

// 扫码处理：调用 MES_工位返修记录_上线扫码
const handleScan = async () => {
    if (!scanCode.value) {
        ElMessage.warning('请先扫码或输入条码')
        return
    }
    loadingScan.value = true
    try {
        const param = []
        param[0] = ['码值', scanCode.value]
        const data = CreateData('11', 'MES_工位返修记录_上线扫码', param)
        const res = await ExecDatabase(data)

        const rows = Array.isArray(res.data) ? res.data : []
        if (!rows.length) {
            const firstRow = res.data && res.data[0]
            const message = (firstRow && firstRow.msg) || '未查询到该产品返修记录'
            ElMessage.warning(message)
            clearProduct()
            return
        }
        const row = rows[0]
        if (row.msg) {
            ElMessage.error(row.msg)
            clearProduct()
            return
        }
        formData.id = row.ID
        formData.productNo = row.产品编号 || ''
        formData.productType = row.产品型号 || ''
        formData.productTypeCode = row.型号代码 !== undefined && row.型号代码 !== null ? Number(row.型号代码) : null
        formData.orderNo = row.订单号 || ''
        formData.ngStation = row.不合格工位 || ''
        formData.ngTime = row.不合格时间 || ''
        formData.repairDesc = row.返修描述 || ''
        formData.repairStatus = row.返修状态 !== undefined && row.返修状态 !== null && row.返修状态 !== '' ? Number(row.返修状态) : null
        formData.repairUplineStation = row.返修上线口 || ''
        formData.repairUplineTime = row.返修上线时间 || ''
        formData.restartArriveTime = row.再起始工位到达时间 || ''
        selectedRepairUplineStation.value = row.返修上线口 || ''
        if (selectedRepairUplineStation.value) {
            const item = uplineStationList.value.find(x => String(x.value) === String(selectedRepairUplineStation.value))
            repairUplineInput.value = item ? item.label : selectedRepairUplineStation.value
        } else {
            repairUplineInput.value = ''
        }
        selectedRestartStation.value = row.再起始工位 || formData.ngStation || ''

        // 扫码成功后，自动获取MOM产品状态
        resetMomProductStatus()
        if (formData.productNo) {
            await fetchMomProductStatus()
        }
    } catch (e) {
        console.error('上线扫码存储过程失败:', e)
        ElMessage.error('查询失败')
    } finally {
        loadingScan.value = false
    }
}

const clearProduct = () => {
    formData.orderNo = ''
    formData.productNo = ''
    formData.productType = ''
    formData.productTypeCode = null
    formData.ngStation = ''
    formData.ngTime = ''
    formData.repairDesc = ''
    formData.repairStatus = null
    formData.repairUplineStation = ''
    formData.repairUplineTime = ''
    formData.restartArriveTime = ''
    scanCode.value = ''
    resetMomProductStatus()
}

const resetForm = (clearScan = true) => {
    if (clearScan) scanCode.value = ''
    clearProduct()
    selectedRestartStation.value = ''
    selectedRepairUplineStation.value = ''
    repairUplineInput.value = ''
    stationList.value = []
}

// 创建返修记录弹窗
const createRepairDialog = reactive({ visible: false, loading: false })
const createRepairForm = reactive({ codeValue: '', ngStation: '', repairStatus: 1 })
const createRepairStationList = ref([])
const createRepairStationLoading = ref(false)

// 打开创建返修记录弹窗
const handleOpenCreateRepairDialog = async () => {
    createRepairForm.codeValue = ''
    createRepairForm.ngStation = ''
    createRepairForm.repairStatus = 1
    createRepairDialog.visible = true
    await loadCreateRepairStationList()
}

// 加载工位列表（来源于 MES_计划BOM_工位与名称_查询）
const loadCreateRepairStationList = async () => {
    createRepairStationLoading.value = true
    try {
        const res = await ExecDatabaseByParam('11', 'MES_计划BOM_工位与名称_查询', [])
        if (res.data && res.data.length > 0) {
            createRepairStationList.value = res.data.map(x => ({
                label: `${x.工位号} - ${x.工位名称 || ''}`,
                value: x.工位号
            }))
        } else {
            createRepairStationList.value = []
        }
    } catch (e) {
        console.error('加载工位列表失败:', e)
        ElMessage.error('加载工位列表失败')
        createRepairStationList.value = []
    } finally {
        createRepairStationLoading.value = false
    }
}

// 提交创建返修记录
const handleCreateRepairSubmit = async () => {
    if (!createRepairForm.codeValue) {
        ElMessage.warning('请输入产品码值')
        return
    }
    if (!createRepairForm.ngStation) {
        ElMessage.warning('请选择不合格工位')
        return
    }
    if (createRepairForm.repairStatus === null || createRepairForm.repairStatus === undefined) {
        ElMessage.warning('请选择返修状态')
        return
    }
    createRepairDialog.loading = true
    try {
        const param = []
        param[0] = ['码值', createRepairForm.codeValue]
        param[1] = ['不合格工位', createRepairForm.ngStation]
        param[2] = ['返修状态', createRepairForm.repairStatus]
        const data = CreateData('11', 'MES_工位返修记录_创建返修记录', param)
        const res = await ExecDatabase(data)
        if (res.data && res.data.length > 0) {
            const row = res.data[0]
            if (row.result === 1 || row.result === '1') {
                ElMessage.success('创建返修记录成功')
                createRepairDialog.visible = false
                createRepairForm.codeValue = ''
                createRepairForm.ngStation = ''
                createRepairForm.repairStatus = 1
            } else {
                ElMessage.error(row.msg || '创建返修记录失败')
            }
        } else {
            ElMessage.error('创建返修记录失败')
        }
    } catch (e) {
        console.error('创建返修记录失败:', e)
        ElMessage.error('创建返修记录失败')
    } finally {
        createRepairDialog.loading = false
    }
}

// 上线点击 -> 弹窗确认
const confirmDialog = reactive({ visible: false, loading: false })
const handleUplineClick = async () => {
    if (!canUpline.value) {
        ElMessage.warning('请完善产品与工位选择')
        return
    }

    // 检查MOM产品状态，如果不是"排队中"则重点提示
    if (momProductStatus.success && momProductStatus.productStatus && momProductStatus.productStatus !== '排队中') {
        try {
            await ElMessageBox.confirm(
                `当前MOM产品状态为【${momProductStatus.productStatus}】，不是"排队中"状态！\n\n确定要继续返修上线吗？`,
                '⚠️ 状态警告',
                {
                    confirmButtonText: '确定继续',
                    cancelButtonText: '取消',
                    type: 'warning',
                    dangerouslyUseHTMLString: false
                }
            )
        } catch {
            // 用户取消
            return
        }
    }

    confirmDialog.visible = true
}

// 空托盘上线
const emptyUplineDialog = reactive({ visible: false, loading: false })
const handleEmptyUplineClick = () => {
    if (!canEmptyUpline.value) {
        ElMessage.warning('请先选择返修上线口')
        return
    }
    emptyUplineDialog.visible = true
}

const confirmEmptyUpline = async () => {
    try {
        emptyUplineDialog.loading = true
        const payload = `WEB|EmptyUplineMES|${selectedRepairUplineStation.value}|1`
        publication.topic = window.g.mqttPublishTopic
        publication.payload = payload
        const ok = mqttClient?.doPublish(publication)
        if (ok) {
            ElMessage.success('空托盘上线请求已发送，等待回执...')
            mqttTimeout = setTimeout(() => {
                emptyUplineDialog.loading = false
                ElMessage.error('空托盘上线超时，未收到后端确认消息 请重试')
            }, 10000)
        } else {
            ElMessage.error('空托盘上线消息发送失败')
            emptyUplineDialog.loading = false
        }
    } catch (e) {
        console.error('confirmEmptyUpline error:', e)
        ElMessage.error('空托盘上线消息发送异常')
        emptyUplineDialog.loading = false
    }
}

// 确认发布MQTT：WEB|RepairUplineMES|返修上线口工位|再起始工位号^产品编号^订单号^产品型号^产品型号代码
const confirmPublish = async () => {
    try {
        confirmDialog.loading = true
        // 格式：WEB|RepairUplineMES|返修上线口工位|再起始工位号^产品编号^订单号^产品型号^产品型号代码
        const payload = `WEB|RepairUplineMES|${selectedRepairUplineStation.value}|${selectedRestartStation.value}^${formData.productNo}^${formData.orderNo}^${formData.productType}^${formData.productTypeCode || 0}`
        publication.topic = window.g.mqttPublishTopic
        publication.payload = payload
        const ok = mqttClient?.doPublish(publication)
        if (ok) {
            ElMessage.success('上线请求已发送，等待回执...')
            mqttTimeout = setTimeout(() => {
                confirmDialog.loading = false
                ElMessage.error('返修上线超时，未收到后端确认消息 请重试')
            }, 10000)
        } else {
            ElMessage.error('上线消息发送失败')
            confirmDialog.loading = false
        }
    } catch (e) {
        console.error('confirmPublish error:', e)
        ElMessage.error('上线消息发送异常')
        confirmDialog.loading = false
    }
}

// 查询返修上线口
const handleQueryRepairUpline = async () => {
    if (!repairUplineInput.value) return
    try {
        const param = []
        param[0] = ['OpCode', repairUplineInput.value]
        const res = await ExecDatabaseByParam('11', 'MES_工位返修记录_编号查询上线口', param)

        if (res.data && res.data.length > 0) {
            const row = res.data[0]
            selectedRepairUplineStation.value = row.工位号
            repairUplineInput.value = `${row.工位号} - ${row.工位名称 || ''}`
        } else {
            ElMessage.warning('工位码不正确')
            repairUplineInput.value = ''
            selectedRepairUplineStation.value = ''
        }
    } catch (e) {
        console.error('查询返修上线口失败:', e)
        ElMessage.error('查询返修上线口失败')
        repairUplineInput.value = ''
        selectedRepairUplineStation.value = ''
    }
}

const handleClearRepairUpline = () => {
    repairUplineInput.value = ''
    selectedRepairUplineStation.value = ''
}

const handleRepairUplineInput = () => {
    // 当用户手动输入修改时，清空已选中的工位ID，确保必须回车查询才能选中
    selectedRepairUplineStation.value = ''
}

const handleRepairUplineBlur = () => {
    // 焦点离开时，如果未查询到有效工位（即selectedRepairUplineStation为空），则清空输入框
    if (!selectedRepairUplineStation.value) {
        repairUplineInput.value = ''
    }
}

// 加载工位下拉
const loadUplineStationList = async () => {
    try {
        const resUpline = await ExecDatabaseByParam('11', 'MES_计划BOM_工位与名称_查询_返修上线口', [])
        if (resUpline.data && resUpline.data.length > 0) {
            uplineStationList.value = resUpline.data.map(x => ({
                label: `${x.工位号} - ${x.工位名称 || ''}`,
                value: x.工位号
            }))
        } else {
            uplineStationList.value = []
        }
    } catch (e) {
        console.error('加载返修上线口列表失败:', e)
        ElMessage.error('加载返修上线口列表失败')
    }
}

const loadRestartStationList = async (repairUpline) => {
    try {
        if (!repairUpline) {
            stationList.value = []
            selectedRestartStation.value = ''
            return
        }
        const param = []
        param[0] = ['返修口', repairUpline]
        const res = await ExecDatabaseByParam('11', 'MES_计划BOM_工位与名称_查询_返修上线口_对应上线工位', param)
        if (res.data && res.data.length > 0) {
            stationList.value = res.data.map(x => ({
                label: `${x.工位号} - ${x.工位名称 || ''}`,
                value: x.工位号
            }))
        } else {
            stationList.value = []
        }
        if (
            selectedRestartStation.value &&
            !stationList.value.some(x => String(x.value) === String(selectedRestartStation.value))
        ) {
            selectedRestartStation.value = ''
        }

        // 工位列表加载完成后，重新检查MOM返回的工位是否在列表中
        if (momProductStatus.success && momProductStatus.opStation && stationList.value.length > 0) {
            const found = stationList.value.some(x => String(x.value) === String(momProductStatus.opStation))
            momProductStatus.stationNotInList = !found
            if (found && !selectedRestartStation.value) {
                // 如果MOM工位在列表中且当前未选择，自动选中
                selectedRestartStation.value = momProductStatus.opStation
            }
        }
    } catch (e) {
        console.error('加载再起始工位列表失败:', e)
        ElMessage.error('加载再起始工位列表失败')
        stationList.value = []
    }
}

// 登录与初始化
const checkPermission = async () => {
    try {
        const cookieUserId = Cookie.get('userId')
        const cookieUserName = Cookie.get('userName')
        if (cookieUserId && cookieUserName) {
            isAuthenticated.value = true
            userInfo.value = { UserID: cookieUserId, 姓名: cookieUserName }
            ElMessage.success(`欢迎 ${cookieUserName} 登录系统`)
            await initPage()
            return
        }

        const result = await permissionVerify.value.show({
            title: '返修上线登录',
            promptText: '请刷卡进行身份验证',
            permissionLevel: '操作工'
        })
        if (result.success) {
            isAuthenticated.value = true
            userInfo.value = result.data
            ElMessage.success(`欢迎 ${result.data.姓名 || result.data.userName || '用户'} 登录系统`)
            await initPage()
        }
    } catch (e) {
        if (e.cancelled) {
            ElMessage.warning('已取消登录')
        } else {
            ElMessage.error('权限验证失败')
        }
    }
}

const initPage = async () => {
    await loadUplineStationList()
    if (selectedRepairUplineStation.value) {
        await loadRestartStationList(selectedRepairUplineStation.value)
    }
    // 初始化MQTT（订阅使用选择的上线口工位号，若未选则先不订阅，待选择后重建）
    createMqttConnection()
}

// 退出登录
const handleLogout = async () => {
    try {
        await ElMessageBox.confirm('确定要退出登录吗？', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' })
        isAuthenticated.value = false
        userInfo.value = {}
        resetForm()
        Cookie.remove('userId')
        Cookie.remove('userName')
        router.push('/')
    } catch { }
}

// 监听返修上线口变化，重新订阅该口的主题
const lastSubscribed = ref('')
const handleReSubscribe = () => {
    if (!mqttClient || !mqttClient.client) return
    const topic = window.g.mqttSubscriptionTopic + "/RepairUplinePAD"
    if (lastSubscribed.value && lastSubscribed.value !== topic) {
        mqttClient.doUnSubscribe({ topic: lastSubscribed.value })
    }
    subscription.topic = topic
    mqttClient.doSubscribe(subscription)
    lastSubscribed.value = topic
}

// watch: 选择返修上线口变化
watch(
    () => selectedRepairUplineStation.value,
    async (newVal) => {
        await loadRestartStationList(newVal)
        if (isAuthenticated.value) handleReSubscribe()
    }
)

watch(() => confirmDialog.visible, (newVal) => {
    if (!newVal) {
        clearTimeout(mqttTimeout)
        confirmDialog.loading = false
    }
})

watch(() => emptyUplineDialog.visible, (newVal) => {
    if (!newVal) {
        clearTimeout(mqttTimeout)
        emptyUplineDialog.loading = false
    }
})

onMounted(() => {
    // 注入方法
    setTimeout(() => {
        if (permissionVerify.value) {
            permissionVerify.value.setCreateData(CreateData)
            permissionVerify.value.setExecDatabase(ExecDatabase)
            permissionVerify.value.setStore({
                state: {
                    station: { stationNumber: '' },
                    user: { name: Cookie.get('userName') || '' }
                }
            })
            checkPermission()
        } else {
            ElMessage.error('权限验证组件初始化失败')
        }
    }, 300)
})

onBeforeUnmount(() => {
    try {
        if (mqttClient) {
            mqttClient.destroyConnection()
        }
    } catch { }
})
</script>

<style lang="scss" scoped>
.app-container {
    width: 100%;
    height: 100vh;
    background: #f0f2f5;
    overflow: hidden;
    display: flex;
    flex-direction: column;
}

.scroll-container {
    flex: 1;
    overflow-y: auto;
    overflow-x: hidden;
    /* 增加底部padding，避免内容贴底 */
    padding-bottom: 20px;
}

.header-section {
    background: linear-gradient(135deg, #2c3e50 0%, #4ca1af 100%);
    color: white;
    padding: 12px 16px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    flex-shrink: 0;
}

.header-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.page-title {
    font-size: 20px;
    font-weight: 600;
    margin: 0 0 4px 0;
}

.page-subtitle {
    font-size: 12px;
    opacity: 0.9;
    margin: 0;
}

.top-section,
.bottom-section {
    padding: 12px;
}

.card {
    background: white;
    border-radius: 8px;
    padding: 16px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.form {
    display: flex;
    flex-direction: column;
    gap: 16px;
}

.form-row {
    display: flex;
    gap: 16px;
    align-items: flex-start;
}

.form-item {
    display: flex;
    align-items: center;
    flex: 1;
}

.form-item.form-actions {
    flex: none;
    justify-content: flex-end;
    gap: 12px;
}

.form-label {
    width: 135px;
    flex-shrink: 0;
    text-align: right;
    color: #606266;
    font-size: 14px;
    font-weight: 500;
    margin-right: 8px;
    white-space: nowrap;
}

.w-100 {
    width: 100%;
}

.mqtt-status-bar {
    padding: 8px 16px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 14px;
    transition: all 0.3s ease;
}

.mqtt-status-bar.success {
    background-color: #f0f9ff;
    color: #67c23a;
    border-bottom: 1px solid #b3e19d;
}

.mqtt-status-bar.error {
    background-color: #fef0f0;
    color: #f56c6c;
    border-bottom: 1px solid #fab6b6;
}

.mqtt-status-bar.warning {
    background-color: #fdf6ec;
    color: #e6a23c;
    border-bottom: 1px solid #f5dab1;
}

.mqtt-status-content {
    display: flex;
    align-items: center;
    gap: 8px;
}

.status-icon {
    font-size: 16px;
}

.auth-loading {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    height: 100vh;
    color: #909399;
}

@media (max-width: 1200px) {
    .form-row {
        flex-wrap: wrap;
    }

    .form-item {
        min-width: 100%;
        margin-bottom: 4px;
    }

    /* 在小屏幕上，label可以稍微左对齐或者保持右对齐但调整宽度 */
    .form-label {
        width: 140px;
        text-align: left;
    }
}

/* 竖屏PAD优化：高度自适应、控件放大可点性 */
@media (orientation: portrait) {
    .app-container {
        height: 100dvh;
    }

    .page-title {
        font-size: 18px;
    }

    .form-label {
        width: 140px;
        font-size: 15px;
    }

    :deep(.el-input__wrapper) {
        min-height: 42px;
    }

    :deep(.el-input__icon) {
        font-size: 16px;
    }

    :deep(.el-select .el-input__wrapper) {
        min-height: 42px;
    }

    :deep(.el-button) {
        height: 42px;
    }

    :deep(.el-select__prefix) {
        align-items: center;
    }
}
</style>
