<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 Record Search</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="searchForm.stationNumber" placeholder="请选择工位号" filterable clearable
                                    class="form-input" @change="handleSearch">
                                    <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="searchForm.productNo" placeholder="请输入产品编号" clearable
                                    class="form-input" @keyup.enter="handleSearch" />
                            </div>
                        </div>

                        <!-- 第二行 -->
                        <div class="form-row">
                            <div class="form-item">
                                <label class="form-label">返修状态：</label>
                                <el-select v-model="searchForm.repairStatus" placeholder="全部状态" clearable
                                    class="form-input" @change="handleSearch">
                                    <el-option label="全部状态" value="" />
                                    <el-option label="未下线" value="0" />
                                    <el-option label="已下线" value="1" />
                                    <el-option label="回流中" value="2" />
                                    <el-option label="已完成" value="3" />
                                </el-select>
                            </div>
                            <div class="form-item">
                                <label class="form-label">时间范围：</label>
                                <el-date-picker v-model="searchForm.dateRange" type="daterange" range-separator="至"
                                    start-placeholder="开始日期" end-placeholder="结束日期" format="YYYY-MM-DD"
                                    value-format="YYYY-MM-DD" class="form-date-picker" @change="handleSearch" />
                            </div>
                        </div>

                        <!-- 第三行：操作按钮 -->
                        <div class="form-row form-row-actions">
                            <el-button type="primary" icon="Search" @click="handleSearch" :loading="loading"
                                size="large">
                                查询
                            </el-button>
                            <!-- <el-button icon="Refresh" @click="handleReset" size="large">
                                重置
                            </el-button> -->
                        </div>
                    </div>
                </div>
            </div>

            <!-- 数据展示区域 -->
            <div class="data-section">
                <div class="data-card">
                    <el-table v-loading="loading" :data="tableData" :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="订单号" width="120" show-overflow-tooltip />
                        <el-table-column prop="产品编号" label="产品编号" width="240" show-overflow-tooltip />
                        <el-table-column prop="产品型号" label="产品型号" width="100" show-overflow-tooltip />
                        <el-table-column prop="不合格工位" label="不合格工位" width="100" show-overflow-tooltip />
                        <el-table-column prop="不合格时间" label="不合格时间" width="170" show-overflow-tooltip />
                        <el-table-column prop="返修上线口" label="返修上线口" width="100" show-overflow-tooltip />
                        <el-table-column prop="返修上线时间" label="返修上线时间" width="170" show-overflow-tooltip />
                        <el-table-column prop="再起始工位" label="再起始工位" width="100" show-overflow-tooltip />
                        <el-table-column prop="再起始工位到达时间" label="再起始工位到达时间" width="170" show-overflow-tooltip />
                        <el-table-column prop="返修描述" label="返修描述" min-width="150" show-overflow-tooltip />
                        <el-table-column label="返修状态" width="100" fixed="right">
                            <template #default="scope">
                                <el-tag :type="getStatusType(scope.row.返修状态)" size="small"
                                    @dblclick="handleStatusDblClick(scope.row)">
                                    {{ getStatusText(scope.row.返修状态) }}
                                </el-tag>
                            </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="detailDialog.visible" title="返修记录详情" width="90%" :close-on-click-modal="false">
                <div class="detail-content">
                    <el-descriptions :column="1" border size="large">
                        <el-descriptions-item label="订单号">{{ detailDialog.data.订单号 }}</el-descriptions-item>
                        <el-descriptions-item label="产品编号">{{ detailDialog.data.产品编号 }}</el-descriptions-item>
                        <el-descriptions-item label="产品型号">{{ detailDialog.data.产品型号 }}</el-descriptions-item>
                        <el-descriptions-item label="不合格工位">{{ detailDialog.data.不合格工位 }}</el-descriptions-item>
                        <el-descriptions-item label="不合格时间">{{ detailDialog.data.不合格时间 }}</el-descriptions-item>
                        <el-descriptions-item label="返修上线口">{{ detailDialog.data.返修上线口 }}</el-descriptions-item>
                        <el-descriptions-item label="返修上线时间">{{ detailDialog.data.返修上线时间 }}</el-descriptions-item>
                        <el-descriptions-item label="再起始工位">{{ detailDialog.data.再起始工位 }}</el-descriptions-item>
                        <el-descriptions-item label="再起始工位到达时间">{{ detailDialog.data.再起始工位到达时间 }}</el-descriptions-item>
                        <el-descriptions-item label="返修描述">{{ detailDialog.data.返修描述 || '-' }}</el-descriptions-item>
                        <el-descriptions-item label="返修状态">
                            <el-tag :type="getStatusType(detailDialog.data.返修状态)">
                                {{ getStatusText(detailDialog.data.返修状态) }}
                            </el-tag>
                        </el-descriptions-item>
                    </el-descriptions>
                </div>
                <template #footer>
                    <el-button type="primary" @click="detailDialog.visible = false" size="large">关 闭</el-button>
                </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 router = useRouter()

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

// 权限验证相关
const isAuthenticated = ref(false)
const permissionVerify = ref(null)
const userInfo = ref({})

// 响应式数据
const loading = ref(false)
const stationList = ref([])
const tableData = ref([])
const tableHeight = ref(500)

// 搜索表单
const searchForm = reactive({
    stationNumber: '',
    productNo: '',
    repairStatus: '',
    dateRange: []
})

// 分页信息
const pagination = reactive({
    currentPage: 1,
    pageSize: 50,
    total: 0
})

// 详情对话框
const detailDialog = reactive({
    visible: false,
    data: {}
})

const loginUserName = computed(() => Cookie.get('userName') || userInfo.value.姓名 || userInfo.value.userName || '-')

// 计算表格高度
const calculateTableHeight = () => {
    tableHeight.value = window.innerHeight - 320
}

// 获取状态类型
const getStatusType = (status) => {
    const statusMap = {
        '0': 'danger',   // 未下线
        '1': 'warning',  // 已下线
        '2': 'info',     // 回流中
        '3': 'success'   // 已完成
    }
    return statusMap[String(status)] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
    const statusMap = {
        '0': '未下线',
        '1': '已下线',
        '2': '回流中',
        '3': '已完成'
    }
    return statusMap[String(status)] || '未知状态'
}

// 权限验证
const checkPermission = async () => {
    try {
        // 优先检查Cookie是否已登录
        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 initializeData()
            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 initializeData()
        }
    } catch (error) {
        if (error.cancelled) {
            ElMessage.warning('已取消登录')
        } else {
            ElMessage.error('权限验证失败')
        }
    }
}

// 初始化
onMounted(async () => {
    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)
})

// 初始化数据（权限验证通过后调用）
const initializeData = async () => {
    calculateTableHeight()
    window.addEventListener('resize', calculateTableHeight)

    // 初始化时间范围为最近30天
    const today = new Date()
    const thirtyDaysAgo = new Date(today.getTime() - 30 * 24 * 60 * 60 * 1000)
    searchForm.dateRange = [formatDate(thirtyDaysAgo), formatDate(today)]

    // 加载工位列表
    await loadStationList()

    // 执行查询
    await handleSearch()
}

// 格式化日期
const formatDate = (date) => {
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    return `${year}-${month}-${day}`
}

// 加载工位列表
const loadStationList = async () => {
    try {
        const param = []
        const response = await ExecDatabaseByParam('11', 'MES_计划BOM_工位与名称_查询', param)
        if (response.data && response.data.length > 0) {
            stationList.value = response.data.map(item => ({
                label: `${item.工位号} - ${item.工位名称 || ''}`,
                value: item.工位号
            }))
        }
    } catch (error) {
        console.error('加载工位列表失败:', error)
        ElMessage.error('加载工位列表失败')
    }
}

// 查询数据
const handleSearch = async () => {
    loading.value = true
    try {
        // 构建查询参数 - 复用存储过程 MES_工位返修记录_分页_查询
        const param = []
        param[0] = ['工位号', searchForm.stationNumber || '']
        param[1] = ['产品编号', searchForm.productNo || '']
        param[2] = ['返修状态', searchForm.repairStatus || '']
        param[3] = ['开始时间', searchForm.dateRange && searchForm.dateRange[0] ? searchForm.dateRange[0] + ' 00:00:00' : '']
        param[4] = ['结束时间', searchForm.dateRange && searchForm.dateRange[1] ? searchForm.dateRange[1] + ' 23:59:59' : '']
        param[5] = ['PageCurrent', pagination.currentPage]
        param[6] = ['PageSize', pagination.pageSize]
        param[7] = ['PageCount', '1111', 'int', '1']
        param[8] = ['ItemCount', '1111', 'int', '1']

        const response = await ExecDatabaseByParam('11', 'MES_工位返修记录_分页_查询', param)

        if (response.data && response.data.result) {
            tableData.value = response.data.result
            // 获取总数
            if (response.data.output && response.data.output.length > 0) {
                pagination.total = parseInt(response.data.output[0].ItemCount) || 0
            }
        } else {
            tableData.value = []
            pagination.total = 0
        }
    } catch (error) {
        console.error('查询失败:', error)
        ElMessage.error('查询失败，请稍后重试')
    } finally {
        loading.value = false
    }
}

// 重置查询条件
const handleReset = () => {
    searchForm.stationNumber = ''
    searchForm.productNo = ''
    searchForm.repairStatus = ''
    // 重置为最近30天
    const today = new Date()
    const thirtyDaysAgo = new Date(today.getTime() - 30 * 24 * 60 * 60 * 1000)
    searchForm.dateRange = [formatDate(thirtyDaysAgo), formatDate(today)]
    pagination.currentPage = 1
    handleSearch()
}

// 双击返修状态列 - 隐蔽的删除功能
const handleStatusDblClick = async (row) => {
    // 只有非完成状态才允许删除（状态 !== 3）
    if (String(row.返修状态) === '3') {
        return // 已完成状态不允许删除，静默忽略
    }

    try {
        await ElMessageBox.confirm(
            `确定要删除该返修记录吗？\n产品编号：${row.产品编号 || '-'}\n当前状态：${getStatusText(row.返修状态)}`,
            '删除返修记录',
            {
                confirmButtonText: '确定删除',
                cancelButtonText: '取消',
                type: 'warning',
                confirmButtonClass: 'el-button--danger'
            }
        )

        // 调用删除存储过程
        const param = []
        param[0] = ['ID', row.ID || '']
        const data = CreateData('12', 'MES_工位返修记录_删除记录', param)
        const res = await ExecDatabase(data)

        if (res.data && res.data.length >= 0) {
            ElMessage.success('删除成功')
            // 刷新列表
            await handleSearch()
        } else {
            ElMessage.error('删除失败')
        }
    } catch (e) {
        if (e !== 'cancel') {
            console.error('删除失败:', e)
            ElMessage.error('删除失败')
        }
    }
}

// 分页大小改变
const handleSizeChange = (val) => {
    pagination.pageSize = val
    pagination.currentPage = 1
    handleSearch()
}

// 当前页改变
const handleCurrentChange = (val) => {
    pagination.currentPage = val
    handleSearch()
}

// 查看详情
const handleViewDetail = (row) => {
    detailDialog.data = row
    detailDialog.visible = true
}

// 退出登录
const handleLogout = async () => {
    try {
        await ElMessageBox.confirm(
            '确定要退出登录吗？',
            '提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        )

        isAuthenticated.value = false
        userInfo.value = {}
        tableData.value = []
        pagination.total = 0

        // 清理登录Cookie
        Cookie.remove('userId')
        Cookie.remove('userName')

        ElMessage.success('已退出登录')

        // 重新返回首页
        router.push('/')
    } catch {
        // 用户取消
    }
}
</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, #1e3c72 0%, #2a5298 100%);
    color: white;
    padding: 16px 20px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

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

    .title-area {
        cursor: pointer;
        transition: opacity 0.2s;

        &:hover {
            opacity: 0.85;
        }
    }

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

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

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

// 权限验证加载样式
.auth-loading {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    height: 100vh;
    color: #909399;

    i {
        font-size: 40px;
        margin-bottom: 20px;
    }

    p {
        font-size: 16px;
    }
}

// 查询区域样式
.search-section {
    padding: 12px 16px;

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

        .search-form {
            .form-row {
                display: flex;
                gap: 16px;
                margin-bottom: 12px;
                flex-wrap: wrap;

                &:last-child {
                    margin-bottom: 0;
                }

                &.form-row-actions {
                    justify-content: center;
                    gap: 20px;
                    margin-top: 8px;
                }
            }

            .form-item {
                display: flex;
                align-items: center;
                flex: 1;
                min-width: 280px;

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

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

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

            .form-date-picker {
                flex: 1;
                min-width: 260px;
            }
        }
    }
}

// 数据区域样式
.data-section {
    flex: 1;
    padding: 0 16px 16px;
    overflow: hidden;

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

        :deep(.el-table) {
            flex: 1;
            border-radius: 8px;

            .el-table__cell {
                padding: 10px 0;
            }
        }
    }
}

// 分页样式
.pagination-wrapper {
    display: flex;
    justify-content: center;
    padding-top: 16px;
    border-top: 1px solid #ebeef5;
    margin-top: 12px;
}

// 详情对话框样式
.detail-content {
    :deep(.el-descriptions) {
        .el-descriptions__label {
            font-weight: 600;
            width: 140px;
        }

        .el-descriptions__content {
            word-break: break-all;
        }
    }
}

// 触屏优化 - PAD竖屏适配
@media (max-width: 1024px) {
    .header-section {
        padding: 12px 16px;

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

    .search-section {
        padding: 10px 12px;

        .search-card {
            padding: 12px 16px;
        }

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

            .form-item {
                min-width: 100%;
            }

            .form-label {
                width: 90px;
                font-size: 14px;
            }
        }
    }

    .data-section {
        padding: 0 12px 12px;
    }
}

// PAD触屏优化 - 增大点击区域
@media (orientation: portrait) {
    .app-container {
        height: 100dvh;
    }

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

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

    :deep(.el-input__wrapper) {
        min-height: 44px;
        font-size: 15px;
    }

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

    :deep(.el-button) {
        height: 34px;
        font-size: 15px;
        padding: 12px 24px;
    }

    :deep(.el-button--large) {
        height: 34px;
        font-size: 16px;
        padding: 14px 32px;
    }

    :deep(.el-date-editor) {
        min-height: 44px;
    }

    :deep(.el-table) {
        font-size: 14px;
    }

    :deep(.el-tag) {
        font-size: 13px;
        padding: 4px 10px;
    }

    :deep(.el-pagination) {

        .el-pagination__total,
        .el-pagination__sizes,
        .el-pagination__jump {
            font-size: 14px;
        }

        .el-pager li {
            min-width: 36px;
            height: 36px;
            line-height: 36px;
            font-size: 14px;
        }

        .btn-prev,
        .btn-next {
            min-width: 36px;
            height: 36px;
        }
    }
}

// 横屏优化
@media (orientation: landscape) and (max-height: 600px) {
    .header-section {
        padding: 8px 16px;

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

        .page-subtitle {
            display: none;
        }
    }

    .search-section {
        padding: 8px 12px;

        .search-card {
            padding: 10px 16px;
        }

        .form-row {
            margin-bottom: 8px;
        }
    }
}
</style>
