<template>
    <div class="layout-padding">
        <div class="layout-padding-auto layout-padding-view">
            <el-row v-show="showSearch">
                <el-form :model="state.queryForm" ref="queryRef" :inline="true" @keyup.enter="getDataList">
                    <el-form-item :label="$t('runFlow.initiatorId')" prop="initiatorId" v-if="!props.myFlow.initiatorId">
                        <el-tooltip content="请输入用户名称进行模糊搜索" placement="top">
                            <el-select v-model="state.queryForm.initiatorId" :placeholder="t('runFlow.inputInitiatorIdTip')" clearable filterable style="max-width: 180px"
                                       remote :remote-method="remoteMethod" :reserve-keyword="false">
                                <el-option v-for="(item, index) in dicData.initiatorId" :key="index" :label="item.name" :value="item.userId"></el-option>
                            </el-select>
                        </el-tooltip>
                    </el-form-item>
                    <el-form-item :label="$t('runFlow.code')" prop="code" >
                        <el-input :placeholder="t('runFlow.inputCodeTip')" v-model="state.queryForm.code" clearable
                                  style="max-width: 180px" />
                    </el-form-item>
                    <el-form-item :label="$t('runFlow.flowName')" prop="flowName">
                        <el-input :placeholder="t('runFlow.inputFlowNameTip')" v-model="state.queryForm.flowName" clearable
                                  style="max-width: 180px" />
                    </el-form-item>
                    <el-form-item :label="$t('runFlow.flowKey')" prop="flowKey" >
                        <el-input :placeholder="t('runFlow.inputFlowKeyTip')" v-model="state.queryForm.flowKey" clearable
                                  style="max-width: 180px" />
                    </el-form-item>
                    <el-form-item :label="$t('runFlow.status')" prop="status" >
                        <el-select v-model="state.queryForm.status" :placeholder="t('runFlow.inputStatusTip')" clearable style="max-width: 180px">
                            <el-option v-for="(item, index) in DIC_PROP.FLOW_STATUS" :key="index" :label="item.label" :value="item.value"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-button icon="search" type="primary" @click="getDataList">
                            {{ $t('common.queryBtn') }}
                        </el-button>
                        <el-button icon="Refresh" @click="resetQuery">{{ $t('common.resetBtn') }}</el-button>
                    </el-form-item>
                </el-form>
            </el-row>
            <el-row>
                <div class="mb8" style="width: 100%">
                    <right-toolbar v-model:showSearch="showSearch" 	:export="'jsonflow_runflow_export'"
                                   @exportExcel="exportExcel" class="ml10" style="float: right;margin-right: 20px"
                                   @queryTable="getDataList"></right-toolbar>
                </div>
            </el-row>
            <el-table :data="state.dataList" v-loading="state.loading" style="width: 100%"
                      @sort-change="sortChangeHandle">
                <el-table-column type="index" :label="t('runFlow.index')" width="40" />
                <el-table-column prop="id" :label="t('runFlow.id')"  show-overflow-tooltip/>
                <el-table-column prop="initiatorId" :label="t('runFlow.initiatorId')"  show-overflow-tooltip v-if="!props.myFlow.initiatorId">
                    <template #default="scope">
                        <convert-name :options="state.dicData.initiatorId" :value="scope.row.initiatorId"
                                      :valueKey="'userId'" :showKey="'name'"></convert-name>
                    </template>
                </el-table-column>
                <el-table-column prop="code" :label="t('runFlow.code')"  show-overflow-tooltip/>
                <el-table-column prop="flowName" :label="t('runFlow.flowName')"  show-overflow-tooltip/>
                <el-table-column prop="orderId" :label="t('flowApplication.formName')"  show-overflow-tooltip>
                    <template #default="scope">
                        <convert-name :options="state.dicData.orderId" :value="scope.row.orderId"
                                      :valueKey="'id'" :showKey="'formName'"></convert-name>
                    </template>
                </el-table-column>
                <el-table-column prop="groupName" :label="t('runFlow.groupName')"  show-overflow-tooltip/>
                <el-table-column prop="startTime" :label="t('runFlow.startTime')"  show-overflow-tooltip/>
                <el-table-column prop="endTime" :label="t('runFlow.endTime')"  show-overflow-tooltip/>
                <el-table-column prop="useTime" :label="t('runFlow.useTime')" show-overflow-tooltip/>
                <el-table-column prop="invalidReason" :label="t('runFlow.invalidReason')"  show-overflow-tooltip/>
<!--                <el-table-column prop="isIndependent" :label="t('runFlow.isIndependent')"  show-overflow-tooltip>
                    <template #default="scope">
                        <dict-tag :options="DIC_PROP.YES_OR_NO" :value="scope.row.isIndependent"></dict-tag>
                    </template>
                </el-table-column>-->
                <el-table-column prop="status" :label="t('runFlow.status')"  show-overflow-tooltip>
                    <template #default="scope">
                        <dict-tag :options="DIC_PROP.FLOW_STATUS" :value="scope.row.status"></dict-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="version" :label="t('runFlow.version')"  show-overflow-tooltip/>
                <el-table-column prop="remark" :label="t('runFlow.remark')" show-overflow-tooltip/>
<!--                <el-table-column prop="createUser" :label="t('runFlow.createUser')"  show-overflow-tooltip>
                    <template #default="scope">
                        <convert-name :options="state.dicData.createUser" :value="scope.row.createUser"
                                      :valueKey="'userId'" :showKey="'name'"></convert-name>
                    </template>
                </el-table-column>
                <el-table-column prop="createTime" :label="t('runFlow.createTime')"  show-overflow-tooltip/>-->
                <el-table-column :label="$t('common.action')" width="210">
                    <template #default="scope">
                        <el-dropdown style="vertical-align: middle; margin-right: 10px">
                            <span>
                              功能
                              <el-icon class="el-icon--right">
                                <arrow-down/>
                              </el-icon>
                            </span>
                            <template #dropdown>
                                <el-dropdown-menu>
                                    <el-dropdown-item @click="formDialogRef.openDialog('view', scope.row.id)">
                                        {{ $t('common.viewBtn') }}
                                    </el-dropdown-item>
                                    <el-dropdown-item divided @click="formDialogRef.openDialog('edit', scope.row.id)">
                                        {{ $t('common.editBtn') }}
                                    </el-dropdown-item>
                                    <el-dropdown-item divided @click="handlePrintTemplate(scope.row)"
                                                      v-if="scope.row.isIndependent ==='1'">
                                        {{ $t('jfI18n.printTemplate') }}
                                    </el-dropdown-item>
                                    <el-dropdown-item divided @click="methods.comment(scope.row)">
                                        查看审批过程
                                    </el-dropdown-item>
                                    <el-dropdown-item divided @click="methods.remind(scope.row)"
                                               v-if="scope.row.status ==='0'">
                                        催办流程
                                    </el-dropdown-item>
                                    <el-dropdown-item divided
                                               v-if="scope.row.status ==='2' || scope.row.status ==='3'"
                                               @click="scope.row.status ==='2' ? methods.handleInvalidFlow(scope.row) : methods.handleTerminateFlow(scope.row)">
                                        恢复流程
                                    </el-dropdown-item>
                                    <el-dropdown-item divided v-if="scope.row.status === '0'"
                                               @click.native="methods.handleEarlyComplete(scope.row)">
                                        提前结束流程
                                    </el-dropdown-item>
                                    <el-dropdown-item divided v-if="scope.row.status === '0'"
                                               @click.native="methods.handleTerminateFlow(scope.row)">
                                        终止流程
                                    </el-dropdown-item>
                                    <el-dropdown-item divided v-if="scope.row.status === '0'"
                                               @click.native="methods.handleInvalidFlow(scope.row)">
                                        作废流程
                                    </el-dropdown-item>
                                </el-dropdown-menu>
                            </template>
                        </el-dropdown>
                        <el-tooltip placement="top">
                            <template #content>
                                查看工单
                            </template>
                            <el-button text type="primary" icon="view" @click="methods.handleJob(scope.row)">
                            </el-button>
                        </el-tooltip>
                        <el-tooltip placement="top" content="对已发起的流程实例图，再次可视化单独编辑配置。只对当前流程实例生效">
                            <el-button text type="primary" icon="edit" @click="handleEditPhoto(true, scope.row)"
                                       v-auth="'jsonflow_runflow_edit'">
                                编辑实例图
                            </el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>
            <pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" v-bind="state.pagination" />
        </div>

        <!-- 编辑、新增  -->
        <form-dialog ref="formDialogRef" @refresh="getDataList(false)" />

        <el-drawer
                class="flow-overflow-drawer" direction="rtl"
                append-to-body size="100%"
                v-model="data.showDesignFlow"
                :with-header="false"
        >
            <flow-form-design v-if="data.showDesignFlow" :currFlowForm="data.currFlowForm" @handleDesignFlow="handleEditPhoto"></flow-form-design>
        </el-drawer>

        <!-- 查看审批过程 -->
        <el-dialog
                v-model="data.showComment" v-if="data.showComment"
                top="20px"
                width="90%"
                title="查看审批过程"
                append-to-body>
            <comment :curr-job="data.currJob"></comment>
        </el-dialog>

        <!-- 打印模板设计器 -->
        <el-drawer class="tinymce-print-drawer" append-to-body direction="rtl"
                   v-model="data.showTinymceEditor" size="100%"
                   :title="data.tinymceTitle" @close="getDataList">
            <tinymce-editor v-if="data.showTinymceEditor" :currFlowForm="data.currFlowForm"></tinymce-editor>
        </el-drawer>
    </div>
</template>

<script setup lang="ts" name="systemRunFlow">
    import { BasicTableProps, useTable } from "/@/hooks/table";
    import * as runFlow from '/@/api/jsonflow/run-flow'
    import { useMessage, useMessageBox } from "/@/hooks/message";

    import { useI18n } from "vue-i18n";
    import {onLoadDicUrl, onLoaded, remoteMethodByKey} from "/@/flow/components/convert-name/convert";
    import {parseWithFunctions} from "/@/flow";
    import * as runApplication from '/@/api/order/run-application'
    import * as flowApplication from '/@/api/order/flow-application'
    import {DIC_PROP} from "/@/flow/support/dict-prop";
    import {openFlowPreview} from "/@/flow/support/extend";

    // 引入组件
    const FormDialog = defineAsyncComponent(() => import('./form.vue'));
    const Comment = defineAsyncComponent(() => import('../comment/timeline.vue'));
    const FlowFormDesign = defineAsyncComponent(() => import('/@/flow/components/onebtn-design/design.vue'));
    const TinymceEditor = defineAsyncComponent(() => import('/@/flow/components/tinymce/TinymceEditor.vue'));

    const { t } = useI18n()
    const $message = useMessage();
    // 定义字典
    const dicData = reactive({});
    const onLoad = onLoadDicUrl();
    onMounted(() => {
        // onLoad(dicData);
    });
    // 定义变量内容
    const formDialogRef = ref()
    // 搜索变量
    const queryRef = ref()
    const showSearch = ref(true)

    const props = defineProps({
        myFlow: {
            type: Object,
            default: {},
        }
    });

    const state: BasicTableProps = reactive<BasicTableProps>({
        queryForm: !props.myFlow.initiatorId ? {} : {initiatorId: props.myFlow.initiatorId},
        pageList: runFlow.fetchList,
        onLoaded: onLoaded({key: "initiatorId"}, {key: "orderId"}, {key: "createUser"}),
        descs: ["create_time"]
    })

    //  table hook
    const {
        getDataList,
        currentChangeHandle,
        sizeChangeHandle,
        sortChangeHandle,
        downBlobFile
    } = useTable(state)

    // 清空搜索条件
    const resetQuery = () => {
        // 清空搜索条件
        queryRef.value?.resetFields()
        getDataList()
    }

    // 导出excel
    const exportExcel = () => {
        downBlobFile('/jsonflow/run-flow/export', state.queryForm, 'run-flow.xlsx')
    }

    const data = reactive({
        currJob: {},
        showComment: false,
        showDesignFlow: false,
        currFlowForm: {},
        showTinymceEditor: false,
        tinymceTitle: '',
    });

    function remoteMethod(query: string) {
        remoteMethodByKey(query, onLoad, dicData, 'userName', "initiatorId")
    }

    const getFormInfo = (row, callback) => {
        if (row.fromType === '0') {
            runApplication.getByFlowInstId(row.id)
                .then(resp => {
                    data.currFlowForm = resp.data
                    callback(resp)
                })
        } else {
            flowApplication.getObj(row.formId)
                .then(resp => {
                    data.currFlowForm = resp.data
                    data.currFlowForm.formId = resp.data.id
                    data.currFlowForm.flowInstId = row.id
                    callback(resp)
                })
        }
    }
    const handleEditPhoto = (bool, row?: any) => {
        if (bool === false) {
            data.showDesignFlow = bool
            getDataList()
            return
        }
        function callback(resp) {
            data.currFlowForm.formInfo = parseWithFunctions(resp.data.formInfo, true)
            data.currFlowForm.active = "formSetting";
            data.showDesignFlow = bool
        }

        getFormInfo(row, callback)
    }

    function handlePrintTemplate(row) {
        function callback(resp) {
            let row = data.currFlowForm
            data.currFlowForm = {id: row.formId, formType: row.type, formId: row.formId, formName: row.formName, path: row.path, isForm: true}
            data.currFlowForm.flowInstId = row.flowInstId
            data.currFlowForm.formInfo = row.formInfo
            data.tinymceTitle = "打印模板设计器（自定义《" + row.formName + "》打印格式）"
            data.showTinymceEditor = true
        }

        getFormInfo(row, callback)
    }

    const router = useRouter();
    const methods = {
        // 提前结束流程
        handleEarlyComplete(row) {
            useMessageBox().prompt("请输入提前结束流程理由")
                .then(({ value }) => {
                    row.flowInstId = row.id
                    row.jobBtn = DIC_PROP.JOB_BTNS[16].value
                    row.invalidReason = value
                    row.flowStatus = row.status
                    return runFlow.earlyComplete(row)
            }).then(() => {
                $message.success('操作成功')
                getDataList();
            })
        },
        // 终止/恢复流程
        handleTerminateFlow(row) {
            let text = row.status === '0' ? "终止" : "恢复";
            useMessageBox().prompt("请输入" + text + "理由")
                .then(({ value }) => {
                    row.flowInstId = row.id
                    row.jobBtn = DIC_PROP.JOB_BTNS[15].value
                    row.invalidReason = value
                    row.flowStatus = row.status
                    return runFlow.terminateFlow(row)
                }).then(() => {
                $message.success('操作成功')
                getDataList();
            })
        },
        // 作废/恢复流程
        handleInvalidFlow(row) {
            let text = row.status === '0' ? "作废" : "恢复";
            useMessageBox().prompt("请输入" + text + "理由")
                .then(({ value }) => {
                    row.flowInstId = row.id
                    row.jobBtn = DIC_PROP.JOB_BTNS[17].value
                    row.invalidReason = value
                    row.flowStatus = row.status
                    return runFlow.invalidFlow(row)
            }).then(() => {
                $message.success('操作成功')
                getDataList();
            })
        },
        handleJob(row) {
            openFlowPreview(router, {flowInstId: row.id})
        },
        comment(row) {
            data.currJob = row
            data.currJob.flowInstId = row.id
            data.showComment = true
        },
        remind(row) {
            runFlow.remind(row).then(() => {
                $message.success('催办成功')
            })
        }
    }

</script>

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