<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">OP431 Manual Static Out</p>
                    </div>
                    <div class="header-actions">
                        <div class="standard-panel">
                            <span class="standard-label">静置标准：</span>
                            <span class="standard-value">{{ displayMinutes(standardMinutes) }}</span>
                            <el-button type="primary" text circle @click="openStandardDialog" icon="Edit"
                                class="standard-edit" />
                        </div>
                        <div class="login-user">登录人：{{ loginUserName }}</div>
                        <el-button type="danger" icon="SwitchButton" @click="handleLogout" size="small">
                            退出登录
                        </el-button>
                    </div>
                </div>
            </div>

            <div class="scroll-container">
                <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="operation-section">
                    <div class="card main-card">
                        <div class="scan-area">
                            <div class="scan-row">
                                <label class="form-label">产品扫码：</label>
                                <el-input ref="scanInputRef" v-model.trim="productCode" placeholder="请扫描或输入产品码"
                                    clearable prefix-icon="Scanner" @keyup.enter="handleScanQuery"
                                    @clear="handleClearProduct" />
                                <el-button type="primary" :loading="scanLoading" :disabled="!canScan"
                                    @click="handleScanQuery" icon="Search">
                                    查询
                                </el-button>
                            </div>
                        </div>

                        <div class="result-summary" :class="summaryClass">
                            <div>
                                <div class="summary-title">{{ summaryTitle }}</div>
                                <div class="summary-text">{{ summaryText }}</div>
                            </div>
                            <div class="summary-tags" v-if="scanResult.productCode">
                                <el-tag :type="scanResult.partLoad ? 'success' : 'info'" size="large">
                                    {{ scanResult.partLoad ? 'PLC已申请上线' : 'PLC未申请上线' }}
                                </el-tag>
                                <el-tag :type="scanResult.canConfirm ? 'success' : 'warning'" size="large">
                                    {{ scanResult.canConfirm ? '允许确认上线' : '暂不可确认' }}
                                </el-tag>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="info-section">
                    <div class="card">
                        <div class="section-title">
                            <el-icon>
                                <Tickets />
                            </el-icon>
                            产品信息
                        </div>
                        <div class="info-grid">
                            <div class="info-item">
                                <span class="info-label">产品码</span>
                                <span class="info-value strong">{{ scanResult.productCode || '-' }}</span>
                            </div>
                            <div class="info-item">
                                <span class="info-label">订单号</span>
                                <span class="info-value">{{ scanResult.orderNo || '-' }}</span>
                            </div>
                            <div class="info-item">
                                <span class="info-label">产品型号</span>
                                <span class="info-value">{{ scanResult.productType || '-' }}</span>
                            </div>
                            <div class="info-item">
                                <span class="info-label">机型代码</span>
                                <span class="info-value">{{ scanResult.machineCode || '-' }}</span>
                            </div>
                        </div>
                    </div>

                    <div class="card">
                        <div class="section-title">
                            <el-icon>
                                <Clock />
                            </el-icon>
                            静置判定
                        </div>
                        <div class="metric-grid">
                            <div class="metric-item">
                                <span class="metric-label">最近前序工位</span>
                                <span class="metric-value">{{ scanResult.prevStation || '-' }}</span>
                            </div>
                            <div class="metric-item">
                                <span class="metric-label">开始静置时间</span>
                                <span class="metric-value">{{ scanResult.staticStartTime || '-' }}</span>
                            </div>
                            <div class="metric-item highlight">
                                <span class="metric-label">已静置</span>
                                <span class="metric-value">{{ displayMinutes(scanResult.staticMinutes) }}</span>
                            </div>
                            <div class="metric-item">
                                <span class="metric-label">本次标准</span>
                                <span class="metric-value">{{ displayMinutes(scanResult.minStaticMinutes) }}</span>
                            </div>
                            <div class="metric-item">
                                <span class="metric-label">PLC申请上线</span>
                                <el-tag :type="scanResult.partLoad ? 'success' : 'info'">
                                    {{ scanResult.partLoad ? '已申请' : '未申请' }}
                                </el-tag>
                            </div>
                            <div class="metric-item">
                                <span class="metric-label">后端判定</span>
                                <el-tag :type="scanResult.canConfirm ? 'success' : 'warning'">
                                    {{ scanResult.canConfirm ? '允许确认' : '禁止确认' }}
                                </el-tag>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="action-section">
                    <div class="card action-card">
                        <div class="action-copy">
                            <div class="action-title">确认上线</div>
                            <div class="action-desc">
                                条件满足后点击确认，等待系统返回上线结果。
                            </div>
                        </div>
                        <el-button type="success" size="large" :loading="confirmLoading" :disabled="!canConfirmOnline"
                            @click="handleConfirmClick" icon="Upload">
                            确认上线
                        </el-button>
                    </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="产品码">{{ scanResult.productCode || '-' }}</el-descriptions-item>
                    <el-descriptions-item label="订单号">{{ scanResult.orderNo || '-' }}</el-descriptions-item>
                    <el-descriptions-item label="产品型号">{{ scanResult.productType || '-' }}</el-descriptions-item>
                    <el-descriptions-item label="最近前序工位">{{ scanResult.prevStation || '-' }}</el-descriptions-item>
                    <el-descriptions-item label="开始静置时间">{{ scanResult.staticStartTime || '-'
                    }}</el-descriptions-item>
                    <el-descriptions-item label="已静置">{{ displayMinutes(scanResult.staticMinutes)
                    }}</el-descriptions-item>
                    <el-descriptions-item label="静置标准">{{ displayMinutes(scanResult.minStaticMinutes)
                    }}</el-descriptions-item>
                    <el-descriptions-item label="PLC申请上线">
                        <el-tag :type="scanResult.partLoad ? 'success' : 'info'">
                            {{ scanResult.partLoad ? '已申请' : '未申请' }}
                        </el-tag>
                    </el-descriptions-item>
                </el-descriptions>
                <template #footer>
                    <div class="dialog-footer">
                        <el-button @click="confirmDialog.visible = false" icon="Close">取 消</el-button>
                        <el-button type="primary" :loading="confirmLoading" @click="handleConfirmOnline" icon="Upload">
                            确 认 上 线
                        </el-button>
                    </div>
                </template>
            </el-dialog>

            <el-dialog v-model="standardDialog.visible" title="修改静置标准" width="420px" :close-on-click-modal="false">
                <el-form label-width="110px">
                    <el-form-item label="静置标准">
                        <el-input-number v-model="standardDialog.value" :min="0" :precision="1" :step="1"
                            controls-position="right" class="standard-input" />
                        <span class="dialog-unit">分钟</span>
                    </el-form-item>
                </el-form>
                <template #footer>
                    <div class="dialog-footer">
                        <el-button @click="standardDialog.visible = false" icon="Close">取 消</el-button>
                        <el-button type="primary" :loading="standardSaving" @click="handleSaveStandard" icon="Check">
                            保 存
                        </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, computed, inject, onBeforeUnmount, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Tickets, Clock } from '@element-plus/icons-vue'
import PermissionVerify from '@/components/PermissionVerify.vue'
import Cookie from 'js-cookie'
import { useRouter } from 'vue-router'
import { Mqtt } from '@/utils/mqtt.js'
import { logAdd } from '@/utils/log.js'

const OP_NAME = 'OP431'
const STANDARD_NAME = '手动静置标准时间'
const DEFAULT_STANDARD_MINUTES = 30
const PAD_TOPIC_SUFFIX = 'OP431PAD'

const ExecDatabase = inject('ExecDatabase')
const CreateData = inject('CreateData')
const ExecDatabaseByParam = inject('ExecDatabaseByParam')

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

const productCode = ref('')
const standardMinutes = ref(DEFAULT_STANDARD_MINUTES)
const standardSaving = ref(false)
const scanLoading = ref(false)
const confirmLoading = ref(false)
const confirmedSuccess = ref(false)
const standardDialog = reactive({ visible: false, value: DEFAULT_STANDARD_MINUTES })

const scanResult = reactive({
    success: false,
    productCode: '',
    orderNo: '',
    productType: '',
    machineCode: '',
    prevStation: '',
    staticStartTime: '',
    staticMinutes: '',
    minStaticMinutes: '',
    partLoad: false,
    canConfirm: false,
    message: '请扫描产品码查询静置信息'
})

const confirmDialog = reactive({ visible: false })
const mqttStatus = reactive({
    show: false,
    type: 'warning',
    message: 'MQTT未连接',
    icon: 'Warning'
})

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

const canScan = computed(() => !!productCode.value && !scanLoading.value)
const canConfirmOnline = computed(() => {
    return scanResult.success && scanResult.canConfirm && !!scanResult.productCode && !confirmedSuccess.value
})

const summaryClass = computed(() => {
    if (confirmedSuccess.value) return 'success'
    if (!scanResult.productCode) return 'idle'
    return scanResult.canConfirm ? 'success' : 'warning'
})

const summaryTitle = computed(() => {
    if (confirmedSuccess.value) return '确认上线成功'
    if (!scanResult.productCode) return '等待扫码'
    return scanResult.canConfirm ? '满足上线条件' : '暂不可上线'
})

const summaryText = computed(() => scanResult.message || '请扫描产品码查询静置信息')

const navigateHome = () => {
    router.push('/')
}

const displayMinutes = (value) => {
    if (value === null || value === undefined || value === '') return '-'
    const num = Number(value)
    if (Number.isNaN(num)) return `${value} 分钟`
    return `${num.toFixed(2)} 分钟`
}

const getEffectiveStandard = () => {
    const value = Number(standardMinutes.value)
    if (Number.isNaN(value) || value < 0) return DEFAULT_STANDARD_MINUTES
    return value
}

const openStandardDialog = () => {
    standardDialog.value = getEffectiveStandard()
    standardDialog.visible = true
}

const readPersistentValue = async (name) => {
    const param = []
    param[0] = ['工位号', OP_NAME]
    param[1] = ['名称', name]
    const data = CreateData('11', 'MES_持久化变量_读取', param)
    const response = await ExecDatabase(data)
    const row = response.data && response.data.length ? response.data[0] : null
    return row && row.值 ? String(row.值).trim() : ''
}

const writePersistentValue = (name, value) => {
    const param = []
    param[0] = ['工位号', OP_NAME]
    param[1] = ['名称', name]
    param[2] = ['值', value]
    const data = CreateData('12', 'MES_持久化变量_写入', param)
    return ExecDatabase(data)
}

const writeStationLog = (content, msgType = 'INFO') => {
    if (!ExecDatabaseByParam) return
    logAdd({ ExecDatabaseByParam }, {
        stationNumber: OP_NAME,
        msgType,
        operationType: 'StaticStandardChange',
        Content: `${loginUserName.value || '-'} ${content}`
    })
}

const loadStandardMinutes = async () => {
    try {
        const val = await readPersistentValue(STANDARD_NAME)
        const num = Number(val)
        standardMinutes.value = !Number.isNaN(num) && num >= 0 ? num : DEFAULT_STANDARD_MINUTES
    } catch (e) {
        standardMinutes.value = DEFAULT_STANDARD_MINUTES
        ElMessage.warning('读取静置标准失败，已使用默认30分钟')
    }
}

const handleSaveStandard = async () => {
    const value = Number(standardDialog.value)
    if (Number.isNaN(value) || value < 0) {
        ElMessage.warning('静置标准时间不能小于0')
        return
    }

    standardSaving.value = true
    const oldValue = getEffectiveStandard()
    try {
        await writePersistentValue(STANDARD_NAME, String(value))
        const newVal = await readPersistentValue(STANDARD_NAME)
        const num = Number(newVal)
        standardMinutes.value = !Number.isNaN(num) && num >= 0 ? num : value
        standardDialog.visible = false
        writeStationLog(`修改手动静置出库静置标准：${oldValue}分钟 -> ${standardMinutes.value}分钟`)
        ElMessage.success('静置标准已保存')
    } catch (e) {
        ElMessage.error('保存静置标准失败')
    } finally {
        standardSaving.value = false
    }
}

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', () => {
            mqttStatus.show = true
            mqttStatus.type = 'success'
            mqttStatus.icon = 'CircleCheck'
            mqttStatus.message = 'MQTT已连接'
            subscription.topic = `${window.g.mqttSubscriptionTopic}/${PAD_TOPIC_SUFFIX}`
            mqttClient.doSubscribe(subscription)
            setTimeout(() => {
                if (mqttStatus.type === 'success') mqttStatus.show = false
            }, 3000)
        })

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

        mqttClient.client.on('offline', () => {
            mqttStatus.show = true
            mqttStatus.type = 'error'
            mqttStatus.icon = 'CircleClose'
            mqttStatus.message = 'MQTT离线，请检查网络'
        })

        mqttClient.client.on('error', err => {
            mqttStatus.show = true
            mqttStatus.type = 'error'
            mqttStatus.icon = 'CircleClose'
            mqttStatus.message = `MQTT错误: ${err.message || '未知错误'}`
        })

        mqttClient.client.on('message', (topic, message) => {
            handleMqttMessage(message.toString())
        })
    } catch (e) {
        mqttStatus.show = true
        mqttStatus.type = 'error'
        mqttStatus.icon = 'CircleClose'
        mqttStatus.message = 'MQTT初始化失败'
    }
}

const publishMqtt = (payload) => {
    return new Promise((resolve, reject) => {
        if (!mqttClient || !mqttClient.client || !mqttClient.client.connected) {
            reject(new Error('MQTT未连接'))
            return
        }

        mqttClient.client.publish(window.g.mqttPublishTopic, payload, { qos: 0 }, error => {
            if (error) {
                reject(error)
            } else {
                resolve()
            }
        })
    })
}

const buildPayload = (command) => {
    return `WEB|${command}|${OP_NAME}|${productCode.value}^${getEffectiveStandard()}`
}

const handleMqttMessage = (rawMessage) => {
    const parts = rawMessage.split('|')
    const source = parts[0]
    const command = parts[1]
    const opName = parts[2]
    const result = parts.slice(3).join('|')

    if (source !== 'MES' || opName !== OP_NAME) return

    if (command === 'PadScanQuery') {
        handleScanReply(result)
    }
    if (command === 'PadConfirmOnline') {
        handleConfirmReply(result)
    }
}

const handleScanReply = (result) => {
    clearTimeout(mqttTimeout)
    scanLoading.value = false

    const fields = result.split('^')
    const success = fields[0] === '1'
    if (!success) {
        clearScanResult()
        scanResult.message = fields.slice(1).join('^') || '查询失败'
        ElMessage.error(scanResult.message)
        return
    }

    scanResult.success = true
    scanResult.productCode = fields[1] || productCode.value
    scanResult.orderNo = fields[2] || ''
    scanResult.productType = fields[3] || ''
    scanResult.machineCode = fields[4] || ''
    scanResult.prevStation = fields[5] || ''
    scanResult.staticStartTime = fields[6] || ''
    scanResult.staticMinutes = fields[7] || ''
    scanResult.minStaticMinutes = fields[8] || getEffectiveStandard()
    scanResult.partLoad = fields[9] === '1'
    scanResult.canConfirm = fields[10] === '1'
    scanResult.message = fields.slice(11).join('^') || (scanResult.canConfirm ? '允许确认上线' : '暂不可确认上线')
    confirmedSuccess.value = false
}

const handleConfirmReply = (result) => {
    clearTimeout(mqttTimeout)
    confirmLoading.value = false
    confirmDialog.visible = false

    const fields = result.split('^')
    const success = fields[0] === '1'
    const message = fields.slice(1).join('^') || (success ? '确认上线成功' : '确认上线失败')
    scanResult.message = message

    if (success) {
        confirmedSuccess.value = true
        scanResult.canConfirm = false
        ElMessage.success(message)
    } else {
        confirmedSuccess.value = false
        ElMessage.error(message)
    }
}

const handleScanQuery = async () => {
    if (!productCode.value) {
        ElMessage.warning('请先扫描产品码')
        return
    }

    scanLoading.value = true
    confirmedSuccess.value = false
    clearTimeout(mqttTimeout)
    try {
        await publishMqtt(buildPayload('PadScanQuery'))
        scanResult.message = '已发送扫码查询，等待后端回包...'
        mqttTimeout = setTimeout(() => {
            scanLoading.value = false
            ElMessage.error('扫码查询超时，未收到后端回包')
        }, 10000)
    } catch (e) {
        scanLoading.value = false
        ElMessage.error(e.message || '扫码查询发送失败')
    }
}

const handleConfirmClick = () => {
    if (!canConfirmOnline.value) {
        ElMessage.warning(scanResult.message || '当前状态不允许确认上线')
        return
    }
    confirmDialog.visible = true
}

const handleConfirmOnline = async () => {
    if (!canConfirmOnline.value) {
        ElMessage.warning(scanResult.message || '当前状态不允许确认上线')
        return
    }

    confirmLoading.value = true
    clearTimeout(mqttTimeout)
    try {
        await publishMqtt(buildPayload('PadConfirmOnline'))
        scanResult.message = '已发送确认上线，等待后端回包...'
        mqttTimeout = setTimeout(() => {
            confirmLoading.value = false
            ElMessage.error('确认上线超时，未收到后端回包')
        }, 10000)
    } catch (e) {
        confirmLoading.value = false
        ElMessage.error(e.message || '确认上线发送失败')
    }
}

const clearScanResult = () => {
    scanResult.success = false
    scanResult.productCode = ''
    scanResult.orderNo = ''
    scanResult.productType = ''
    scanResult.machineCode = ''
    scanResult.prevStation = ''
    scanResult.staticStartTime = ''
    scanResult.staticMinutes = ''
    scanResult.minStaticMinutes = ''
    scanResult.partLoad = false
    scanResult.canConfirm = false
    confirmedSuccess.value = false
}

const handleClearProduct = () => {
    productCode.value = ''
    clearScanResult()
    scanResult.message = '请扫描产品码查询静置信息'
}

const initPage = async () => {
    await loadStandardMinutes()
    createMqttConnection()
    nextTick(() => {
        scanInputRef.value?.focus?.()
    })
}

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 }
            await initPage()
            return
        }

        const result = await permissionVerify.value.show({
            title: '手动静置出库登录',
            promptText: '请刷卡进行身份验证',
            permissionLevel: '操作工'
        })
        if (result.success) {
            isAuthenticated.value = true
            userInfo.value = result.data
            await initPage()
        }
    } catch (e) {
        if (e.cancelled) {
            ElMessage.warning('已取消登录')
        } else {
            ElMessage.error('权限验证失败')
        }
    }
}

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

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

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

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

.header-section {
    background: linear-gradient(135deg, #0f766e 0%, #155e75 100%);
    color: white;
    padding: 18px 24px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.12);
    flex-shrink: 0;
}

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

.title-area {
    cursor: pointer;
}

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

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

.header-actions {
    display: flex;
    align-items: center;
    gap: 12px;
}

.standard-panel {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 8px 14px;
    border: 1px solid rgba(255, 255, 255, 0.22);
    border-radius: 22px;
    background: rgba(255, 255, 255, 0.13);
}

.standard-label,
.standard-value,
.login-user {
    white-space: nowrap;
}

.standard-label,
.standard-value {
    font-size: 16px;
    font-weight: 600;
}

.standard-edit {
    color: white;
}

.standard-edit:hover {
    background: rgba(255, 255, 255, 0.18);
    color: white;
}

.login-user {
    opacity: 0.95;
    font-size: 16px;
    font-weight: 600;
}

.scroll-container {
    flex: 1;
    overflow-y: auto;
    overflow-x: hidden;
    padding-bottom: 20px;
}

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

.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;
}

.operation-section,
.info-section,
.action-section {
    padding: 12px 24px 0;
}

.info-section {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 12px;
}

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

.main-card {
    display: flex;
    flex-direction: column;
    gap: 14px;
}

.scan-area {
    display: flex;
    flex-direction: column;
    gap: 10px;
}

.scan-row {
    display: flex;
    align-items: center;
    gap: 12px;
}

.form-label {
    width: 96px;
    flex-shrink: 0;
    text-align: right;
    color: #606266;
    font-size: 16px;
    font-weight: 500;
}

.result-summary {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 16px;
    padding: 14px 16px;
    border-radius: 8px;
    border: 1px solid #dbe4ef;
    background: #f8fafc;
}

.result-summary.success {
    border-color: #b7e4c7;
    background: #f0fdf4;
}

.result-summary.warning {
    border-color: #f5dab1;
    background: #fffbeb;
}

.summary-title {
    font-size: 18px;
    font-weight: 600;
    color: #303133;
    margin-bottom: 4px;
}

.summary-text {
    font-size: 14px;
    color: #606266;
}

.section-title {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 16px;
    font-weight: 600;
    color: #303133;
    margin-bottom: 14px;
}

.info-grid,
.metric-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 12px;
}

.info-item,
.metric-item {
    min-height: 58px;
    padding: 10px 12px;
    border-radius: 8px;
    background: #f8fafc;
    border: 1px solid #edf2f7;
    display: flex;
    flex-direction: column;
    justify-content: center;
    gap: 5px;
}

.metric-item.highlight {
    background: #ecfeff;
    border-color: #a5f3fc;
}

.info-label,
.metric-label {
    color: #909399;
    font-size: 13px;
}

.info-value,
.metric-value {
    color: #303133;
    font-size: 16px;
    font-weight: 500;
    word-break: break-all;
}

.info-value.strong {
    font-size: 18px;
    font-weight: 700;
}

.action-card {
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 16px;
}

.action-title {
    font-size: 18px;
    font-weight: 600;
    color: #303133;
    margin-bottom: 6px;
}

.action-desc {
    color: #606266;
    font-size: 14px;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 8px;
}

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

.standard-input {
    width: 180px;
}

.dialog-unit {
    margin-left: 10px;
    color: #606266;
}

@media (max-width: 1200px) {
    .header-actions {
        flex-wrap: wrap;
        justify-content: flex-end;
    }

    .info-section {
        grid-template-columns: 1fr;
    }
}

@media (max-width: 768px) {
    .scan-row,
    .action-card {
        flex-direction: column;
        align-items: stretch;
    }

    .form-label {
        width: auto;
        text-align: left;
    }

    .info-grid,
    .metric-grid {
        grid-template-columns: 1fr;
    }
}

@media (orientation: portrait) {
    .app-container {
        height: 100dvh;
    }

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

    :deep(.el-input__wrapper),
    :deep(.el-input-number .el-input__wrapper) {
        min-height: 44px;
    }

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

}
</style>
