<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('runJob.jobType')" prop="jobType">
                        <el-select v-model="state.queryForm.jobType" :placeholder="t('runJob.inputJobTypeTip')" clearable filterable style="max-width: 180px"
                                   @change="handleRoleType">
                            <el-option v-for="(item, index) in DIC_PROP.JOB_USER_TYPE" :key="index" :label="item.label" :value="item.value"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item :label="t('runJob.roleId')" prop="roleId">
                        <el-tooltip content="请输入名称进行模糊搜索" placement="top">
                            <el-select v-model="state.queryForm.roleId" :placeholder="t('runJob.inputRoleIdTip')" clearable filterable style="max-width: 180px"
                                       remote :remote-method="(query) => remoteMethodAll(query, state.queryForm.jobType)" :reserve-keyword="false">
                                <el-option v-for="(item, index) in dicData.users" :key="index" :label="item.name" :value="item.userId"
                                           v-if="state.queryForm.jobType === DIC_PROP.JOB_USER_TYPE[0].value"></el-option>
                                <el-option v-for="(item, index) in dicData.roles" :key="index" :label="item.roleName" :value="item.roleId"
                                           v-if="state.queryForm.jobType === DIC_PROP.JOB_USER_TYPE[1].value"></el-option>
                                <el-option v-for="(item, index) in dicData.posts" :key="index" :label="item.postName" :value="item.postId"
                                           v-if="state.queryForm.jobType === DIC_PROP.JOB_USER_TYPE[2].value"></el-option>
                                <el-option v-for="(item, index) in dicData.depts" :key="index" :label="item.name" :value="item.deptId"
                                           v-if="state.queryForm.jobType === DIC_PROP.JOB_USER_TYPE[3].value"></el-option>
                            </el-select>
                        </el-tooltip>
                    </el-form-item>

                    <el-form-item :label="$t('runJob.flowInstId')" prop="flowInstId" >
                        <el-input :placeholder="t('runJob.inputFlowInstIdTip')" v-model="state.queryForm.flowInstId"
                                  @change="cascadeChange('flowInstId', ['runNodeId'])"
                                  style="max-width: 180px" />
                    </el-form-item>
                    <el-form-item :label="$t('runJob.runNodeId')" prop="runNodeId" >
                        <el-select v-model="state.queryForm.runNodeId" :placeholder="t('runJob.inputRunNodeIdTip')" clearable filterable style="max-width: 180px"
                                   @change="cascadeChange('runNodeId', ['runJobId'])">
                            <el-option v-for="(item, index) in cascadeDic.runNodeId" :key="index" :label="item.nodeName" :value="item.id"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item :label="$t('runJob.id')" prop="id" >
                        <el-select v-model="state.queryForm.id" :placeholder="t('runJob.inputIdTip')" clearable filterable style="max-width: 180px">
                            <el-option v-for="(item, index) in cascadeDic.runJobId" :key="index" :label="item.jobName" :value="item.id"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item :label="$t('runJob.status')" prop="status" >
                        <el-select v-model="state.queryForm.status" :placeholder="t('runJob.inputStatusTip')" clearable filterable style="max-width: 180px">
                            <el-option v-for="(item, index) in DIC_PROP.NODE_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%">
                    <el-tooltip placement="top">
                        <template #content>
                            {{ $t('common.addBtn') }}
                        </template>
                        <el-button icon="Plus" type="primary" class="ml10" @click="formDialogRef.openDialog('add')"
                                   v-auth="'jsonflow_runjob_add'">
                        </el-button>
                    </el-tooltip>
                    <el-tooltip placement="top">
                        <template #content>
                            {{ $t('common.delBtn') }}
                        </template>
                        <el-button plain :disabled="multiple" icon="Delete" type="primary" class="ml10"
                                   v-auth="'jsonflow_runjob_del'" @click="handleDelete(selectObjs)">
                        </el-button>
                    </el-tooltip>
                    <right-toolbar v-model:showSearch="showSearch" 	:export="'jsonflow_runjob_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%"
                      :row-class-name="tableRowClassName"
                      @sort-change="sortChangeHandle">
                <el-table-column type="index" :label="t('runJob.index')" width="40" />
                <el-table-column prop="flowInstId" :label="t('runJob.flowInstId')"  show-overflow-tooltip/>
                <el-table-column prop="defFlowId" :label="t('runJob.defFlowId')"  show-overflow-tooltip>
                    <template #default="scope">
                        <convert-name :options="state.dicData.flowInstId" :value="scope.row.defFlowId"
                                      :valueKey="'defFlowId'" :showKey="'flowName'"></convert-name>
                    </template>
                </el-table-column>
                <el-table-column prop="runNodeId" :label="t('runJob.runNodeId')"  show-overflow-tooltip>
                    <template #default="scope">
                        <convert-name :options="state.dicData.runNodeId" :value="scope.row.runNodeId"
                                      :valueKey="'id'" :showKey="'nodeName'"></convert-name>
                    </template>
                </el-table-column>
                <el-table-column prop="jobName" :label="t('runJob.jobName')"  show-overflow-tooltip/>
                <el-table-column prop="jobType" :label="t('runJob.jobType')"  show-overflow-tooltip>
                    <template #default="scope">
                        <dict-tag :options="DIC_PROP.JOB_USER_TYPE" :value="scope.row.jobType"></dict-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="roleId" :label="t('runJob.roleId')">
                    <template #default="scope">
                        <convert-role-name :options="{users: state.dicData.users, roles: state.dicData.roles, posts: state.dicData.posts, depts: state.dicData.depts }"
                                           :value="scope.row"></convert-role-name>
                    </template>
                </el-table-column>
                <el-table-column prop="userId" :label="t('runJob.userId')"  show-overflow-tooltip>
                    <template #default="scope">
                        <convert-name :options="state.dicData.userId" :value="scope.row.userId"
                                      :valueKey="'userId'" :showKey="'name'"></convert-name>
                    </template>
                </el-table-column>
                <el-table-column prop="startTime" :label="t('runJob.startTime')"  show-overflow-tooltip/>
                <el-table-column prop="endTime" :label="t('runJob.endTime')"  show-overflow-tooltip/>
                <el-table-column prop="userKey" :label="t('runJob.userKey')"  show-overflow-tooltip>
                </el-table-column>
<!--                <el-table-column prop="distFlowNodeId" :label="t('runJob.distFlowNodeId')"  show-overflow-tooltip>
                    <template #default="scope">
                        <convert-name :options="state.dicData.runNodeId" :value="scope.row.distFlowNodeId"
                                      :valueKey="'flowNodeId'" :showKey="'nodeName'"></convert-name>
                    </template>
                </el-table-column>-->
                <el-table-column prop="timeout" :label="t('runJob.timeout')"  show-overflow-tooltip/>
                <el-table-column prop="status" :label="t('runJob.status')"  show-overflow-tooltip>
                    <template #default="scope">
                        <dict-tag :options="DIC_PROP.NODE_STATUS" :value="scope.row.status"></dict-tag>
                    </template>
                </el-table-column>
<!--                <el-table-column prop="suspension" :label="t('runJob.suspension')"  show-overflow-tooltip>
                    <template #default="scope">
                        <dict-tag :options="DIC_PROP.YES_OR_NO" :value="scope.row.suspension"></dict-tag>
                    </template>
                </el-table-column>-->
                <el-table-column prop="suspensionReason" :label="t('runJob.suspensionReason')"  show-overflow-tooltip/>
<!--                <el-table-column prop="isSkipRejected" :label="t('runJob.isSkipRejected')"  show-overflow-tooltip>
                    <template #default="scope">
                        <dict-tag :options="DIC_PROP.YES_OR_NO" :value="scope.row.isSkipRejected"></dict-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="isNowRun" :label="t('runJob.isNowRun')"  show-overflow-tooltip>
                    <template #default="scope">
                        <dict-tag :options="DIC_PROP.YES_OR_NO" :value="scope.row.isNowRun"></dict-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="createUser" :label="t('runJob.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('runJob.createTime')"  show-overflow-tooltip/>-->
                <el-table-column prop="flowStatus" :label="t('runJob.flowStatus')" show-overflow-tooltip>
                    <template #default="scope">
                        <dict-tag :options="DIC_PROP.FLOW_STATUS" :value="scope.row.flowStatus"></dict-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="sort" :label="t('runJob.sort')"  show-overflow-tooltip/>
                <el-table-column :label="$t('common.action')" width="180">
                    <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.native="methods.handleComment(scope.row)">查看审批过程
                                    </el-dropdown-item>
                                    <el-dropdown-item
                                            divided
                                            @click.native="methods.handleFlowPic(scope.row)">查看流程图
                                    </el-dropdown-item>
                                    <template v-if="DIC_PROP.FLOW_STATUS[2].value === scope.row.flowStatus">
                                        <template v-if="scope.row.status === '0' || scope.row.status === '9'">
                                            <el-dropdown-item
                                                    v-if="scope.row.jobType !== DIC_PROP.JOB_USER_TYPE[0].value"
                                                    divided
                                                    @click.native="methods.handleSignForJob(scope.row, '1')"
                                            >签收任务
                                            </el-dropdown-item>
                                            <el-dropdown-item
                                                    v-if="scope.row.jobType === DIC_PROP.JOB_USER_TYPE[0].value && scope.row.roleId"
                                                    divided
                                                    @click.native="methods.handleSignForJob(scope.row, '0')"
                                            >反签收任务
                                            </el-dropdown-item>
                                            <el-dropdown-item
                                                    v-if="scope.row.suspension === '1'"
                                                    divided
                                                    @click.native="methods.handleSuspension(scope.row,'0')"
                                            >激活任务
                                            </el-dropdown-item>
                                            <el-dropdown-item
                                                    v-if="scope.row.suspension !== '1'"
                                                    divided
                                                    @click.native="methods.handleSuspension(scope.row,'1')"
                                            >挂起任务
                                            </el-dropdown-item>
                                            <el-dropdown-item
                                                    v-if="scope.row.suspension !== '1' && scope.row.roleId"
                                                    divided
                                                    @click.native="methods.handleJobRoleUserId(scope.row,'0')">
                                                转办任务
                                            </el-dropdown-item>
                                            <el-dropdown-item
                                                    v-if="scope.row.suspension !== '1' && !scope.row.roleId"
                                                    divided
                                                    @click.native="methods.handleJobRoleUserId(scope.row,'1')">
                                                指派人员
                                            </el-dropdown-item>
                                        </template>
                                        <el-dropdown-item divided
                                                          @click.native="methods.handleEarlyComplete(scope.row)">
                                            提前结束流程
                                        </el-dropdown-item>
                                        <el-dropdown-item divided
                                                          @click.native="methods.handleTerminateFlow(scope.row)">
                                            终止流程
                                        </el-dropdown-item>
                                        <el-dropdown-item divided
                                                          @click.native="methods.handleInvalidFlow(scope.row)">
                                            作废流程
                                        </el-dropdown-item>
                                    </template>
                                </el-dropdown-menu>
                            </template>
                        </el-dropdown>

                        <el-tooltip placement="top">
                            <template #content>
                                {{ $t('common.editBtn') }}
                            </template>
                            <el-button icon="edit-pen" text type="primary" @click="formDialogRef.openDialog('edit', scope.row.id)">
                            </el-button>
                        </el-tooltip>
                        <template v-if="!scope.row.roleId || (scope.row.status !== '0' && scope.row.status !== '9')">
                            <el-tooltip placement="top">
                                <template #content>
                                    查看工单
                                </template>
                                <el-button text type="primary" icon="view" @click="methods.handleHiJob(scope.row)">
                                </el-button>
                            </el-tooltip>
                        </template>
                        <template v-if="scope.row.roleId && DIC_PROP.FLOW_STATUS[2].value === scope.row.flowStatus">
                            <el-button icon="Stamp" text type="primary"
                                       v-if="scope.row.suspension !== '1' && (scope.row.status === '0' || scope.row.status === '9') && scope.row.belongType !== '2'"
                                       @click="methods.handleJob(scope.row)">审批
                            </el-button>

                            <el-button icon="Stamp" text type="primary"
                                       v-if="scope.row.suspension !== '1' && scope.row.belongType === '2' && scope.row.isRead === '0'"
                                       @click="methods.handleJob(scope.row, '0', '1')">查看
                            </el-button>
                        </template>

<!--                        <el-tooltip placement="top">
                            <template #content>
                                {{ $t('common.viewBtn') }}
                            </template>
                            <el-button text type="primary" icon="view" @click="formDialogRef.openDialog('view', scope.row.id)">
                            </el-button>
                        </el-tooltip>-->
<!--                        <el-tooltip placement="top">
                            <template #content>
                                {{ $t('common.delBtn') }}
                            </template>
                            <el-button icon="delete" text type="primary" @click="handleDelete([scope.row.id])">
                            </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-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="flow-overflow-drawer" direction="rtl"
                append-to-body size="90%"
                v-model="data.showFlowPic"
        >
            <flow-photo v-if="data.showFlowPic" :curr-job="data.currJob"></flow-photo>
        </el-drawer>

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

    </div>
</template>

<script setup lang="ts" name="systemRunJob">
    import { BasicTableProps, useTable } from "/@/hooks/table";
    import { fetchList, delObjs } from "/@/api/jsonflow/run-job";
    import { useMessage, useMessageBox } from "/@/hooks/message";

    import { useI18n } from "vue-i18n";
    import {
        onCascadeChange,
        onLoadDicUrl,
        onLoaded,
        remoteMethodAllByKey,
    } from "/@/flow/components/convert-name/convert";
    import {handleFlowPreview, openFlowPreview} from "/@/flow/support/extend";
    import {useFlowJob} from "/@/flow/stores/flowJob";
    import {PROP_CONST} from "/@/flow/support/prop-const";
    import {handleChangeJobType} from "/@/flow";
    import {
        handleEarlyComplete, handleInvalidFlow,
        handleSignForJob,
        handleSuspension,
        handleTerminateFlow, onJobNextUserRole,
        onSignForJob, onTurnRunJob
    } from "/@/flow/components/handle-job";

    const $message = useMessage();
    const {proxy} = getCurrentInstance();
    // 引入组件
    const FormDialog = defineAsyncComponent(() => import('./form.vue'));
    const UserRolePicker = defineAsyncComponent(() => import('../../../flow/components/user-role/picker.vue'));
    const Comment = defineAsyncComponent(() => import('../comment/timeline.vue'));
    const FlowPhoto = defineAsyncComponent(() => import('../flow-design/view.vue'));

    const flowJob = useFlowJob()
    const {t} = useI18n()
    const $router = useRouter();
    // 定义查询字典
    const dicData = reactive({});
    const cascadeDic = reactive({});
    const onLoad = onLoadDicUrl();
    const onCascade = onCascadeChange(cascadeDic, {key: "flowInstId", cascades: ["runNodeId"]}, {key: "runNodeId", cascades: ["runJobId"]});
    onMounted(() => {
        // onLoad(dicData);
    });
    function cascadeChange(key, cascades){
        onCascade(state.queryForm, {key: key, cascades: cascades});
    }

    // 定义变量内容
    const formDialogRef = ref()
    // 搜索变量
    const queryRef = ref()
    const showSearch = ref(true)
    // 多选变量
    const selectObjs = ref([]) as any
    const multiple = ref(true)

    const data = reactive({
        // 0、转办 1、指派
        nodeUserType: undefined,
        currJob: undefined,
        queryForm: {},
        showComment: false,
        showFlowPic: false,
        activeName: '-1'
    });

    const state: BasicTableProps = reactive<BasicTableProps>({
        queryForm: {},
        pageList: fetchList,
        onLoaded: onLoaded({key: "userId"}, {key: "flowInstId"}, {key: "runNodeId"}, ...PROP_CONST.LOAD_USER_ROLE),
        descs: ["receive_time"]
    })

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

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

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

    const tableRowClassName = ({row, rowIndex}) => {
        if (row.isRead !== '1') {
            return 'row-custom-warning'
        }
        return ''
    }

    // 删除操作
    const handleDelete = async (ids: string[]) => {
        try {
            await useMessageBox().confirm(t('common.delConfirmText'));
        } catch {
            return;
        }

        try {
            await delObjs(ids);
            getDataList();
            useMessage().success(t('common.delSuccessText'));
        } catch (err: any) {
            useMessage().error(err.msg);
        }
    };

    function remoteMethodAll(query: string, jobType) {
        remoteMethodAllByKey(onLoad, dicData, query, jobType)
    }

    function handleRoleType() {
        handleChangeJobType(dicData, state.queryForm)
    }

    const methods = {
        handleHiJob(row) {
            openFlowPreview($router, row)
        },
        handleJob(row, isView?, isRead?) {
            handleFlowPreview($router, row, isView, isRead, $message, flowJob, getDataList)
        },
        handleJobRoleUserId(row, type) {
            data.currJob = row
            methods.openJobRoleUserId(type)
        },
        // 指定任务参与者
        onJobNextUserRole(items) {
            onJobNextUserRole($message, items, getDataList, data)
        },
        handleComment(row) {
            data.currJob = row
            data.showComment = true
        },
        handleFlowPic(row) {
            data.currJob = row
            data.showFlowPic = true
        },
        // 签收反签收任务
        handleSignForJob(row, type) {
            handleSignForJob(methods, $message, getDataList, row, type)
        },
        // 反签收任务
        onSignForJob(obj) {
            onSignForJob($message, flowJob, getDataList, obj)
        },
        // 挂起激活任务
        handleSuspension(row, suspension) {
            handleSuspension($message, getDataList, row, suspension)
        },
        // 选择参与者
        openJobRoleUserId(type) {
            data.nodeUserType = type
            proxy.$refs.userRolePicker.onOpen();
        },
        onSelectItems(items) {
            if (data.nodeUserType === '0') {
                methods.onTurnRunJob(items[0])
            } else {
                methods.onJobNextUserRole(items)
            }
        },
        // 提前结束流程
        handleEarlyComplete(row) {
            handleEarlyComplete($message, flowJob, getDataList, row)
        },
        // 终止流程
        handleTerminateFlow(row) {
            handleTerminateFlow($message, flowJob, getDataList, row)
        },
        // 作废流程
        handleInvalidFlow(row) {
            handleInvalidFlow($message, flowJob, getDataList, row)
        },
        // 转办任务
        onTurnRunJob(role) {
            onTurnRunJob($message, flowJob, getDataList, data, role)
        }
    }
</script>

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

  .el-table .row-custom-warning {
    --el-table-tr-bg-color: var(--el-color-warning-light-9);
  }
</style>
