<template>
    <!-- 审批详情：查看、进行审批操作 -->
    <div class="approve-detail-wrap" v-if="isETAApprove">
        <div class="approve-detail">
            <div class="approve-info">
                <span>研报名称:{{reportInfo.title||''}}</span>
                <span>研报分类:{{reportInfo.classify||''}}</span>
                <span style="min-width: 100px;">发起人:{{reportInfo.approver||''}}</span>
            </div>
            <div class="approve-content" 
                v-loading="isLoading"
                element-loading-text="研报加载中...">
                <component v-if="reportInfo.reportId&&!isError"
                    :is="reportInfo.componentName"
                    :reportId="reportInfo.reportId"
                    :isPreview="true"
                    :isEn="reportInfo.type===2"
                    @reportStartLoading="isLoading=true"
                    @reportEndLoading="isLoading=false"
                    @reportError="isError=true"
                ></component>
                <tableNoData v-if="isError" text="无法获取到报告内容,该报告可能已被删除!"></tableNoData>
            </div>
        </div>
        <div class="approve-tool">
            <div class="tool-btn">
                <!-- 根据审批的状态决定显示 -->
                <el-button type="danger" @click="changeApprove('reject')"
                    v-if="formType==='approve'&&approveInfo.isCurrentApprover&&permissionBtn.isShowBtn('approvePermission','reportApprove_reject')">驳回</el-button>
                <el-button type="primary" @click="changeApprove('pass')"
                    v-if="formType==='approve'&&approveInfo.isCurrentApprover&&permissionBtn.isShowBtn('approvePermission','reportApprove_agree')">同意</el-button>
                <el-button type="primary" @click="changeApprove('return')"
                    v-if="formType==='myself'&&approveInfo.state!==4&&permissionBtn.isShowBtn('approvePermission','reportApprove_repeal')">撤销</el-button>
                <el-button type="primary" plain @click="$router.replace(`/approveList?formType=${formType}`)">返回</el-button>
            </div>
            <div class="approve-timeline-wrap">
                <p>审批流程</p>
                <div class="timeline">
                    <TimeLine 
                        :TimeLineData="TimeLineData"
                    />
                </div>
                <div class="approve-status" >
                    <img :src="require(`@/assets/img/approve_m/${approveInfo.stateText||'pending'}.png`)" alt="">
                </div>
            </div>
        </div>
        <RejectDialog 
            :isDetailDialogShow="isDetailDialogShow"
            :isEdit="true"
            @close="isDetailDialogShow=false;"
            @edit="rejectApprove"
        />
    </div>
    <div class="nodata-wrap approve-page-wrap" v-else>
        <tableNoData :text="pageLoading?'':'系统暂未开通审批流程，请开启审批流程后再进行操作！'"></tableNoData>
    </div>
</template>

<script>
import ReportDetail from '@/views/smartReport/reportDetail.vue';
import Reportdtl from '@/views/report_manage/reportdtl.vue'
import TimeLine from './components/timeLine.vue';
import RejectDialog from './components/rejectDialog.vue';
import {approveInterence} from '@/api/modules/approve.js';
import reportApproveConfig from "@/mixins/reportApproveConfig.js"

const ApproveType = ['','依次审批','会签','或签']
const ApproveState = ['','待审批','已同意','已驳回']
export default {
    mixins:[reportApproveConfig],
    components: { RejectDialog },
    data() {
        return {
            isError:false,
            isLoading:false,
            isDetailDialogShow:false,
            TimeLineData:[],
            formType:'detail',//进入审批详情的方式：approve(待处理)/detail(已处理)/myself(我发起的)
            reportInfo:{ //报告相关信息
                reportId:0,//研报or智能研报的报告id
                title:'',
                classify:'',
                approver:'',
                componentName:'',
                type:0,//1中文研报 2英文研报 3智能研报
            },
            approveInfo:{//审批相关的信息
                state:1,//当前审批的状态：1-待审批；2-已同意；3-已驳回；4-已撤回
                stateText:'pending',//审批状态对应图片文字：待审批(pending)，已同意(passed)，已驳回(reject)，已撤回(return)
                isCurrentApprover:false,//审批进行中的节点审批人是否是当前用户，控制通过&驳回按钮显示
            },
        };
    },
    computed:{
        UserId(){
            return Number(localStorage.getItem("AdminId"));
        }
    },
    methods: {
        getApproveDetail(){
            const {type,approveId} = this.$route.query
            if(!approveId) return 
            approveInterence.getApproveDetail({
                ReportApproveId:Number(approveId)
            }).then(res=>{
                if(res.Ret!==200) return
                //格式化时间线数据 
                this.formatTimeLineData(res.Data)
                const {Report={},Approve={}} = res.Data||{}
                this.reportInfo = {
                    reportId:Report.ReportId||0,
                    title:Report.ReportTitle||'',
                    classify:Report.ReportClassify||'',
                    approver:Approve.ApplyUserName||'',
                    componentName:Report.ReportType===3?'ReportDetail':'Reportdtl',
                    type:Report.ReportType
                }
                this.formType = type||'detail'
                this.approveInfo.state=Approve.State
                this.approveInfo.stateText=['','pending','passed','reject','return'][Approve.State]
            })
        },
        //转换接口数据
        formatTimeLineData({Approve={},ApproveFlowNodes=[]}){
            //发起人节点
            const startNode = {
                nodeType:1,
                nodeText:'发起人：',
                nodeStatus:'passed',
                approveList:[{
                    approverName:Approve.ApplyUserName||'',
                    approveTime:Approve.CreateTime||''
                }]
            }
            //排序过的审批节点，遍历
            let currentIndex = 0
            let Nodes = ApproveFlowNodes.map((i,index)=>{
                //找到当前节点的index
                if(i.ReportApproveNodeId===Approve.CurrNodeId){
                    currentIndex = index
                }
                //审批节点只有一个人时不显示是什么审批流
                const strApproveType = `（${ApproveType[i.ApproveType]}）`
                const node = {
                    nodeType:2,
                    nodeText:'审批人：'+i.Users.length+'人'+(i.Users.length>1?strApproveType:''),
                    nodeStatus:i.ReportApproveNodeId===Approve.CurrNodeId?'process':'future',
                    approveType:ApproveType[i.ApproveType]
                }
                const approveList = i.Users.map(u=>{
                    const {State='',ApproveTime='',ApproveRemark=''}=u.ApproveRecord||{}
                    return {
                        approverName:u.UserName,
                        approveStatus:ApproveState[State]||'',
                        approveTime:ApproveTime,
                        approveReason:ApproveRemark
                    }
                })
                //检测当前节点的User与当前用户是否匹配 且审批需要是待审批状态
                if(i.ReportApproveNodeId===Approve.CurrNodeId&&Approve.State===1){
                    //当前节点的User中，有没有当前用户
                    const hasUser = i.Users.findIndex(u=>u.UserId===this.UserId)
                    if(hasUser!==-1){
                        //只有依次审批需要看顺序
                        if(i.ApproveType===1){
                            this.approveInfo.isCurrentApprover = i.Users[hasUser].ApproveRecord?true:false
                        }else{
                            this.approveInfo.isCurrentApprover = true
                        }
                    }else{
                        this.approveInfo.isCurrentApprover = false
                    }
                }
                node.approveList = approveList
                return node
            })
            //将当前节点之前的置为通过节点，当前节点之后的置为未进行节点
            Nodes.forEach((n,index)=>{
                if(index<currentIndex){
                    n.nodeStatus = 'passed'
                }
                if(index>currentIndex){
                    n.nodeStatus = 'future'
                }
            })

            if(!Nodes.length){
                this.TimeLineData = [startNode,...Nodes]
                return
            }

            //如果当前审批是已驳回，移除当前节点后面的节点
            if(Approve.State===3){
                Nodes = Nodes.filter((_,index)=>index<=currentIndex)
                Nodes[currentIndex].nodeStatus = 'reject'
            }

            //如果当前审批已撤销，移除当前节点后面的节点,在最后加上撤销节点
            if(Approve.State===4){
                Nodes = Nodes.filter((_,index)=>index<=currentIndex)
                //检查最后一个节点是否有人审批
                let hasApprove = false
                let stateNum = 0
                Nodes[currentIndex].approveList.forEach(u=>{
                    if(u.approveStatus&&u.approveStatus!=='待审批'){
                        hasApprove = true
                    }
                    //依次审批和会签，计算已同意的数量
                    if(u.approveStatus==='已同意'){
                        stateNum++
                    }
                    if(u.approveStatus==='已驳回'){
                        Nodes[currentIndex].nodeStatus = 'reject'
                    }
                })
                //若审批撤销，则检查当前节点是否是通过节点
                if(Nodes[currentIndex].approveType!=='或签'&&stateNum===Nodes[currentIndex].approveList.length){
                    Nodes[currentIndex].nodeStatus = 'passed'
                }
                if(Nodes[currentIndex].approveType==='或签'&&stateNum>0){
                    Nodes[currentIndex].nodeStatus = 'passed'
                }
                //若没有人审批，则把这个节点删除
                !hasApprove&&(Nodes.pop())
                //在最后加上撤销节点
                Nodes.push({
                    nodeType:3,
                    nodeText:'发起人:',
                    nodeStatus:'return',
                    approveList:[{
                        approverName:(Approve.ApplyUserName||'')+'（已撤销）',
                        approveTime:Approve.ModifyTime||''
                    }],
                })
            }

            //如果当前审批已同意，则最后一个节点状态改为已同意
            if(Approve.State===2){
                Nodes[currentIndex].nodeStatus = 'passed'
            }

            //再次遍历Nodes
            //1.去除已同意的或签节点，没有审批的审批人状态
            //2.去除已驳回的节点，没有参与审批的审批人的状态
            Nodes.forEach(n=>{
                if(n.nodeStatus==='passed'||n.nodeStatus==='reject'){
                    n.approveList.forEach(a=>{
                        if(a.approveStatus==='待审批'){
                            a.approveStatus = ''
                        }
                    })
                }
            })

            this.TimeLineData = [startNode,...Nodes]
        },
        async changeApprove(type){
            const {approveId} = this.$route.query
            if(!approveId) return
            if(type==='reject'){
                this.isDetailDialogShow = true
                return 
            }
            let res = null
            if(type==='return'){
                res = await approveInterence.cancelApprove({
                    ReportApproveId:Number(approveId)
                })
            }
            if(type==='pass'){
                res = await approveInterence.passApprove({
                    ReportApproveId:Number(approveId)
                })
            }
            if(res.Ret!==200) return 
            this.$message.success(`${type==='return'?'撤销':'通过'}成功`)
            type!=='reject'&&(this.$router.replace("/approveList"))
        },
        rejectApprove(reason){
            this.isDetailDialogShow = false
            approveInterence.rejectApprove({
                ReportApproveId:Number(this.$route.query.approveId),
                ApproveRemark:reason||''
            }).then(res=>{
                if(res.Ret!==200) return 
                this.$message.success("驳回成功")
                this.$router.replace("/approveList")
            })
        }
    },
    mounted(){
        this.getApproveDetail()
    },
    components: { TimeLine, ReportDetail, Reportdtl, RejectDialog }
};
</script>

<style lang="scss">
.approve-detail-wrap{
    .approve-content{
        .smart-report-detail{
            .main-box{
                width: auto;
                box-sizing: border-box;
                margin:0;
                padding:10px;
                border:none !important;
                border-radius: 4px;
            }
        }
        #reportdtl{
            margin:0 auto;
            padding:10px;
            border:none !important;
            border-radius: 4px;
        }
    }
}
</style>
<style scoped lang="scss">
@import url('./css/pageStyle.scss');
.approve-detail-wrap{
    height: calc(100vh - 120px);
    display: flex;
    .approve-detail,.approve-tool{
        height: 100%;
        box-sizing: border-box;
    }
    .approve-tool{
        width:400px;
        min-width: 360px;
        background-color: #fff;
        display: flex;
        flex-direction: column;
        overflow: hidden;
        .tool-btn{
            padding:20px;
            text-align: right;
        }
        .approve-timeline-wrap{
            position: relative;
            margin-left:20px;
            flex:1;
            overflow-y: auto;
            .timeline{
                padding:20px;
                padding-left: 0;
            }
            .approve-status{
                position:absolute;
                width:200px;
                height:200px;
                right:0;
                bottom:0;
                overflow: hidden;
                pointer-events: none;
                img{
                    width:100%;
                    height:100%;
                }
            }
        }
    }
    .approve-detail{
        flex: 1;
        margin-right:20px;
        background-color: #fff;
        display: flex;
        flex-direction: column;
        .approve-info{
            display: flex;
            gap:60px;
            padding:15px 20px;
            border-bottom: 1px solid #C8CDD9;
        }
        .approve-content{
            flex: 1;
            min-width: 840px;
            padding:20px;
            overflow-y: auto;
            position:relative;
        }
    }
}
</style>
