<template>
    <div class="detail-container">
        <!-- 返回按钮 -->
        <div>
            <el-button type="danger" plain icon="el-icon-close" size="mini" @click="handleClose">返回</el-button>
        </div>

        <!-- 审核状态区域 -->
        <div class="status-section">
            <div class="status-icon">
                <i :class="statusIconClass"></i>
            </div>
            <div class="status-text">{{ statusText }}</div>
        </div>

        <!-- 移交内容区域 -->
        <div class="content-section">
            <div class="section-title">
                <div class="title-bar"></div>
                <span>移交内容</span>
            </div>
            <div class="content-info">
                <span class="project-name">{{ projectName }}</span>
                <span class="receiving-org">接收组织: {{ receivingOrg }}</span>
            </div>
        </div>

        <!-- 文件详情表格 -->
        <div class="table-section">
            <el-table :data="fileList" border style="width: 100%" class="detail-table" max-height="800">
                <el-table-column prop="index" label="序号" width="80" align="center">
                    <template slot-scope="scope">
                        {{ scope.$index + 1 }}
                    </template>
                </el-table-column>
                <el-table-column prop="proName" label="项目名称" min-width="150">
                    <template slot-scope="scope">
                        {{ scope.row.proName || '--' }}
                    </template>
                </el-table-column>
                <el-table-column prop="singleProName" label="单项工程名称" min-width="150">
                    <template slot-scope="scope">
                        {{ scope.row.singleProName || '--' }}
                    </template>
                </el-table-column>
                <el-table-column prop="createUserName" label="申请人" min-width="100">
                    <template slot-scope="scope">
                        {{ scope.row.createUserName || '--' }}
                    </template>
                </el-table-column>
                <el-table-column prop="createTime" label="申请时间" min-width="120">
                    <template slot-scope="scope">
                        {{ scope.row.createTime || '--' }}
                    </template>
                </el-table-column>
                <el-table-column prop="archiveName" label="档案名称" min-width="300">
                    <template slot-scope="scope">
                        <div class="archive-name-cell file-name-link" @click="viewFile(scope.row)">{{ scope.row.archiveName }}</div>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <!-- 移交审批区域 -->
        <div v-if="showApprovalActions && viewStatus !== 'detail'" class="approval-section">
            <div class="section-title">
                <div class="title-bar"></div>
                <span>移交审批</span>
            </div>
            <div class="approval-form">
                <div class="form-item">
                    <label class="form-label">审批意见:</label>
                    <el-input v-model="approvalComment" type="textarea" :rows="4" placeholder="请输入审批意见"
                        class="comment-textarea" clearable show-word-limit maxlength="255">
                    </el-input>
                </div>
                <div class="approval-actions">
                    <el-button type="primary" @click="handleApprove"
                        v-hasPermi="['transfer:apply:audit']">同意</el-button>
                    <el-button type="danger" @click="handleReject" v-hasPermi="['transfer:apply:audit']">驳回</el-button>
                </div>
            </div>
        </div>
        <div v-if="showApprovalActions2" class="approval-section">
            <div class="section-title">
                <div class="title-bar"></div>
                <span>审批意见</span>
            </div>
            <div class="approval-form">
                <div class="audit-info">
                    <div class="audit-row">
                        <span class="audit-label">审核人：</span>
                        <span class="audit-value">{{ auditUserName || '--' }}</span>
                    </div>
                    <div class="audit-row">
                        <span class="audit-label">审核日期：</span>
                        <span class="audit-value">{{ auditDate || '--' }}</span>
                    </div>
                    <div class="audit-row">
                        <span class="audit-label">审核意见：</span>
                        <span class="audit-value">{{ auditOpinion || '--' }}</span>
                    </div>
                </div>
            </div>
        </div>
        <!-- 预览文件 -->
        <ViewFile v-if="isViewflag" :rowData="row" :title="title" @closeDialog="closeDialog" @showColose="showColose" :width="600" />
    </div>
</template>

<script>
import { decryptWithSM4 } from '@/utils/sm'
import {
    getTransferApplyFilesByApplyIdApi,
    getTransferApplyApi,
} from '@/api/filesTransfer/apply'
import {auditTransferApplyApi,getTransferAuditApi,getTransferAudieFilesByApplyIdApi} from '@/api/filesTransfer/audit'
import ViewFile from '@/views/viewFile/viewFile.vue'

export default {
    name: 'DetailData',
    components:{ViewFile},
    data() {
        return {
            id: decryptWithSM4(this.$route.query.id),
            viewStatus: decryptWithSM4(this.$route.query.viewStatus),
            status: decryptWithSM4(this.$route.query.auditStatus), // approving, approved, rejected
            projectName: '',
            receivingOrg: '',
            approvalComment: '', // 审批意见
            fileList: [],
            // 审批信息展示
            auditUserName: '',
            auditDate: '',
            auditOpinion: '',
            isViewflag: false,
            row: {},
            title: "",
            errorObj: {
                approvalComment: '审批意见',
            },
        }
    },
    computed: {
        statusIconClass() {
            const iconMap = {
                'approving': 'el-icon-time',
                'approved': 'el-icon-check',
                'rejected': 'el-icon-close'
            }
            return iconMap[this.status] || 'el-icon-time'
        },
        statusText() {
            const textMap = {
                'approving': '审批中',
                'approved': '已通过',
                'rejected': '已驳回'
            }
            return textMap[this.status] || '审批中'
        },
        showApprovalActions() {
            return this.status === 'approving'
        },
        showApprovalActions2() {
            return this.status === 'approved' || this.status === 'rejected'
        }
    },
    mounted() {
        // 禁用页面滚动
        document.body.style.overflow = 'hidden';
    },
    beforeDestroy() {
        // 恢复页面滚动
        document.body.style.overflow = 'auto';
    },
    created() {
        this.initData();
    },
    methods: {
        // 预览文件
        viewFile(row) {
            console.error(row);
            
            this.title = "预览";
            this.row = row;
            this.isViewflag = true;
        },
        closeDialog() {
            this.isViewflag = false; 
        },
        showColose() {
            this.isflag = false;
        },
        handleClose() {
            if (this.viewStatus === 'audit') {
                const obj = { path: "/archivesManagement/filesTransfer/audit" }
                this.$tab.closeOpenPage(obj)
            } else {
                const obj = { path: "/archivesManagement/filesTransfer/apply" }
                this.$tab.closeOpenPage(obj)
            }
        },
        async initData() {
            this.fileList = [];
            
            const res = this.viewStatus === 'audit' ? await getTransferAudieFilesByApplyIdApi({ id: this.id }) : await getTransferApplyFilesByApplyIdApi({ id: this.id });

            const res2 = this.viewStatus === 'audit' ? await getTransferAuditApi({ id: this.id }) : await getTransferApplyApi({ id: this.id });
            this.projectName = res2?.data?.proName || '/';
            this.receivingOrg = res2?.data?.deptName || '/';
            // 审批信息
            this.auditUserName = res2?.data?.auditUser || '--';
            this.auditDate = res2?.data?.auditTime || '--';
            this.auditOpinion = res2?.data?.auditOpinion || '--';
            if (Array.isArray(res.data) && res.data.length > 0) {
                res.data.map(item => {
                    const newFile = {
                        proName: item.proName,
                        singleProName: item.singleProName,
                        createUserName: item.createUserName,
                        createTime: item.createTime,
                        archiveName: item?.parParentName + '/' + item?.parentName + '/' + item?.fileName,
                        fileId: item?.fileId || '',
                    }
                    this.fileList.push(newFile);
                })
            }

        },
        handleApprove() {
            if (!this.approvalComment.trim()) {
                this.$message.warning('请填写审批意见')
                return
            }

            this.$confirm('确认同意此申请？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'success'
            }).then(() => {
                this.auditTransferApply(1)
            }).catch(() => {
                // 取消操作
            })
        },
        handleReject() {
            if (!this.approvalComment.trim()) {
                this.$message.warning('请填写审批意见')
                return
            }

            this.$confirm('确认驳回此申请？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.auditTransferApply(2)
            }).catch(() => {
                // 取消操作
            })
        },
        // 审核
        auditTransferApply(auditStatus) {
            // 显示遮罩层
            this.loading = this.$loading({
                        lock: true,
                        text: "数据提交中，请稍候...",
                        background: 'rgba(0,0,0,0.5)',
                        target: this.$el.querySelector('.el-dialog') || document.body
                    })
            auditTransferApplyApi({
                id: this.id,
                auditOpinion: this.approvalComment.trim(),
                auditStatus: auditStatus
            }).then(res => {
                this.loading.close();
                this.$message.success(res.msg || '审核成功');
                this.handleClose();
            }).catch(error => {
                this.loading.close();
                this.$modal.msgError(this.errorMsg(error));
            })

        },
        errorMsg(error) {
            const errorMessage = error.message;
            const errorArr = errorMessage.split('：');
            const errorObjData = errorArr.length > 1 ? JSON.parse(errorArr[1]) : '';
            if(errorObjData){
                return this.errorObj[errorObjData.paramName] + errorArr[0] + ':' + errorObjData.originalValue;
            }else{
                return errorMessage;
            }
            
        }
    }
}
</script>

<style lang="scss" scoped>
.detail-container {
    padding: 20px;
    background: #fff;
    height: calc(100vh - 120px);
    /* 减去头部导航栏的高度 */
    overflow-y: auto;
    box-sizing: border-box;

    /* 自定义滚动条样式 */
    &::-webkit-scrollbar {
        width: 6px;
        background: #f5f5f5;
    }

    &::-webkit-scrollbar-track {
        background: #f5f5f5;
        border-radius: 3px;
    }

    &::-webkit-scrollbar-thumb {
        background: #c0c4cc;
        border-radius: 3px;
        transition: background 0.3s;
    }

    &::-webkit-scrollbar-thumb:hover {
        background: #909399;
    }
}

.status-section {
    text-align: center;
    margin-bottom: 40px;

    .status-icon {
        margin-bottom: 15px;

        i {
            font-size: 80px;
            color: #409eff;
        }
    }

    .status-text {
        font-size: 24px;
        font-weight: bold;
        color: #333;
    }
}

.content-section {
    margin-bottom: 30px;

    .section-title {
        display: flex;
        align-items: center;
        margin-bottom: 15px;

        .title-bar {
            width: 4px;
            height: 20px;
            background: #409eff;
            margin-right: 10px;
        }

        span {
            font-size: 18px;
            font-weight: bold;
            color: #333;
        }
    }

    .content-info {
        display: flex;
        align-items: center;
        gap: 30px;

        .project-name {
            font-size: 16px;
            color: #333;
        }

        .receiving-org {
            font-size: 14px;
            color: #666;
        }
    }
}

.table-section {
    margin-bottom: 30px;

    .detail-table {
        .archive-name-cell {
            white-space: normal;
            word-break: break-word;
            line-height: 1.4;
        }
    }
}

.approval-section {
    margin-top: 30px;

    .section-title {
        display: flex;
        align-items: center;
        margin-bottom: 20px;

        .title-bar {
            width: 4px;
            height: 20px;
            background: #409eff;
            margin-right: 10px;
        }

        span {
            font-size: 18px;
            font-weight: bold;
            color: #333;
        }
    }

    .approval-form {
        .audit-info {
            padding: 4px 0 0 6px;
        }

        .audit-row {
            margin-bottom: 10px;
            font-size: 14px;
            color: #333;
        }

        .audit-label {
            display: inline-block;
            min-width: 80px;
            color: #666;
        }

        .audit-value {
            color: #333;
        }

        .form-item {
            margin-bottom: 20px;

            .form-label {
                display: block;
                margin-bottom: 8px;
                font-size: 14px;
                font-weight: 500;
                color: #333;
            }

            .comment-textarea {
                width: 100%;

                ::v-deep .el-textarea__inner {
                    border: 1px solid #dcdfe6;
                    border-radius: 4px;
                    padding: 10px;
                    font-size: 14px;
                    line-height: 1.5;
                    resize: vertical;
                    min-height: 100px;

                    &:focus {
                        border-color: #409eff;
                        outline: none;
                    }
                }
            }
        }

        .approval-actions {
            text-align: center;
            padding: 20px 0;

            .el-button {
                margin: 0 10px;
                padding: 10px 30px;
                font-size: 14px;
            }
        }
    }
}

// 状态颜色变化
.status-section {
    .status-icon i {
        &.el-icon-time {
            color: #409eff; // 审批中 - 蓝色
        }

        &.el-icon-check {
            color: #67c23a; // 已通过 - 绿色
        }

        &.el-icon-close {
            color: #f56c6c; // 已驳回 - 红色
        }
    }

    .status-text {
        &.approving {
            color: #409eff;
        }

        &.approved {
            color: #67c23a;
        }

        &.rejected {
            color: #f56c6c;
        }
    }
}
.file-name-link {
    color: #409EFF;
    cursor: pointer;
}
.file-name-link:hover {
    text-decoration: underline;
}
</style>