<template>
<l-fullscreen-dialog
    :title="`${title}`"
    :visible.sync="midVisible"
    :showOk="false"

    @closed="handleClosed"
    @opened="handleOpened"

    ref="formDialog"
    >

    <template #headerRight v-if="isRead && task && task.f_State == 1" >
        <el-button size="mini" type="primary" @click="handleRead" >{{$t('确认阅读')}}</el-button>
    </template>

    <l-layout class="l-tab-page" :right="400">
        <l-panel :style="{'padding-right':isRead?'':0 }" >
            <div class="l-auto-window" style="padding: 0 8px;"  >
                <el-tabs v-model="activeName" @tab-click="handleTabClick" >
                    <el-tab-pane v-if="hasWfForm" :label="$t('表单信息')" name="form">
                        <div class="l-rblock" v-loading="formSchemeLoding">
                            <template v-if="showForm" >
                                <l-form-viewer 
                                    v-if="formType == '1'"
                                    :formInfo="formInfo"
                                    :isWfForm="true"
                                    :authFieldsMap="formAuthFieldsMap"
                                    ref="wfForm"
                                ></l-form-viewer>
                                <component ref="wfForm" v-else :requiredMap="formRequiredMap" :authFieldsMap="formAuthFieldsMap" :isWfForm="true" :is="sysFormComponent"></component>
                            </template>
                        </div>
                    </el-tab-pane>
                    <el-tab-pane :label="$t('流程信息')" name="wfinfo">
                        <l-layout style="background: #f1f2f5;" :right="320">
                            <l-panel class="flow-panel" style="padding:0;padding-top:0;" >
                                <template #title>
                                    <el-button-group>
                                        <el-tooltip effect="dark" :content="$t('复原')" placement="bottom">
                                            <el-button  size="mini" icon="el-icon-aim" @click="resetZoom"></el-button>
                                        </el-tooltip>
                                        <el-tooltip effect="dark" :content="$t('放大')" placement="bottom">
                                            <el-button  size="mini" icon="el-icon-zoom-in" @click="handlerZoom(0.1)"></el-button>
                                        </el-tooltip>
                                        <el-tooltip effect="dark" :content="$t('缩小')" placement="bottom">
                                            <el-button  size="mini" icon="el-icon-zoom-out" @click="handlerZoom(-0.1)"></el-button>
                                        </el-tooltip>
                                    </el-button-group>

                                    <div style="float:right;" >
                                        <el-tag size="small" effect="plain" style="margin-right: 8px;">正在审核</el-tag>
                                        <el-tag size="small" effect="plain" style="margin-right: 8px;" type="success">已审核</el-tag>
                                    </div>
                                    
                                </template>
                                <b-wflow-viewer
                                    ref="bflow" 
                                    @elementClick="elementClick"
                                    >
                                </b-wflow-viewer>
                            </l-panel>
                            <template #right >
                                 <l-panel v-if="nodeLogs.length>0" class="flow-panel" style="padding:0;padding-top:0;" >
                                     <template #title >
                                         记录信息
                                     </template>
                                     <div class="l-rblock l-time-line-wraper" style="padding:8px;overflow:hidden auto;" >
                                        <el-timeline>
                                            <el-timeline-item :type="item.type" v-for="(item,index) in nodeLogs" :key="index" :timestamp="item.time" placement="top">
                                                <el-card shadow="hover">
                                                    <div class="title" >{{item.name}}</div>
                                                    <div class="content">
                                                        <l-user v-for="(userId,index2) in item.userIds"  :key="index2" :value="userId" ></l-user>
                                                        {{item.des}}
                                                    </div>
                                                </el-card>
                                            </el-timeline-item>
                                        </el-timeline>
                                    </div>
                                 </l-panel>
                            </template>
                        </l-layout>
                    </el-tab-pane>
                    <el-tab-pane :label="$t('流转记录')" name="wflogs">
                        <div class="l-rblock l-time-line-wraper" style="padding:8px;overflow:hidden auto;" >
                            <el-timeline>
                                <el-timeline-item :type="item.type" v-for="(item,index) in logs" :key="index" :timestamp="item.time" placement="top">
                                    <el-card shadow="hover">
                                        <div class="title" >{{item.name}}</div>
                                        <div class="content">
                                            <l-user v-for="(userId,index2) in item.userIds"  :key="index2" :value="userId" ></l-user>
                                            {{item.des}}
                                        </div>
                                    </el-card>
                                </el-timeline-item>
                            </el-timeline>
                        </div>
                    </el-tab-pane>
                </el-tabs>
            </div>
        </l-panel>

        <template #right v-if="!isRead">
            <l-panel   style="padding-left:0;" title="审批栏" >
                <div class="l-rblock" style="padding:8px;" >
                   <el-form :model="formData" :rules="myRules" size="mini"  ref="form" >
                        <el-form-item :label="isCreateAgain?'备注':'审批意见'" prop="des">
                            <el-input
                                type="textarea"
                                v-model="formData.des"
                                placeholder="请输入"

                                rows="3"
                                >
                            </el-input >
                        </el-form-item>    
                        <el-form-item class="l-task-btns" > 
                            <el-button v-for="(btn,index) in taskBtns" :key="index" :type="btn.type" @click="handleBtnClick(btn)" >{{btn.name}}</el-button>
                        </el-form-item>         
                    </el-form>
                    <l-wf-audit-info :data="userLogs" ></l-wf-audit-info>
                </div>
            </l-panel>
        </template>
    </l-layout>


    <l-dialog   
        :width="500"
        :height="nodeUsers.length * 48 + 88"
        title="选择下一审核节点人员"
        :visible.sync="selectUsersVisible"
        @ok="handleSelectUsersSave"
        @close="handleSelectUsersCloseForm"

        :showClose="false"
        >
        <select-users ref="selectUsers" :nodeList="nodeUsers"></select-users>
    </l-dialog>

    <l-dialog
        :title="$t(tUserType == 1?`选择转移人员`:`选择加签人员`)"
        :visible.sync="selectTUserVisible"
        :height="480"
        width="1024px"
        :hasBtns="false"
    >
        <l-user-select-panel  @change="handleChange" :multiple="false" ref="userSelectPanel" ></l-user-select-panel>
    </l-dialog>

    <l-dialog 
        :title="$t('驳回节点选择')"
        :visible.sync="selectRejectNodeVisible"
        :height="136"
        :width="500"

        @ok="handleSelectRejectNodeSave"
        @close="handleRejectNodeCloseForm"

        :showClose="false"
    >
        <select-reject-node ref="selectRejectNode" :nodeList="completedNodes"></select-reject-node>
    </l-dialog>

    <!--选择签章-->
    <l-dialog 
        :title="$t('选择签章')"
        :visible.sync="selectSignVisible"
        :height="480"
        :width="508"

        @ok="handleSelectSignSave"
        @closed="handleSelectSignCloseForm"
        @opened="handleSelectSignOpenForm"
    >
        <select-sign ref="SelectSign" ></select-sign>
    </l-dialog>
</l-fullscreen-dialog>
</template>

<script>
import mixin from '../../../mixins/wf'
import SelectUsers from './selectAuditUsers.vue'
import SelectRejectNode from './selectRejectNode.vue'
import SelectSign from './selectSign.vue'

const api = window.$api.workflow.process
const apiStamp = window.$api.workflow.stamp

export default {
    mixins:[mixin()],
    components:{
        SelectUsers,
        SelectRejectNode,
        SelectSign
    },
    props:{
        isCreateAgain:Boolean,
        isRead:Boolean
    },
    data () {
        return {
            midVisible:false,
            formData:{
                des:''
            },
            rules:{
                des:[
                    { required: true, message: '请填写审批意见',trigger: 'blur' }
                ],
            },

            currentBtn:null,
            
            nodeUsers:[],
            selectUsersVisible:false,
            selectTUserVisible:false,
            tUserType:1, // 1 转移 2 加签,

            selectRejectNodeVisible:false, // 驳回节点选择
            selectSignVisible:false, // 选择签章
            stampList:[]
        }
    },
    computed:{
        myRules(){
            if(this.isCreateAgain || this.isRead){
                return {}
            }
            else{
                return this.rules
            }
        },
        completedNodes(){
            const nodes = this.$deepClone(this.wfData)
            return nodes.filter(t=>t.hasFinish && t.id != this.currentNode.id)
        },
    },
    watch:{
        visible: {
            handler (n) {
                this.midVisible = n
            }
        },
    },
    methods:{
        resetZoom(){
            this.$refs.bflow.reset()
        },
        handlerZoom(r){
            this.$refs.bflow.handlerZoom(r)
        },
        elementClick(node){
            if(node){
                this.nodeLogs = this.nodeMap[node.id] || []
            }
            else{
                this.nodeLogs = []
            }
        },

        resetFormToMe(){
            this.$refs.form && this.$refs.form.resetFields()
            this.taskBtns = []
        },
        setForm(){
            this.$refs.form && this.$refs.form.clearValidate()
            this.currentNode = this.wfData.find(t=>t.id == this.task.f_UnitId)

            // 设置审核按钮
            const btns = []
            if(this.currentNode.type =='startEvent'){
                btns.push({
                    code:'learun_create',
                    name:'提交',
                    type:'primary'
                })
            }
            else{
                this.currentNode.btnlist.forEach(btn => {
                    if(btn.code == 'agree'){
                        btn.type = 'primary'
                    }
                    else if(btn.code == 'disagree'){
                        btn.type = 'danger'
                    }
                    btns.push(btn)
                })

                if(this.currentNode.isAddSign){
                    btns.push({
                        code:'learun_sign',
                        name:'加签',
                        type:'success'
                    })
                }

                if(this.currentNode.isTransfer){
                    btns.push({
                        code:'learun_transfer',
                        name:'转移',
                        type:'success'
                    })
                }
            }
            this.taskBtns = btns
        },

        validateForm(){
            return this.$formValidateWraper(this.$refs.form)
        },

        handleBtnClick(btn){
            this.$refs.formDialog.showLoading('流程处理中...')
            this.$nextTick(async ()=>{
                this.currentBtn = btn

                if(!(await this.validateForm())){
                    this.$refs.formDialog.hideLoading()
                    return
                }

                if(!(await this.validateWfForm())){
                    this.$refs.formDialog.hideLoading()
                    return
                }

                if(!(await this.saveWfForm(btn.code))){
                    this.$refs.formDialog.hideLoading()
                    return 
                }
                let res
                switch(btn.code){
                    case 'learun_create':
                        res = await this.$awaitWraper(api.createAgain({
                            processId:this.processId,           
                            des:`重新提交${this.formData.des?'-':''}${this.formData.des}` 
                        }))
                        break
                    case 'learun_sign':
                        this.tUserType = 2
                        this.selectTUserVisible = true
                        break
                    case 'learun_transfer':
                        this.tUserType = 1
                        this.selectTUserVisible = true
                        break
                    default:
                        if(this.task.f_Type == 6){// 加签审核
                            res = await this.$awaitWraper(api.signAudit(this.taskId,{
                                code:btn.code,
                                name:btn.name,
                                des:this.formData.des
                            }))
                        }
                        else {
                            if(this.currentNode.rejectType == '2' && btn.code == 'disagree'){
                                this.selectRejectNodeVisible = true
                                this.$refs.formDialog.hideLoading()
                                return 
                            }

                            if(btn.isSign){
                                // 加载签章数据
                                const stampList = await this.$awaitWraper(apiStamp.getList(this.loginInfo.f_UserId))

                                if(stampList && stampList.length >0){
                                    this.stampList = stampList
                                    this.selectSignVisible = true
                                    this.$refs.formDialog.hideLoading()
                                    return
                                }
                            }
                            
                            res = await this.audit()
                        }

                        break
                }
                this.$refs.formDialog.hideLoading()
                if(res){
                    this.midVisible = false
                    this.$emit('refresh')
                }
            })
        },

        async audit(){
            // 获取接下来节点审核人
            if(this.currentBtn.isNextAuditor){
                const res = await api.getNextUsers({processId:this.processId,nodeId:this.currentNode.id})
                const nodeUserMap = res.data.data
                const nodeUsers = []
                for(let key in nodeUserMap){
                    const nodeUserItem = nodeUserMap[key]
                    if(nodeUserItem.length > 1){
                        nodeUsers.push({
                            name:this.wfData.find(t=>t.id == key).name,
                            id:key,
                            options:nodeUserItem.map(t=>{return{value:t.id,label:t.name} })
                        })
                    }
                }

                this.nodeUsers = nodeUsers

                if(this.nodeUsers.length > 0){
                    this.selectUsersVisible = true
                    return
                }
            }


            return await this.$awaitWraper(api.audit(this.taskId,{
                code:this.currentBtn.code,
                name:this.currentBtn.name,
                des:this.formData.des
            }))
        },



        handleSelectUsersSave(){
            this.selectUsersVisible = false
            this.$refs.formDialog.showLoading('流程处理中...')
            const nextUsers = this.$refs.selectUsers.getForm()
            this.$nextTick(async ()=>{
                const res = await this.$awaitWraper(api.audit(this.taskId,{
                    code:this.currentBtn.code,
                    name:this.currentBtn.name,
                    nextUsers: nextUsers,
                    des:this.formData.des
                }))
                if(res){
                    this.midVisible = false
                }
                this.$refs.formDialog.hideLoading()
                this.$emit('refresh')
            })
        },
        handleSelectUsersCloseForm(){
            this.$refs.selectUsers.resetForm()
        },
        handleChange(userInfo){
            if(userInfo){
                const title = this.tUserType == 1?'转移':'加签'
                if(this.loginInfo.f_UserId == userInfo.f_UserId){
                    this.$message({
                        type: 'warning',
                        message: `${title}不能给自己本人`
                    })     
                    return
                }

                
                this.$confirm(`是否确定${title}给${userInfo.f_RealName}?`, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.selectTUserVisible = false
                    this.$refs.formDialog.showLoading('流程处理中...')
                    
                    this.$nextTick(async ()=>{
                        let res

                        if(this.tUserType == 1){
                            res = await this.$awaitWraper(api.transferUser(this.taskId,{
                                toUserId:userInfo.f_UserId,           
                                des:`转移给${userInfo.f_RealName}${this.formData.des?'-':''}${this.formData.des}` 
                            }))
                        }
                        else{
                            res = await this.$awaitWraper(api.sign(this.taskId,{
                                toUserId:userInfo.f_UserId,           
                                des:`加签给${userInfo.f_RealName}${this.formData.des?'-':''}${this.formData.des}` 
                            }))
                        }

                        this.$refs.formDialog.hideLoading()

                        if(res){
                            this.midVisible = false
                            this.$emit('refresh')
                        }
                    })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: `已取消${title}`
                    })         
                })

            }
        },

        async handleSelectRejectNodeSave(){
            if(await this.$refs.selectRejectNode.validateForm()){
                this.$refs.formDialog.showLoading('流程处理中...')
                const nextId = this.$refs.selectRejectNode.getForm()
                this.selectRejectNodeVisible = false
                this.$nextTick(async ()=>{
                    const res = await this.$awaitWraper(api.audit(this.taskId,{
                        code:this.currentBtn.code,
                        name:this.currentBtn.name,
                        nextId: nextId,
                        des:this.formData.des
                    }))
                    if(res){
                        this.midVisible = false
                    }
                    this.$refs.formDialog.hideLoading()
                    this.$emit('refresh')
                })
            }
        },
        handleRejectNodeCloseForm(){
            this.$refs.selectRejectNode.resetForm()
        },

        async handleRead(){
            
            this.$refs.formDialog.showLoading('流程处理中...')
            const res = await this.$awaitWraper(api.readAudit(this.taskId))
            if(res){
                this.midVisible = false
            }
            this.$refs.formDialog.hideLoading()
            this.$emit('refresh')
        },


        // 签章
        async handleSelectSignSave(){
            if(await this.$refs.SelectSign.validateForm()){
                this.$refs.formDialog.showLoading('流程处理中...')
                const {f_StampId,f_Password} = this.$refs.SelectSign.getForm()
                this.selectSignVisible = false
                this.$nextTick(async ()=>{
                    const res = await this.$awaitWraper(api.audit(this.taskId,{
                        code:this.currentBtn.code,
                        name:this.currentBtn.name,
                        stampImg:f_StampId,
                        stampPassWord:f_Password,
                        des:this.formData.des
                    }))
                    if(res){
                        this.midVisible = false
                    }
                    this.$refs.formDialog.hideLoading()
                    this.$emit('refresh')
                })

            }
        },
        handleSelectSignCloseForm(){
            this.$refs.SelectSign.resetForm()
        },
        handleSelectSignOpenForm(){
            this.$refs.SelectSign.setForm(this.stampList)
        }
    }
}
</script>

<style lang="scss">
    .l-task-btns{
        .el-button{
            margin: 0;
            margin-top: 8px;
            margin-right: 8px;
        }
    }
</style>