<template>
    <!-- 领用审核详情 -->
    <div class="business-details-container">
        <el-row>
            <el-col :span="18">
                <div class="left-container">
                    <div class="pages-title">领用申请详情</div>

                    <TitleTip :title="`基本信息`" />
                    <el-form size="small" style="padding: 20px" disabled label-width="120px" :model="detailsInfo">
                        <el-row>
                            <el-col :span="8">
                                <el-form-item label="领用单位">
                                    <el-input v-model="detailsInfo.leaseUnit" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="领用工程">
                                    <el-input v-model="detailsInfo.leaseProject" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="领料人">
                                    <el-input v-model="detailsInfo.leasePerson" />
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <!--
                                <el-col :span="8">
                                    <el-form-item label="采购申请编号">
                                        <el-input v-model="detailsInfo.applyCode" />
                                    </el-form-item>
                                </el-col>
                            -->
                            <el-col :span="8">
                                <el-form-item label="标准配置">
                                    <el-input v-model="detailsInfo.leaseUnit" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="联系电话">
                                    <el-input v-model="detailsInfo.phone" />
                                </el-form-item>
                            </el-col>

                            <el-col :span="8">
                                <el-form-item label="类型规格">
                                    <el-input v-model="detailsInfo.maTypeNames" />
                                </el-form-item>
                            </el-col>
                        </el-row>

                        <!-- <el-row></el-row> -->
                    </el-form>

                    <TitleTip :title="`明细信息`" />
                    <el-table style="margin-top: 20px" :data="detailsList">
                        <el-table-column label="序号" align="center" width="80" type="index" />
                        <el-table-column prop="maTypeName" label="类型名称" align="center" show-overflow-tooltip />
                        <el-table-column prop="typeName" label="规格型号" align="center" show-overflow-tooltip />
                        <el-table-column prop="unitName" label="计量单位" align="center" show-overflow-tooltip />
                        <el-table-column prop="preNum" label="预领数量" align="center" show-overflow-tooltip />
                        <el-table-column prop="remark" label="备注" align="center" show-overflow-tooltip />
                    </el-table>

                    <TitleTip :title="`附件信息`" />
                    <div class="file-box">暂无附件</div>
                </div>
            </el-col>
            <el-col :span="6">
                <div class="right-container">
                    <div class="right-title">
                        <div></div>
                        <div></div>
                        <div>流程记录</div>
                    </div>

                    <div class="process-record">
                        <el-steps :active="active" :space="120" direction="vertical">
                            <el-step v-for="step in auditingList" :key="step.id" :title="step.nodeName">
                                <template slot="description">
                                    <div class="custom-description">
                                        审核结果:
                                        <el-tag size="mini" type="primary" v-if="step.isAccept === 0">待审批</el-tag>
                                        <el-tag size="mini" type="success" v-if="step.isAccept === 1">已通过</el-tag>
                                        <el-tag size="mini" type="danger" v-if="step.isAccept === 2">已驳回</el-tag>
                                    </div>

                                    <div class="node-info" v-if="step.auditBy">
                                        审核人:
                                        {{ step.auditBy }}
                                    </div>

                                    <div class="node-info" v-if="step.createTime">
                                        审核时间:
                                        {{ step.createTime }}
                                    </div>

                                    <div class="node-info" v-if="step.remark">
                                        审核意见:
                                        {{ step.remark }}
                                    </div>
                                </template>
                            </el-step>
                        </el-steps>
                    </div>

                    <div class="auditing-container" v-if="pagesType === 1">
                        <el-input
                            type="textarea"
                            placeholder="请输入审核意见"
                            v-model="auditingParams.remark"
                            :autosize="{ minRows: 2, maxRows: 6 }"
                        />

                        <el-row class="btn-container">
                            <el-button type="success" size="mini" @click="onHandleAuditing(1)">通过</el-button>
                            <el-button type="danger" size="mini" @click="onHandleAuditing(2)">驳回</el-button>
                        </el-row>
                    </div>
                </div>
            </el-col>
        </el-row>
    </div>
</template>

<script>
import TitleTip from './components/title-tip.vue'
import { getLeaseTaskDetail } from '@/api/business/index'
import { submitAuditingApi, getAuditingDetailsApi,getNodeAuditStatusAPI} from '@/api/receive-apply/index.js'
import { getInfo,iwsLogin } from '@/api/login'
import { getConfig } from '@/api/config';
import { setToken, setExpiresIn } from '@/utils/auth'
export default {
    components: {
        TitleTip
    },
    data() {
        return {
            active: 1,
            userId: '',
            pagesType: 1,
            currentNodeId: '',
            detailsInfo: {},
            detailsList: [],
            auditingList: [],
            auditingParams: {
                nodeId: '', // 当前审核记录的id
                remark: '', // 审核意见
                typeId: '', // 当前审核记录中的 typeId
                taskId: '', // 外层列表的taskId
                isAccept: '', // 审批结果 1. 通过 2. 驳回
                recordId: '',
                nextNodeId: '', // 下个流程节点ID
                leaseId: '', // 外键id
                taskCode: '', // 任务编码
                unitName: '', // 单位名称
                projectName: '' // 项目名称
            }
        }
    },
    async created() {
        // 判断当前路由页面是否有查询参数
        if (this.$route.query) {
            const { id, taskId, type } = this.$route.query
            console.log('路由参数:', id, taskId, type)
            // ----type---- 1. 查看 2. 审核
            this.auditingParams.taskId = taskId
            // 如果有type参数，则设置pagesType
            if (type !== undefined) {
                this.pagesType = type
            }else{
                this.getNodeAuditStatus()
            }
            // this.currentNodeId = nodeId
            await this.getLeaseTaskDetailFun(id, taskId)
        }
        this.userId = sessionStorage.getItem('userId')
    },
    methods: {
        async getNodeAuditStatus(){
            const res = await getNodeAuditStatusAPI({taskId:this.auditingParams.taskId})
            if(res.data){
                if (res.data.auditStatus == 0) {
                    this.pagesType = 1;
                } else if (res.data.auditStatus == 1) {
                    this.pagesType = 2;
                }else{
                    this.pagesType = 1;
                } 
            }else{
                this.pagesType = 1
            }
        },
        
        // 通过 或 驳回
        async onHandleAuditing(type) {
            // 组装参数
            // 1. 先找出当前用户有权限的所有节点
            const userAuthorizedNodes = this.auditingList.filter(
                e => e.configValues && e.configValues.includes(this.userId)
            )

            if (userAuthorizedNodes.length === 0) {
                this.$modal.msgError('未查询到您的审核权限！')
                return
            }

            // 2. 根据当前节点状态找出应该审核的节点
            // 优先找待审核的节点(isAccept === 0)
            let currentNode = userAuthorizedNodes.find(node => node.isAccept === 0)

            // 如果没有待审核的节点，则使用第一个有权限的节点
            if (!currentNode) {
                currentNode = userAuthorizedNodes[0]
            }

            console.log('当前审核节点:', currentNode)

            const { recordId, id, typeId, isAccept } = currentNode

            // if (isAccept != 0) {
            //     this.$modal.msgError('当前已审核，不可重复审核')
            //     return
            // }

            Object.assign(this.auditingParams, {
                typeId,
                recordId,
                nodeId: id
            })

            this.auditingParams.isAccept = type

            this.auditingParams.leaseId = this.detailsInfo.id

            this.auditingParams.taskCode = this.detailsInfo.code

            this.auditingParams.unitName = this.detailsInfo.leaseUnit

            this.auditingParams.projectName = this.detailsInfo.leaseProject

            // 找出当前节点在审核列表中的索引
            const currentIndex = this.auditingList.findIndex(e => e.id === id)

            if (currentIndex !== -1 && currentIndex !== this.auditingList.length - 1) {
                this.auditingParams.nextNodeId = this.auditingList[currentIndex + 1].id
            }

            console.log('提交的审核参数:', this.auditingParams)

            const res = await submitAuditingApi(this.auditingParams)
            console.log(res, '提交结果')

            if (res.code === 200) {
                this.$modal.msgSuccess('审核成功')
                setTimeout(() => {
                    // const obj = { path: '/business-examine/receive-apply' }
                    // this.$tab.closeOpenPage(obj)
                    this.$tab.closePage()
                }, 500)
            }
        },

        // 获取数据详情 和 审核记录详情
        async getLeaseTaskDetailFun(id, taskId) {
            const { data: res } = await getLeaseTaskDetail(id)

            this.detailsInfo = res.leaseApplyInfo
            this.detailsList = res.leaseApplyDetailsList

            const { rows: result } = await getAuditingDetailsApi({ taskId })
            this.auditingList = result

            console.log('审核列表数据:', this.auditingList)
            console.log('当前用户ID:', this.userId)
            console.log(
                '审核权限检查:',
                this.auditingList.map(item => ({
                    nodeName: item.nodeName,
                    configValues: item.configValues,
                    hasPermission: item.configValues && item.configValues.includes(this.userId)
                }))
            )
        }
    }
}
</script>

<style scoped lang="scss">
.business-details-container {
    padding: 20px;
}

.pages-title {
    padding: 10px 0 30px 0;
    font-size: 20px;
    font-weight: bold;
    letter-spacing: 2px;
    text-align: center;
    color: #19a4a0;
}

.file-box {
    padding: 10px;
    display: grid;
    grid-template-columns: repeat(12, 1fr);
    grid-gap: 10px;
    div {
        height: 80px;
        text-align: center;
    }

    & div:nth-child(12n) {
        margin-right: 0;
    }
}

.right-container {
    padding: 0 20px;
}

.right-title {
    display: flex;
    align-items: center;
    font-size: 14px;
    & div:first-child {
        width: 16px;
        height: 16px;
        border-radius: 50%;
        background-color: #19a4a0;
        z-index: 9;
    }
    & div:nth-child(2) {
        width: 16px;
        height: 16px;
        border-radius: 50%;
        background-color: #b2e1e0;
        transform: translateX(-50%);
    }
}

.process-record {
    margin-top: 20px;
    //   height: 60vh;
}

.btn-container {
    margin-top: 10px;
    display: flex;
    justify-content: space-around;
}

::v-deep .el-step__icon.is-text {
    background-color: #19a4a0;
    color: #19a4a0;
    border: none;
    width: 16px;
    height: 16px;
}

::v-deep .el-step.is-vertical .el-step__line {
    width: 2px;
    top: 26px;
    bottom: 8px;
    left: 7px;
}

::v-deep .el-step__title.is-finish {
    font-weight: bold;
    color: #303133;
    font-size: 16px;
}

::v-deep .el-step__title.is-wait {
    font-weight: bold;
    color: #303133;
    font-size: 16px;
}

.custom-description {
    padding: 8px 0 8px 20px;
    color: #666;
}

.node-info {
    // padding: 2px 0;
    padding-left: 20px;
    color: #666;
    letter-spacing: 1px;
}
</style>
