<template>
    <div>
        <el-form ref="dataFormRef" :model="form" :rules="dataRules" label-width="120px" v-loading="loading" :disabled="operType === 'view'">
            <span style="margin-left: 30px">什么是被驳回人？当被驳回人为空时，则默认会驳回到该节点下的全部审批人。当被驳回人不为空时，则会驳回到该节点下指定的审批人员（{{userRoleIdText}}）</span>
            <el-row :gutter="24">
                <el-divider> 任意驳回选择 </el-divider>

                <el-col :span="12" class="mb20">
                    <el-form-item :label="t('runReject.flowInstId')" prop="flowInstId">
                        <el-input v-model="form.flowInstId" :placeholder="t('runReject.inputFlowInstIdTip')" disabled/>
                    </el-form-item>
                </el-col>

                <el-col :span="12" class="mb20">
                    <el-form-item :label="t('runReject.defFlowId')" prop="defFlowId">
                        <el-select v-model="form.defFlowId" :placeholder="t('runReject.inputDefFlowIdTip')" clearable filterable disabled>
                            <el-option v-for="(item, index) in cascadeDic.defFlowId" :key="index" :label="item.flowName" :value="item.defFlowId"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>

                <el-col :span="12" class="mb20">
                    <el-form-item :label="t('runReject.toRunNodeId')" prop="toRunNodeId">
                        <el-tooltip placement="top" content="若不选择具体的【指定被驳回人】，则默认会驳回到该节点下的全部审批人">
                            <el-select v-model="form.toRunNodeId" :placeholder="t('runReject.inputToFlowNodeIdTip')" clearable filterable
                                       @change="cascadeChange('toRunNodeId', ['handleUserId'])">
                                <el-option v-for="(item, index) in cascadeDic.toRunNodeId" :key="index" :label="item.nodeName" :value="item.id"></el-option>
                            </el-select>
                        </el-tooltip>
                    </el-form-item>
                </el-col>

                <el-col :span="12" class="mb20" v-if="form.runRejectVO.nodeType !== DIC_PROP.NODE_TYPE[4].value">
                    <el-form-item :label="t('runReject.handleUserId')" prop="handleUserId">
                        <el-tooltip placement="top">
                                <template #content>{{validateNull(cascadeDic.handleUserId) ? userIdText : userIdText2}}</template>
                            <el-select v-model="form.handleUserId" :placeholder="t('runReject.inputHandleUserIdTip')" clearable filterable
                                       @change="handleUserIdChange">
                                <el-option v-for="(item, index) in cascadeDic.handleUserId" :key="index" :label="item.name" :value="item.userId"></el-option>
                            </el-select>
                        </el-tooltip>
                    </el-form-item>
                </el-col>

            </el-row>
        </el-form>
        <footer class="el-dialog__footer">
            <span class="dialog-footer">
              <el-button type="primary" @click="handleUpdate" :loading="loading">{{ $t('common.confirmButtonText') }}</el-button>
            </span>
        </footer>
    </div>
</template>

<script setup lang="ts" name="RunRejectForm">
    import { useI18n } from "vue-i18n"
    import {onCascadeChange, onLoadDicUrl} from "/@/flow/components/convert-name/convert";
    import {validateNull} from "/@/utils/validate";
    import {useMessage} from "/@/hooks/message";
    import {DIC_PROP} from "/@/flow/support/dict-prop";

    const { t } = useI18n();
    const $message = useMessage();
    const $emit = defineEmits(['onRejectJob']);
    // 定义变量内容
    const dataFormRef = ref();
    const loading = ref(false);
    const operType = ref(false);

    // 定义字典
    const dicData = reactive({});
    const cascadeDic = reactive({});
    // const onLoad = onLoadDicUrl({key: "userId"});
    const onCascade = onCascadeChange(cascadeDic, {key: "flowInstId", cascades: ["defFlowId"]}, {prefix: "runReject", key: "flowInstId", cascades: ["toRunNodeId"]},
        {key: "toRunNodeId", cascades: ["handleUserId"]});
    onMounted(() => {
        // onLoad(dicData);
    });
    function cascadeChange(key, cascades){
        onCascade(form, {key: key, cascades: cascades});
        handleToFlowNodeId(form[key])
    }

    // 提交表单数据
    const form = reactive({
        defFlowId: '',
        flowInstId: '',
        toRunNodeId: '',
        handleUserId: '',
        runRejectVO: {},
    });

    // 定义校验规则
    const dataRules = ref({
        defFlowId: [{required: true, message: '流程名称不能为空', trigger: 'blur'}],
        flowInstId: [{required: true, message: '流程实例ID不能为空', trigger: 'blur'}],
        toRunNodeId: [{required: true, message: '达到节点名称不能为空', trigger: 'blur'}],
    })

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

    const userIdText = '注：当前被驳回节点下可候选被驳回人为空不可驳回，请使用【任意跳转】'
    const userIdText2 = '注：当被驳回人为空时，则默认会驳回到当前节点显示的全部审批人'
    const userRoleIdText = '注：被驳回节点下的任务需审批过存在审批人才可驳回，否则请使用【任意跳转】'

    function handleToFlowNodeId(val) {
        if (!val) return
        const runNode = cascadeDic.toRunNodeId.find(f => f.id === val)
        form.runRejectVO.toRunNodeId = runNode.id
        form.runRejectVO.toFlowNodeId = runNode.flowNodeId
        form.runRejectVO.nodeType = runNode.nodeType
    }

    function handleUserIdChange(val) {
        form.runRejectVO.handleUserId = val
    }

    function initJobData() {
        Object.assign(form, props.currJob)
        onCascade(form)
    }

    async function handleUpdate() {
        const valid = await dataFormRef.value.validate().catch(() => {});
        if (!valid) return false;

        if (validateNull(cascadeDic.handleUserId) && form.runRejectVO.nodeType !== DIC_PROP.NODE_TYPE[4].value) {
            $message.warning(userIdText)
            return
        }

        props.currJob.runRejectVO = form.runRejectVO
        form.runRejectVO.remark = props.currJob.comment

        loading.value = true
        try {
            $emit('onRejectJob', props.currJob)
            setTimeout(() => { // 异步异常
                loading.value = false
            }, 3000)
        } catch (e) {
            loading.value = false
        }
    }

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

    onMounted(() => {
        initJobData();
    });

</script>

<style lang="scss" scoped>
  .el-dialog__footer {
    text-align: center;

    .dialog-footer {
      text-align: center;
    }
  }
</style>
