<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">First Part Photo Upload</p>
                    </div>
                    <div class="header-actions">
                        <div style="display:flex;align-items:center;color:#fff;opacity:.95;">
                            登录人：{{ loginUserName }}
                        </div>
                        <el-button type="danger" icon="SwitchButton" @click="handleLogout" size="small">退出登录</el-button>
                    </div>
                </div>
            </div>

            <!-- 查询筛选区域 -->
            <div class="search-section">
                <div class="search-card">
                    <div class="search-form">
                        <div class="form-row">
                            <div class="form-item">
                                <label class="form-label">工位号：</label>
                                <el-select v-model="stationNumberValue" placeholder="请选择工位号" filterable clearable
                                    class="form-input" @change="loadPhotoItems">
                                    <el-option v-for="item in stationNumber" :key="item.value" :label="item.label"
                                        :value="item.value" />
                                </el-select>
                            </div>
                            <div class="form-item form-actions">
                                <el-button type="primary" icon="Search" @click="loadPhotoItems"
                                    :disabled="!stationNumberValue">查询</el-button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 数据展示区域：仅显示拍照上传项（项目类型=3） -->
            <div class="data-section">
                <div class="data-card">
                    <el-table v-loading="loading" :data="photoItems" :height="tableHeight" border stripe
                        style="width:100%"
                        :header-cell-style="{ background: '#f5f7fa', color: '#303133', fontWeight: 'bold', textAlign: 'center' }"
                        :cell-style="{ textAlign: 'center' }">
                        <el-table-column type="index" label="序号" width="60" fixed="left" />
                        <el-table-column prop="检测项目" label="检测项目" min-width="180" show-overflow-tooltip />
                        <el-table-column prop="工位号" label="工位号" width="110" />
                        <el-table-column prop="是否合格" label="是否合格" width="90">
                            <template #default="scope">
                                <el-tag
                                    :type="parseInt(scope.row.是否合格) === 1 ? 'success' : (parseInt(scope.row.是否合格) === 2 ? 'warning' : 'info')"
                                    size="small">
                                    {{ scope.row.是否合格 === 1 || scope.row.是否合格 === '1' ? 'OK' : (scope.row.是否合格 === 2 ||
                                        scope.row.是否合格 === '2' ? 'NG' : '未填写') }}
                                </el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column prop="结果确认" label="结果确认" width="90">
                            <template #default="scope">
                                <el-tag :type="scope.row.结果确认 == 1 ? 'success' : 'warning'" size="small">
                                    {{ scope.row.结果确认 == 1 ? '已确认' : '未确认' }}
                                </el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column prop="测量值" label="图片路径" min-width="260" show-overflow-tooltip />
                        <el-table-column label="操作" width="140" fixed="right">
                            <template #default="scope">
                                <el-button link type="primary" size="small" :disabled="scope.row.结果确认 == 1"
                                    @click="openUploadDialog(scope.row)">拍照上传</el-button>
                            </template>
                        </el-table-column>
                    </el-table>

                    <div class="pagination-wrapper">
                        <el-pagination v-model:current-page="pagination.currentPage"
                            v-model:page-size="pagination.pageSize" :page-sizes="[20, 50, 100, 200]"
                            :total="pagination.total" layout="total, sizes, prev, pager, next, jumper"
                            @size-change="handleSizeChange" @current-change="handleCurrentChange" />
                    </div>
                </div>
            </div>

            <!-- 上传对话框 -->
            <el-dialog v-model="uploadDialog.visible" title="拍照上传" width="640px" :close-on-click-modal="false">
                <div class="upload-form">
                    <el-form label-width="120px">
                        <el-form-item label="检测项目">
                            <el-input v-model="uploadDialog.row.检测项目" disabled />
                        </el-form-item>
                        <el-form-item label="相对路径">
                            <el-input v-model.trim="uploadDialog.relativePath"
                                placeholder="例如 OP120(固定架装配)\\2025-08-30\\首件项目-20250830-094503.png" />
                        </el-form-item>
                        <el-form-item label="选择图片">
                            <input type="file" accept="image/*" capture="environment" @change="onFileChange" />
                        </el-form-item>
                        <el-form-item v-if="uploadDialog.preview" label="预览">
                            <img :src="uploadDialog.preview" alt="预览"
                                style="max-width:100%;max-height:260px;border:1px solid #e4e7ed;border-radius:4px;" />
                        </el-form-item>
                    </el-form>
                    <div v-if="uploadDialog.error" style="color:#f56c6c;">{{ uploadDialog.error }}</div>
                </div>
                <template #footer>
                    <div style="display:flex;justify-content:flex-end;gap:8px;">
                        <el-button @click="uploadDialog.visible = false" :disabled="uploadDialog.loading">取 消</el-button>
                        <el-button type="primary" :loading="uploadDialog.loading" @click="submitUpload">上 传</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 } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import PermissionVerify from '@/components/PermissionVerify.vue'
import Cookie from 'js-cookie'
import { useRouter } from 'vue-router'

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

// 路由
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 stationNumber = ref([])
const stationNumberValue = ref('')
const loading = ref(false)
const photoItems = ref([])
const tableHeight = ref(500)

// 分页（如数据量不大，也可不分页；这里做简单分页）
const pagination = reactive({ currentPage: 1, pageSize: 50, total: 0 })

// 上传对话框
const uploadDialog = reactive({
    visible: false,
    loading: false,
    row: {},
    relativePath: '',
    file: null,
    preview: '',
    error: ''
})

const calculateTableHeight = () => {
    tableHeight.value = window.innerHeight - 280
}

// 登录与初始化
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 initializePage()
            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 initializePage()
        }
    } catch (e) {
        if (e.cancelled) {
            ElMessage.warning('已取消登录')
        } else {
            ElMessage.error('权限验证失败')
        }
    }
}

const initializePage = async () => {
    calculateTableHeight()
    window.addEventListener('resize', calculateTableHeight)
    await loadStationNumber()
    if (stationNumber.value.length > 0) {
        stationNumberValue.value = stationNumber.value[0].value
        await loadPhotoItems()
    }
}

// 读取工位列表（用于筛选）
const loadStationNumber = async () => {
    try {
        stationNumber.value = []
        const param = []
        const data = CreateData('11', '电子看板_质量数据_首件数据_工位表_查询', param)
        const res = await ExecDatabase(data)
        if (Array.isArray(res.data)) {
            for (let i = 0; i < res.data.length; i++) {
                stationNumber.value.push({
                    label: `【${res.data[i].工位号}】${res.data[i].工位名称 || ''}`,
                    value: res.data[i].工位号
                })
            }
        }
    } catch (e) {
        console.error('加载工位列表失败:', e)
        ElMessage.error('加载工位列表失败')
    }
}

// 读取拍照上传项：项目类型=3
const loadPhotoItems = async () => {
    if (!stationNumberValue.value) {
        photoItems.value = []
        pagination.total = 0
        return
    }
    loading.value = true
    try {
        const param = []
        param.push(['工位号', stationNumberValue.value])
        const data = CreateData('11', '电子看板_质量数据_首件数据_MOBY_查询', param)
        const res = await ExecDatabase(data)
        const all = Array.isArray(res.data) ? res.data : []
        const onlyPhoto = all.filter(x => Number(x.项目类型) === 3)
        pagination.total = onlyPhoto.length
        // 简单分页
        const start = (pagination.currentPage - 1) * pagination.pageSize
        photoItems.value = onlyPhoto.slice(start, start + pagination.pageSize)
    } catch (e) {
        console.error('查询失败:', e)
        ElMessage.error('查询失败，请稍后重试')
    } finally {
        loading.value = false
    }
}

const handleSizeChange = (val) => {
    pagination.pageSize = val
    pagination.currentPage = 1
    loadPhotoItems()
}
const handleCurrentChange = (val) => {
    pagination.currentPage = val
    loadPhotoItems()
}

// 打开上传弹窗
const openUploadDialog = (row) => {
    try {
        uploadDialog.visible = true
        uploadDialog.loading = false
        uploadDialog.row = row
        uploadDialog.file = null
        uploadDialog.preview = ''
        uploadDialog.error = ''
        // 默认路径与文件名
        const today = new Date()
        const yyyy = today.getFullYear()
        const mm = String(today.getMonth() + 1).padStart(2, '0')
        const dd = String(today.getDate()).padStart(2, '0')
        const hh = String(today.getHours()).padStart(2, '0')
        const mi = String(today.getMinutes()).padStart(2, '0')
        const ss = String(today.getSeconds()).padStart(2, '0')
        const ymd = `${yyyy}-${mm}-${dd}`
        const ymdhms = `${yyyy}${mm}${dd}-${hh}${mi}${ss}`
        // 默认相对路径：{工位号}({工位名称})\\{日期}\\{首件项目名称}-{时间}.png
        const stationLabel = (stationNumber.value.find(x => x.value === stationNumberValue.value)?.label || '')
            .replace(/^【[^】]*】/, '') // 去掉【工位号】前缀
            .trim()
        const stationName = stationLabel || ''
        const projectName = (row.检测项目 || '').toString().replace(/[\\/:*?"<>|]/g, '').replace('照片路径','')
        uploadDialog.relativePath = `${stationNumberValue.value}${stationName ? '(' + stationName + ')' : ''}\\${ymd}\\${projectName ? projectName + '-' : ''}${ymdhms}.png`
    } catch (e) { }
}

// 文件选择
const onFileChange = (e) => {
    uploadDialog.error = ''
    const files = e && e.target ? e.target.files : []
    if (!files || !files[0]) {
        uploadDialog.file = null
        uploadDialog.preview = ''
        return
    }
    const file = files[0]
    if (!/^image\//.test(file.type)) {
        uploadDialog.error = '请选择图片文件'
        return
    }
    uploadDialog.file = file
    const reader = new FileReader()
    reader.onload = (ev) => {
        uploadDialog.preview = ev.target && ev.target.result ? ev.target.result.toString() : ''
    }
    reader.readAsDataURL(file)
}

// 提交上传
const submitUpload = async () => {
    try {
        if (!uploadDialog.relativePath) { uploadDialog.error = '请填写相对路径'; return }
        if (!uploadDialog.file || !uploadDialog.preview) { uploadDialog.error = '请选择图片'; return }
        uploadDialog.loading = true

        // 调用本地上传接口（127.0.0.1:9982/UploadImageToShare）
        const payload = {
            MsgId: Math.random().toString(36).substring(2),
            RelativePath: uploadDialog.relativePath,
            ImageBase64: uploadDialog.preview // 可包含 data:image/png;base64, 前缀
        }
        const res = await ExecHttpRequest(window.g.API_MES_Controller_URL + '/UploadImageToShare', 'post', payload)
        const code = res && res.data ? res.data.Code : null
        const message = res && res.data ? (res.data.Message || '') : ''
        if (code !== '200') {
            ElMessage.error(message || '上传失败')
            uploadDialog.loading = false
            return
        }

        // 上传成功 -> 调用结果确认存储过程：电子看板_质量数据_首件数据_MOBY_结果确认
        // 需要保存完整UNC前缀：\\Cait-officefile\\mes\\首件照片 + RelativePath
        const root = (window.g && window.g.imageShareRoot) ? window.g.imageShareRoot : ''
        const rel = uploadDialog.relativePath.replace(/\//g, '\\')
        const fullPath = root ? `${root}\\${rel}` : rel
        const param = []
        param.push(['ID', uploadDialog.row.ID])
        param.push(['测量值', fullPath])
        param.push(['是否合格', 1])
        param.push(['检测人', Cookie.get('userName') || loginUserName.value || ''])
        const data = CreateData('12', '电子看板_质量数据_首件数据_MOBY_结果确认', param)
        const confirmRes = await ExecDatabase(data)
        if (Array.isArray(confirmRes.data) && confirmRes.data[0] && confirmRes.data[0].result === '1') {
            ElMessage.success('上传成功并已结果确认')
            uploadDialog.visible = false
            await loadPhotoItems()
        } else {
            ElMessage.warning('上传成功，但结果确认失败，请稍后重试')
        }
    } catch (e) {
        console.error('提交上传失败:', e)
        ElMessage.error('提交上传失败，请稍后重试')
    } finally {
        uploadDialog.loading = false
    }
}

// 退出登录
const handleLogout = async () => {
    try {
        await ElMessageBox.confirm('确定要退出登录吗？', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' })
        isAuthenticated.value = false
        userInfo.value = {}
        photoItems.value = []
        pagination.total = 0
        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: '' },
                    user: { name: Cookie.get('userName') || '' }
                }
            })
            checkPermission()
        } else {
            ElMessage.error('权限验证组件初始化失败')
        }
    }, 300)
})
</script>

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

.header-section {
    background: linear-gradient(135deg, #1d976c 0%, #93f9b9 100%);
    color: white;
    padding: 12px 16px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

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

.search-section {
    padding: 12px;
}

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

.search-form .form-row {
    display: flex;
    gap: 12px;
}

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

.search-form .form-item.form-actions {
    flex: none;
    justify-content: flex-end;
}

.search-form .form-label {
    width: 80px;
    flex-shrink: 0;
    text-align: right;
    color: #606266;
    font-size: 14px;
}

.search-form .form-input {
    flex: 1;
    min-width: 220px;
}

.data-section {
    flex: 1;
    padding: 0 12px 12px;
    overflow: hidden;
}

.data-card {
    background: white;
    border-radius: 8px;
    padding: 10px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
    height: 100%;
    display: flex;
    flex-direction: column;
}

.data-card :deep(.el-table) {
    flex: 1;
}

.data-card :deep(.el-table .el-table__cell) {
    padding: 8px 0;
}

.pagination-wrapper {
    display: flex;
    justify-content: center;
    padding-top: 12px;
    border-top: 1px solid #ebeef5;
    margin-top: 12px;
}

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

/* 竖屏PAD优化 */
@media (orientation: portrait) {
    .app-container {
        height: 100dvh;
    }

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

    .search-form .form-label {
        width: 100px;
        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;
    }
}
</style>
