<template>
    <div class="layout-container">
    <div class="layout-padding w100">
    <div class="layout-padding-auto layout-padding-view">
<!--        <div style="margin-bottom: 10px;">
            <div style="font-size: 20px;">{{ data.currJob.flowName }}</div>
            <div style="font-weight: 300;">
                <span >发起人：{{ data.currJob.initiatorName }}</span>
                <span style="margin-left: 10px">发起时间：{{ data.currJob.initiatorTime }}</span>
            </div>
        </div>-->
        <!-- 选项卡tabs -->
        <el-tabs ref="tabs" v-model="data.currElTab.active" @tab-click="methods.handleClick">
            <el-tab-pane v-for="(item, index) in data.elTabs"
                         :key="index"
                         :label="item.formName"
                         :name="item.id">
                <template #label>
                    <div>
                        <i :class="item.icon" style="vertical-align: middle;margin-right: 3px"></i>
                        <span style="vertical-align: middle;">{{ item.formName }}</span>
                    </div>
                </template>
            </el-tab-pane>
        </el-tabs>

        <div id="handle_job">

        <!-- 动态组件 -->
        <template v-if="data.currElTab.path && data.currElTab.path.startsWith('http')">
            <dynamic-iframe v-if="data.currElTab.active" :currJob="data.currJob" :currElTab="data.currElTab" @handleJob="methods.handleJob"></dynamic-iframe>
        </template>
        <template v-else>
            <dynamic-link v-if="data.currElTab.active" :currJob="data.currJob" :currElTab="data.currElTab" @handleJob="methods.handleJob"></dynamic-link>
        </template>

        <!-- 审批项 -->
        
        
        <el-form v-if="!data.currJob.hiJob && !orderVue.vueKeySys.sysPaths.includes(data.currElTab.path)" label-width="72px" style="margin-top: 22px;">
            
            <template v-if="data.currElTab.isAutoAudit !== '1'">
                <el-form-item :label="t('jfcomment.remark')">
                    <el-input v-model="data.currJob.comment" :autosize="{ minRows: 3, maxRows: 6}" maxlength="50" show-word-limit
                              type="textarea" :placeholder="t('jfcomment.inputRemarkTip')">
                    </el-input>
                </el-form-item>
                <el-form-item :label="t('jfcomment.signName')" style="display: none">
                    <sign-name ref="signNameRef" :currJob="data.currJob"></sign-name>
                </el-form-item>
                <el-form-item>
                    <template v-for="(jobBtn, index) in data.jobBtns.length > 6 ? data.jobBtns.slice(0, 6) : data.jobBtns" :key="index">
                        <el-button :loading="data.loading"
                                   v-if="/*methods.handleJobBtns(jobBtn) */ true"
                                   icon="Check"
                                   plain
                                   @click="methods.handleJob(jobBtn, true)">{{ methods.getJobBtnName(jobBtn) }}
                        </el-button>
                    </template>
                    <el-dropdown max-height="500px" size="small" style="vertical-align: middle; margin-left: 10px" placement="top" v-if="data.jobBtns.length > 6">
                        <el-button icon="More">{{ t('jfI18n.more') }}</el-button>
                        <template #dropdown>
                            <el-dropdown-menu v-if="/*methods.handleJobBtns(jobBtn) */ true">
                                <template v-for="(jobBtn, index) in data.jobBtns.slice(6)" :key="index">
                                    <el-dropdown-item @click.native="methods.handleJob(jobBtn, true)" divided>
                                        {{ methods.getJobBtnName(jobBtn) }}
                                    </el-dropdown-item>
                                </template>
                            </el-dropdown-menu>
                        </template>
                    </el-dropdown>
                </el-form-item>
            </template>
        </el-form>

        </div>

        <el-dialog
                v-if="data.showToRunNode"
                v-model="data.showToRunNode"
                top="20px"
                width="70%"
                title="选择任意驳回节点"
                append-to-body>
            <run-reject :curr-job="data.currJob" @onRejectJob="btnMethods.onRejectJob"></run-reject>
        </el-dialog>

        <el-dialog
                v-if="data.showJumpToRunNode"
                v-model="data.showJumpToRunNode"
                top="20px"
                width="70%"
                title="选择任意跳转节点"
                append-to-body>
            <run-any-jump :curr-job="data.currJob" @onAnyJumpJob="btnMethods.onAnyJumpJob"></run-any-jump>
        </el-dialog>

        <el-dialog
                v-if="data.showJobSignature"
                v-model="data.showJobSignature"
                top="20px"
                width="70%"
                :title="data.jobSignatureTitle"
                append-to-body>
            <job-signature :curr-job="data.currJob" @onJobSignature="btnMethods.onJobSignature"></job-signature>
        </el-dialog>

        <el-dialog
                v-if="data.showJobCopyPass"
                v-model="data.showJobCopyPass"
                top="20px"
                width="70%"
                :title="data.jobSignatureTitle"
                append-to-body>
            <copy-pass-job :curr-job="data.currJob" @onJobSignature="btnMethods.onJobSignature"></copy-pass-job>
        </el-dialog>

        <el-dialog
                v-if="data.showNodeSignature"
                v-model="data.showNodeSignature"
                top="20px"
                width="70%"
                :title="data.nodeSignatureTitle"
                append-to-body>
            <node-signature :curr-job="data.currJob" @onNodeSignature="btnMethods.onNodeSignature"></node-signature>
        </el-dialog>

        <el-dialog
                v-if="data.showDistPerson"
                v-model="data.showDistPerson"
                top="20px"
                width="70%"
                title="分配参与者"
                append-to-body>
            <dist-person :curr-job="data.currJob"></dist-person>
        </el-dialog>

        <user-role-picker ref="userRolePicker" :isOnlyOne="true" @onSelectItems="btnMethods.onSelectItems">
        </user-role-picker>

    </div>
    </div>
    </div>
</template>

<script setup lang="ts" name="HandleJob">
    import {useI18n} from 'vue-i18n';
    import {deepClone} from "/@/utils/other";
    import {useMessage, useMessageBox} from "/@/hooks/message";
    import {useUserInfo} from "/@/stores/userInfo";
    import {TabsPaneContext} from "element-plus";
    import * as orderVue from "/@/api/order/order-key-vue";
    import {validateNull} from "/@/utils/validate";
    import {DIC_PROP} from "../../support/dict-prop";
    import {getJobBtnName} from "../../index";
    import * as doJob from "/@/api/jsonflow/do-job";
    import * as runNode from "/@/api/jsonflow/run-node";
    import * as runFlow from "/@/api/jsonflow/run-flow";
    import mittBus from '/@/utils/mitt';
    import {useFlowJob} from "../../stores/flowJob";
    import {setPropsDataValue} from "../../support/common";
    import {initHandleJobHeight} from "../../utils";
    import {handleTodoDetail, handleToDoneDetail} from "../../support/extend";

    const {t} = useI18n();
    const userInfo = useUserInfo();
    const $message = useMessage();
    const flowJob = useFlowJob();
    const route = useRoute();
    const {proxy} = getCurrentInstance();

    // 引入组件
    const DynamicLink = defineAsyncComponent(() => import('./dynamic-link.vue'));
    const DynamicIframe = defineAsyncComponent(() => import('./dynamic-iframe.vue'));
    const SignName = defineAsyncComponent(() => import('../sign-name/index.vue'));
    const UserRolePicker = defineAsyncComponent(() => import('../user-role/picker.vue'));
    const JobSignature = defineAsyncComponent(() => import('./job-signature.vue'));
    const CopyPassJob = defineAsyncComponent(() => import('./copy-pass-job.vue'));
    const NodeSignature = defineAsyncComponent(() => import('./node-signature.vue'));
    const RunReject = defineAsyncComponent(() => import('/@/views/jsonflow/run-reject/flow.vue'));
    const RunAnyJump = defineAsyncComponent(() => import('/@/views/jsonflow/run-job/flow.vue'));
    const DistPerson = defineAsyncComponent(() => import('/@/views/jsonflow/dist-person/flow.vue'));

    const props = defineProps({
        currJob: {
            type: Object,
            default: {},
        }
    });
    const data = reactive({
        currJob: {},
        // 0、转办 1、下一办理人
        nodeUserType: undefined,
        jobSignatureTitle: undefined,
        showJobSignature: false,
        showJobCopyPass: false,
        nodeSignatureTitle: undefined,
        showNodeSignature: false,
        showJumpToRunNode: false,
        showToRunNode: false,
        showDistPerson: false,
        elTabs: {},
        jobBtns: [],
        currElTab: {active: null},
        loading: false,
    });

    const channel = new BroadcastChannel('currJob_channel');
    const btnMethods = {
        onHandleJob(jobBtn) {
            data.currJob.jobBtn = jobBtn
            let nodeSignatures = [DIC_PROP.JOB_BTNS[1].value, DIC_PROP.JOB_BTNS[2].value, DIC_PROP.JOB_BTNS[3].value];
            if (jobBtn === DIC_PROP.JOB_BTNS[13].value) btnMethods.openJobRoleUserId('1')
            else if (jobBtn === DIC_PROP.JOB_BTNS[14].value) btnMethods.openJobRoleUserId('0');
            else if (jobBtn === DIC_PROP.JOB_BTNS[15].value) btnMethods.handleTerminateFlow(data.currJob);
            else if (jobBtn === DIC_PROP.JOB_BTNS[16].value) btnMethods.handleEarlyComplete(data.currJob);
            else if (jobBtn === DIC_PROP.JOB_BTNS[17].value) btnMethods.handleInvalidFlow(data.currJob);
            else if (jobBtn === DIC_PROP.JOB_BTNS[18].value) btnMethods.doDistPerson();
            else if (jobBtn === DIC_PROP.JOB_BTNS[11].value) btnMethods.doJobSignature(jobBtn)
            else if (jobBtn === DIC_PROP.JOB_BTNS[12].value) btnMethods.doJobSignature(jobBtn)
            else if (jobBtn === DIC_PROP.JOB_BTNS[7].value) btnMethods.onBackFirstJob(data.currJob)
            else if (jobBtn === DIC_PROP.JOB_BTNS[8].value) btnMethods.onBackPreJob(data.currJob)
            else if (nodeSignatures.includes(jobBtn)) btnMethods.doNodeSignature(jobBtn)
            else btnMethods.doHandleJob(jobBtn)
        },
        doHandleJob(jobBtn) {
            data.currJob.jobBtn = jobBtn
            if (jobBtn === DIC_PROP.JOB_BTNS[9].value) {
                return btnMethods.doAnyJumpJob()
            }
            if (jobBtn === DIC_PROP.JOB_BTNS[10].value) {
                return btnMethods.doRejectJob()
            }
            let jobSignatures = [DIC_PROP.JOB_BTNS[4].value, DIC_PROP.JOB_BTNS[5].value, DIC_PROP.JOB_BTNS[6].value];
            if (jobSignatures.includes(jobBtn)) {
                return btnMethods.doJobSignature(jobBtn)
            }
            doJob.complete(data.currJob).then(() => {
                $message.success('审批成功')
                btnMethods.onContextmenuClose()
            })
        },
        onBackFirstJob(currJob) {
            doJob.backFirstJob(currJob).then(() => {
                $message.success('退回首节点成功')
                btnMethods.onContextmenuClose()
            })
        },
        onBackPreJob(currJob) {
            doJob.backPreJob(currJob).then(() => {
                $message.success('退回上一步成功')
                btnMethods.onContextmenuClose()
            })
        },
        doAnyJumpJob() {
            data.currJob.runRejectVO = {}
            data.showJumpToRunNode = true
        },
        onAnyJumpJob(currJob) {
            doJob.anyJump(currJob).then(() => {
                $message.success('跳转成功')
                data.showJumpToRunNode = false
                btnMethods.onContextmenuClose()
            })
        },
        doRejectJob() {
            data.currJob.runRejectVO = {}
            data.showToRunNode = true
        },
        onRejectJob(currJob) {
            doJob.reject(currJob).then(() => {
                $message.success('驳回成功')
                data.showToRunNode = false
                btnMethods.onContextmenuClose()
            })
        },
        doDistPerson() {
            data.showDistPerson = true
        },
        doJobSignature(jobBtn) {
            data.currJob.nodeJobSigned = {}
            data.jobSignatureTitle = getJobBtnName(jobBtn);
            if (jobBtn === DIC_PROP.JOB_BTNS[11].value || jobBtn === DIC_PROP.JOB_BTNS[12].value) {
                data.currJob.nodeJobSigned.signedType = DIC_PROP.SIGNATURE_TYPE[2].value
                if (jobBtn === DIC_PROP.JOB_BTNS[11].value) data.currJob.nodeJobSigned.belongType = '1'
                else data.currJob.nodeJobSigned.belongType = '2'
                data.showJobCopyPass = true
            } else {
                let type = DIC_PROP.SIGNATURE_TYPE[0].value
                if (DIC_PROP.JOB_BTNS[5].value === jobBtn) type = DIC_PROP.SIGNATURE_TYPE[1].value
                else if (DIC_PROP.JOB_BTNS[6].value === jobBtn) type = DIC_PROP.SIGNATURE_TYPE[2].value
                data.currJob.nodeJobSigned.signedType = type
                data.currJob.nodeJobSigned.belongType = '0'
                data.showJobSignature = true
            }
        },
        doNodeSignature(jobBtn) {
            data.currJob.nodeJobSigned = {}
            data.nodeSignatureTitle = getJobBtnName(jobBtn);
            data.currJob.nodeJobSigned.signedType = DIC_PROP.NODE_SEQUENTIAL_TYPE[2].value
            let nodeType = DIC_PROP.NODE_TYPE[1].value
            let type = DIC_PROP.NODE_SIGNATURE_TYPE[0].value
            if (DIC_PROP.JOB_BTNS[2].value === jobBtn) type = DIC_PROP.NODE_SIGNATURE_TYPE[1].value
            else if (DIC_PROP.JOB_BTNS[3].value === jobBtn) {
                type = DIC_PROP.NODE_SIGNATURE_TYPE[2].value
                nodeType = DIC_PROP.NODE_TYPE[2].value
                if (data.currJob.runNodeVO.nodeType !== nodeType) {
                    $message.info('当前节点不是并行节点，必须在并行节点上才能加并节点')
                    return
                }
            }
            data.currJob.nodeJobSigned.nodeSignedType = type
            data.currJob.nodeJobSigned.nodeType = nodeType
            data.showNodeSignature = true
        },
        onJobSignature(currJob) {
            doJob.signature(currJob).then(() => {
                if (data.currJob.nodeJobSigned.belongType !== '0') {
                    if (data.currJob.nodeJobSigned.belongType === '1') $message.success('抄送成功')
                    else $message.success('传阅成功')
                    data.showJobCopyPass = false
                }
                else {
                    $message.success('加签成功')
                    data.showJobSignature = false
                }
                if (DIC_PROP.SIGNATURE_TYPE[2].value !== data.currJob.nodeJobSigned.signedType) {
                    btnMethods.onContextmenuClose()
                }
            })
        },
        onNodeSignature(currJob) {
            runNode.signature(currJob).then(() => {
                $message.success('加节点成功')
                data.showNodeSignature = false
                if (DIC_PROP.NODE_SIGNATURE_TYPE[2].value !== data.currJob.nodeJobSigned.nodeSignedType) {
                    btnMethods.onContextmenuClose()
                }
            })
        },
        // 选择参与者
        openJobRoleUserId(type) {
            data.nodeUserType = type
            proxy.$refs.userRolePicker.onOpen();
        },
        onSelectItems(items) {
            if (data.nodeUserType === '1') {
                btnMethods.onJobNextUserRole(items[0])
            } else {
                btnMethods.onTurnRunJob(items[0])
            }
        },
        // 提前结束流程
        handleEarlyComplete(row) {
            useMessageBox().prompt('请输入提前结束流程理由')
                .then(({ value }) => {
                    row.jobBtn = DIC_PROP.JOB_BTNS[16].value
                    row.invalidReason = value
                    row.flowStatus = '0'
                    return runFlow.earlyComplete(row)
                }).then(() => {
                $message.success('操作成功')
                btnMethods.onContextmenuClose()
            })
        },
        // 终止流程
        handleTerminateFlow(row) {
            useMessageBox().prompt('请输入终止理由')
                .then(({ value }) => {
                    row.jobBtn = DIC_PROP.JOB_BTNS[15].value
                    row.invalidReason = value
                    row.flowStatus = '0'
                    return runFlow.terminateFlow(row)
                }).then(() => {
                $message.success('操作成功')
                btnMethods.onContextmenuClose()
            })
        },
        // 作废流程
        handleInvalidFlow(row) {
            useMessageBox().prompt('请输入作废理由')
                .then(({ value }) => {
                    row.jobBtn = DIC_PROP.JOB_BTNS[17].value
                    row.invalidReason = value
                    row.flowStatus = '0'
                    return runFlow.invalidFlow(row)
                }).then(() => {
                $message.success('操作成功')
                btnMethods.onContextmenuClose()
            })
        },
        // 转办任务
        onTurnRunJob(role) {
            useMessageBox()
                .confirm('是否确认转办名称为"' + data.currJob.jobName + '"的任务?')
                .then(() => {
                    data.currJob.jobType = role.jobType
                    data.currJob.roleId = role.roleId
                    data.currJob.jobBtn = DIC_PROP.JOB_BTNS[14].value
                    return doJob.turnRunJob(data.currJob)
                }).then(() => {
                $message.success('操作成功')
                btnMethods.onContextmenuClose()
            })
        },
        // 指定下一办理人
        onJobNextUserRole(role) {
            useMessageBox()
            .confirm('是否确认指定下一步参与者?')
            .then(() => {
                data.currJob.nextUserRole = role
                return btnMethods.doHandleJob(DIC_PROP.JOB_BTNS[13].value)
            })
        },
        onContextmenuClose() {
            // flowJob.delJobLen()
            btnMethods.postMessage()
            // 防止重复进入
            if (route.fullPath.indexOf('tokenLoaded') === -1) {
                let source = { contextMenuClickId: 1, ...route }
                mittBus.emit('onCurrentContextmenuClick', Object.assign({}, source));
            } else {
                let timer = setTimeout(() => {
                    window.close();
                    clearTimeout(timer);
                }, 2000);
            }
        },
        postMessage() {
            channel.postMessage({ type: 'currJob', data: '' });
        }
    }

    const $route = useRoute();
    const methods = {
        // 初始化数据
        async initJobData() {
            data.loading = false
            let row = { }
            if (!validateNull(props.currJob)) row = props.currJob
            else {
                setPropsDataValue(row, $route.query, 'id', 'flowInstId', 'isHiJob', 'isView', 'isRead', 'isApp', 'isForm')
            }

            if (row.isHiJob !== '0') {
                await handleToDoneDetail(row, data, row.isApp, row.isForm);
            } else {
                await handleTodoDetail(row, data, row.isView, row.isRead, $message, btnMethods.postMessage);
            }
            data.jobBtns = data.currJob.jobBtns
            methods.handleElTabs()
            data.currJob.resolveSaves = []
            data.currJob.resolveMethods = []
            nextTick(() => {
                initHandleJobHeight(data)
            })
        },
        // 处理tabs
        handleElTabs() {
            data.elTabs = methods.removeCloneElTab()
            // 排序
            let elTab = data.elTabs.sort((s1, s2) => {
                return s1.sort - s2.sort
            }).find(f => f.isActive === '1')
            // 默认展示的tab
            if (elTab) data.currElTab = elTab
            else data.currElTab = data.elTabs[0]

            data.currElTab.active = data.currElTab.id
            data.currJob.currElTab = data.currElTab
        },
        removeCloneElTab() {
            // 判断是否显隐
            let clone = deepClone(data.currJob.elTabs)
            let conditions = orderVue.handleElTab(data.currJob)
            conditions.forEach(cd => {
                if (!cd.isShow || cd.isShow === '0') {
                    data.currJob.elTabs = data.currJob.elTabs.filter(f => f.path !== cd.path);
                    clone = clone.filter(f => f.path !== cd.path)
                }
            })
            return clone
        },
        // 页面选择
        handleClick(tab: TabsPaneContext) {
            if (data.currElTab.id === tab.paneName) return
            // 切换页面
            data.currElTab = data.elTabs.find(f => f.id === tab.paneName)
            data.currElTab.active = data.currElTab.id
            data.currJob.currElTab = data.currElTab
            // 影藏弹出框滚动条
            initHandleJobHeight(data)
        },
        // 提交任务
        async handleJob(jobBtn, isAudit) {
            // 提交时自动审批
            if (proxy.$refs.signNameRef) {
                await proxy.$refs.signNameRef.handleGenerate()
            }
            let b = jobBtn !== DIC_PROP.JOB_BTNS[0].value
            if (b) {
                methods.timeoutLoading()
                btnMethods.onHandleJob(jobBtn)
                return
            }
            // 审批前回调函数
            let resolveMethods = data.currJob.resolveMethods
            if (!validateNull(resolveMethods)) {
                for (const resolveMethod of resolveMethods) {
                    if (resolveMethod) {
                        methods.timeoutLoading()
                        let isPass = await resolveMethod();
                        if (isPass !== true) return
                    }
                }
            }
            // 审批前保存回调函数
            let resolveSaves = data.currJob.resolveSaves
            if (isAudit && !validateNull(resolveSaves)) {
                for (const resolveSave of resolveSaves) {
                    if (resolveSave) {
                        methods.timeoutLoading()
                        await resolveSave();
                    }
                }
            }
            // 判断页面是否保存
            let hiJob = data.currJob.hiJob;
            let elTabs = data.currJob.elTabs.filter(f => (f.isFormEdit !== '0' && !hiJob))
            if (elTabs) {
                let find = elTabs.find(f => f.isSave !== true);
                // 这里测试流程，临时屏蔽判断 todo
                if (find) useMessage().info(find.formName + ' 未保存')
                else {
                    methods.timeoutLoading()
                    btnMethods.onHandleJob(jobBtn)
                }
                return
            }
            methods.timeoutLoading()
            btnMethods.onHandleJob(jobBtn)
        },
        handleJobBtns(jobBtn) {
            // TODO 可在此处做全局权限判断
            let value = DIC_PROP.JOB_BTNS[13].value;
            let next = userInfo.userInfos.authBtnList.some(v => v === 'jsonflow_runjob_invalid');
            if (next) {
                return (jobBtn === value && next) || jobBtn !== value
            } else return jobBtn !== value
        },
        getJobBtnName(jobBtn) {
            return getJobBtnName(jobBtn)
        },
        timeoutLoading() {
            data.loading = true
            setTimeout(() => {// 防重复提交
                data.loading = false
            }, 3 * 1000)
        }
    }

    // 监听双向绑定
    watch(
        () => props.currJob.id,
        (val) => {
            methods.initJobData();
        }
    );

    onMounted(() => {
        methods.initJobData();
    });
</script>

<style lang="scss">
  @import "../../../flow/components/style/flow-drawer.scss";
</style>
