<template>
    <div>
        <!-- 发起工单 -->
        <el-drawer
                class="flow-overflow-drawer" direction="rtl"
                append-to-body size="90%"
                v-if="data.showInitiateOrder"
                v-model="data.showInitiateOrder"
                @closed="handleClosed()"
        >
            <el-tabs class="flow-predict_display_center" v-model="data.currActive" @tab-click="handleTabClick">
                <el-tab-pane label="① 录入表单" name="form"></el-tab-pane>
                <el-tab-pane label="② 流程预测" name="flow"></el-tab-pane>
                <el-tab-pane label="③ 审批预测" name="comment"></el-tab-pane>
            </el-tabs>

            <div id="predictFormHeight" style="height: 850px; overflow-y: auto">
                <slot :currActive="data.currActive"></slot>
            </div>

            <div v-show="data.currActive === 'flow'">
                <div class="flow-predict_display_center">
                    <el-button type="primary" round icon="VideoPlay" @click="submitPredict(false)" v-if="!data.isPredicted || !data.predictFlow.flowInstId"
                               :disabled="data.btnLoading">开始预测</el-button>
                    <el-button type="primary" round icon="Refresh" @click="submitPredict(true)" v-if="data.isPredicted && data.predictFlow.flowInstId"
                               :disabled="data.btnLoading">刷新预测</el-button>
                </div>

                <div class="flow-predict_display">
                    <span style="margin-top: 5px">流程预测选项：</span>
                    <el-checkbox-group v-model="data.predictOptions">
                        <el-checkbox v-for="(item, index) in DIC_PROP.PREDICT_OPTIONS" :key="index" :label="item.value"
                                     :disabled="!!item.disabled">
                            {{ item.label }}
                        </el-checkbox>
                    </el-checkbox-group>
                </div>

                <keep-alive v-if="data.currTabComp && data.isPredicted">
                    <component ref="flow" v-if="data.currTabComp && data.isPredicted" :key="data.currTabComp" :is="data.currTabComp" :currJob="data.predictFlow"></component>
                </keep-alive>

                <div v-if="!data.isPredicted && data.predictFlow.defFlowId" class="flow-predict_display_center" style="font-size: 20px; margin-top: 10%; font-weight: 300">
                    全流程预测进行中：流转轨迹预测、节点参与者预测、连线条件预测、审批过程预测
                </div>

                <div v-if="!data.predictFlow.defFlowId" class="flow-predict_display_center" style="font-size: 20px; margin-top: 10%; font-weight: 300">
                    请点击《开始预测》按钮，进行全流程预测：流转轨迹预测、节点参与者预测、连线条件预测、审批过程预测
                </div>
            </div>

            <div id="predictClientHeight" style="min-width: 980px; overflow-y: auto">
                <comment ref="comment" v-if="data.isPredicted" v-show="data.currActive === 'comment'" :curr-job="data.predictFlow"></comment>
            </div>
        </el-drawer>

    </div>
</template>

<script setup lang="ts" name="JsonFlowPredict">
    import {useI18n} from "vue-i18n";
    import {utils} from "/@//flow/designer/utils/common";
    import * as defFlow from '/@/flow/designer/api/jsonflow'
    import {useMessage} from "/@/hooks/message";
    import * as orderVue from "/@/api/order/order-key-vue";

    // 引入组件
    const FlowPhoto = defineAsyncComponent(() => import('/@/views/jsonflow/flow-design/view.vue'));
    const Comment = defineAsyncComponent(() => import('/@/views/jsonflow/comment/timeline.vue'));

    const {t} = useI18n()
    const {proxy} = getCurrentInstance();
    const $message = useMessage();
    const $emit = defineEmits(['handleInitiateOrder']);

    const props = defineProps({
        currFlowForm: {
            type: Object,
            default: {},
        },
        proxy: {
            type: Object,
            default: null,
        },
    });

    const data = reactive({
        showInitiateOrder: false,
        predictFlow: {},
        currActive: 'form',
        isPredicted: false,
        btnLoading: false,
        predictOptions: [1, 2, 4, 8, 16, 0],
        currTabComp: null,
    })

    function initClientHeight() {
        nextTick(() => {
            let browserHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
            let initClientHeight = document.getElementById("predictClientHeight");
            if (initClientHeight) {
                initClientHeight.style.height = (browserHeight - initClientHeight.offsetTop) + "px";
            }
            let predictFormHeight = document.getElementById("predictFormHeight");
            if (predictFormHeight) {
                predictFormHeight.style.height = (browserHeight - predictFormHeight.offsetTop - 20) + "px";
            }
        })
    }

    function initPredictFlow(row) {
        data.currActive = 'form'
        data.predictFlow = {defFlowId: row.defFlowId, flowKey: row.flowKey}
        data.isPredicted = false
        data.btnLoading = false
        data.predictOptions = [1, 2, 4, 8, 16, 0]
    }

    async function handleTabClick(tab) {
        let currActive = data.currActive
        if (currActive === tab.paneName) return
        if (currActive === 'form' && tab.paneName !== 'form') {
            let formData
            try {
                formData = await props.proxy.$refs.form.getFormData();
            } catch (err: any) {
                // 表单校验报错
            }
            if (!formData) {
                data.currActive = currActive
                return
            }
        }
        if (tab.paneName === 'flow'){
            handLoader(true)
            // 定制化开发工单
            if (data.predictFlow.defFlowId) {
                data.isPredicted = true
            }
        }
        if (tab.paneName === 'comment'){
            handLoader(false)
            if (!data.predictFlow.flowInstId) {
                $message.warning('请先点击第二步，完成流程预测');
                // 不生效
                data.currActive = currActive
                return
            }
        }
        data.currActive = tab.paneName
    }

    async function submitPredict(isRefresh) {
        data.isPredicted = false
        data.btnLoading = true
        let flowInstId = data.predictFlow.flowInstId;
        // 流程预测
        let formData = await props.proxy.$refs.form.getFormData();
        formData.id = utils.getId()
        formData.flowInstId = formData.id
        // 定制化开发工单新增时
        if (!formData.flowKey) {
            formData.flowKey = data.predictFlow.flowKey
        }
        formData.predictOption = data.predictOptions.reduce((a, b) => a + b, 0);
        await defFlow.predictFlow(formData, null)
            .finally(() => {
                data.btnLoading = false
            });
        if (flowInstId) await delFlowInfo(flowInstId)
        data.predictFlow.flowInstId = formData.flowInstId
        data.isPredicted = true
    }

    function handleClosed() {
        $emit('handleInitiateOrder', false)
    }

    async function delFlowInfo(flowInstId?) {
        let row = {id: flowInstId, isPredicted: '1'}
        await defFlow.delFlowInfo(row)
    }

    function open(row, bool) {
        delFlowInfo()
        initPredictFlow(row)
        data.showInitiateOrder = bool
        if (!bool) return
        initClientHeight()
    }

    function handLoader(isLoad) {
        if (isLoad) {
            let path = orderVue.vueKey.FlowDesignView;
            data.currTabComp = `../../views${path}.vue`
        } else data.currTabComp = null
    }

    // 暴露变量
    defineExpose({
        open
    });
</script>

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

<style lang="scss" scoped>
  .flow-predict_display {
    margin-left: 20px;
    display: flex;
    width: 100%;
  }
  .flow-predict_display_center {
    display: flex;
    justify-content: center;
    width: 100%;
  }
</style>
