<template>
    <el-dialog :title="title" v-model="visible" width="60%" draggable>
        <el-form ref="dataFormRef" :model="form" :rules="dataRules" label-width="150px" v-loading="loading" :disabled="operType === 'view'">
            <el-row :gutter="24">

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

                <el-col :span="12" class="mb20">
                    <el-form-item :label="t('runJob.defFlowId')" prop="defFlowId">
                        <el-select v-model="form.defFlowId" :placeholder="t('runJob.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('runJob.runNodeId')" prop="runNodeId">
                        <el-select v-model="form.runNodeId" :placeholder="t('runJob.inputRunNodeIdTip')" clearable filterable disabled>
                            <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-col>

                <el-col :span="12" class="mb20">
                    <el-form-item :label="t('runJob.jobName')" prop="jobName">
                        <el-input v-model="form.jobName" :placeholder="t('runJob.inputJobNameTip')"/>
                    </el-form-item>
                </el-col>

                <el-col :span="12" class="mb20">
                    <el-form-item :label="t('runJob.jobType')" prop="jobType">
                        <el-select v-model="form.jobType" :placeholder="t('runJob.inputJobTypeTip')" clearable filterable
                                   @change="handleRoleType">
                            <el-option v-for="(item, index) in DIC_PROP.JOB_USER_NONE_TYPE" :key="index" :label="item.label" :value="item.value"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>

                <el-col :span="12" class="mb20">
                    <el-form-item :label="t('runJob.roleId')" prop="roleId">
                        <el-tooltip content="请输入名称进行模糊搜索" placement="top">
                            <el-select v-model="form.roleId" :placeholder="t('runJob.inputRoleIdTip')" clearable filterable
                                       remote :remote-method="(query) => remoteMethodAll(query, form.jobType)" :reserve-keyword="false">
                                <el-option v-for="(item, index) in dicData.users" :key="index" :label="item.name" :value="item.userId"
                                           v-if="form.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="form.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="form.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="form.jobType === DIC_PROP.JOB_USER_TYPE[3].value"></el-option>
                            </el-select>
                        </el-tooltip>
                    </el-form-item>
                </el-col>

                <el-col :span="12" class="mb20">
                    <el-form-item :label="t('runJob.userId')" prop="userId">
                        <el-tooltip content="请输入用户名称进行模糊搜索" placement="top">
                            <el-select v-model="form.userId" :placeholder="t('runJob.inputUserIdTip')" clearable filterable
                                       remote :remote-method="remoteMethod" :reserve-keyword="false">
                                <el-option v-for="(item, index) in dicData.userId" :key="index" :label="item.name" :value="item.userId"></el-option>
                            </el-select>
                        </el-tooltip>
                    </el-form-item>
                </el-col>

                <el-col :span="12" class="mb20">
                    <el-form-item :label="t('runJob.startTime')" prop="startTime">
                        <el-date-picker disabled type="datetime" :placeholder="t('runJob.inputStartTimeTip')" v-model="form.startTime" :value-format="dateTimeStr"></el-date-picker>
                    </el-form-item>
                </el-col>

                <el-col :span="12" class="mb20">
                    <el-form-item :label="t('runJob.endTime')" prop="endTime">
                        <el-date-picker disabled type="datetime" :placeholder="t('runJob.inputEndTimeTip')" v-model="form.endTime" :value-format="dateTimeStr"></el-date-picker>
                    </el-form-item>
                </el-col>

                <el-col :span="12" class="mb20">
                    <el-form-item :label="t('runJob.userKey')" prop="userKey">
                        <el-select v-model="form.userKey" :placeholder="t('runJob.inputUserKeyTip')" clearable filterable>
                            <el-option v-for="(item, index) in dicData.userKey" :key="index" :label="item.userKey" :value="item.userKey"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>

<!--                <el-col :span="12" class="mb20">
                    <el-form-item :label="t('runJob.distFlowNodeId')" prop="distFlowNodeId">
                        <el-select v-model="form.distFlowNodeId" :placeholder="t('runJob.inputDistFlowNodeIdTip')" clearable filterable>
                            <el-option v-for="(item, index) in cascadeDic.runNodeId" :key="index" :label="item.nodeName" :value="item.flowNodeId"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>-->

                <el-col :span="12" class="mb20">
                    <el-form-item :label="t('runJob.status')" prop="status">
                        <el-select disabled v-model="form.status" :placeholder="t('runJob.inputStatusTip')" clearable filterable>
                            <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-col>

                <el-col :span="12" class="mb20">
                    <el-form-item :label="t('runJob.timeout')" prop="timeout">
                        <el-input-number :min="1" :max="1000" v-model="form.timeout" :placeholder="t('runJob.inputTimeoutTip')"></el-input-number>
                    </el-form-item>
                </el-col>

                <el-col :span="12" class="mb20">
                    <el-form-item :label="t('runJob.suspension')" prop="suspension">
                        <el-radio-group v-model="form.suspension">
                            <el-radio v-for="(item, index) in DIC_PROP.YES_OR_NO" :key="index" :label="item.value">
                                {{ getLabelByLanguage(item) }}
                            </el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-col>

                <el-col :span="12" class="mb20">
                    <el-form-item :label="t('runJob.suspensionReason')" prop="suspensionReason">
                        <el-input v-model="form.suspensionReason" :placeholder="t('runJob.inputSuspensionReasonTip')"/>
                    </el-form-item>
                </el-col>

                <el-col :span="12" class="mb20">
                    <el-form-item :label="t('runJob.isSkipRejected')" prop="isSkipRejected">
                        <el-radio-group v-model="form.isSkipRejected">
                            <el-radio v-for="(item, index) in DIC_PROP.YES_OR_NO" :key="index" :label="item.value">
                                {{ getLabelByLanguage(item) }}
                            </el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-col>

<!--                <el-col :span="12" class="mb20">
                    <el-form-item :label="t('runJob.isNowRun')" prop="isNowRun">
                        <el-radio-group disabled v-model="form.isNowRun">
                            <el-radio v-for="(item, index) in DIC_PROP.YES_OR_NO" :key="index" :label="item.value">
                                {{ getLabelByLanguage(item) }}
                            </el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-col>-->

                <el-col :span="12" class="mb20">
                    <el-form-item :label="t('runJob.sort')" prop="sort">
                        <el-input-number :min="1" :max="1000" v-model="form.sort" :placeholder="t('runJob.inputSortTip')"></el-input-number>
                    </el-form-item>
                </el-col>

            </el-row>
        </el-form>
        <template #footer v-if="operType !== 'view'">
        <span class="dialog-footer">
          <el-button @click="visible = false">{{ $t('common.cancelButtonText') }}</el-button>
          <el-button type="primary" @click="onSubmit" :disabled="loading">{{ $t('common.confirmButtonText') }}</el-button>
        </span>
        </template>
    </el-dialog>
</template>

<script setup lang="ts" name="RunJobDialog">

    import { useMessage } from "/@/hooks/message";
    import { getObj, addObj, putObj } from '/@/api/jsonflow/run-job'
    import { useI18n } from "vue-i18n"
    import {
        onCascadeChange,
        onFormLoadedUrl,
        onLoadDicUrl,
        remoteMethodAllByKey, remoteMethodByKey
    } from "/@/flow/components/convert-name/convert";
    import {handleChangeJobType} from "/@/flow";
    import {PROP_CONST} from "/@/flow/support/prop-const";

    const emit = defineEmits(['refresh']);
    const { t } = useI18n();
    // 定义变量内容
    const dataFormRef = ref();
    const visible = ref(false);
    const loading = ref(false);
    const operType = ref(false);
    const title = ref('');

    // 提交表单数据
    const form = reactive({
        defFlowId: '',
        flowNodeId: '',
        nodeJobId: '',
        jobType: '',
        roleId: '',
        userId: '',
        startTime: '',
        endTime: '',
        userKey: '',
        distFlowNodeId: '',
        timeout: 0,
        status: '',
        suspension: '',
        suspensionReason: '',
        isSkipRejected: '0',
        createUser: '',
        flowKey: '',
        flowInstId: '',
        runNodeId: '',
        isNowRun: '0',
        sort: 1,
    });

    // 定义校验规则
    const dataRules = ref({
        defFlowId: [{required: true, message: '流程名称不能为空', trigger: 'blur'}],
        flowNodeId: [{required: true, message: '节点名称不能为空', trigger: 'blur'}],
        nodeJobId: [{required: true, message: '任务名称不能为空', trigger: 'blur'}],
        jobType: [{required: true, message: '参与者类型不能为空', trigger: 'blur'}],
        timeout: [{required: true, message: '任务时限不能为空', trigger: 'blur'}],
        isSkipRejected: [{required: true, message: '被驳回是否可跳过不能为空', trigger: 'blur'}],
    })

    // 定义查询字典
    const dicData = reactive({});
    const cascadeDic = reactive({});
    const onLoad = onLoadDicUrl({key: "userKey"});
    const onFormLoaded = onFormLoadedUrl({key: "userId"}, ...PROP_CONST.LOAD_USER_ROLE);
    const onCascade = onCascadeChange(cascadeDic, {key: "flowInstId", cascades: ["defFlowId"]}, {key: "flowInstId", cascades: ["runNodeId"]});
    onMounted(() => {
        onLoad(dicData);
    });
    function cascadeChange(key, cascades){
        onCascade(form, {key: key, cascades: cascades});
    }

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

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

    function handleRoleType() {
        handleChangeJobType(dicData, form)
    }

    // 打开弹窗
    const openDialog = (type: string, id: string) => {
        visible.value = true
        operType.value = type;
        form.id = ''

        if (type === 'add') {
            title.value = t('common.addBtn');
        } else if (type === 'edit') {
            title.value = t('common.editBtn');
        } else if (type === 'view') {
            title.value = t('common.viewBtn');
        }

        // 重置表单数据
        nextTick(() => {
            dataFormRef.value?.resetFields();
        });

        // 获取RunJob信息
        if (id) {
            form.id = id
            getRunJobData(id)
        }
    };

    // 提交
    const onSubmit = async () => {
        const valid = await dataFormRef.value.validate().catch(() => {});
        if (!valid) return false;

        try {
            loading.value = true;
            form.id ? await putObj(form) : await addObj(form);
            useMessage().success(t(form.id ? 'common.editSuccessText' : 'common.addSuccessText'));
            visible.value = false;
            emit('refresh');
        } catch (err: any) {
            useMessage().error(err.msg);
        } finally {
            loading.value = false;
        }
    };

    // 初始化表单数据
    const getRunJobData = (id: string) => {
        // 获取数据
        loading.value = true
        getObj(id).then((res: any) => {
            Object.assign(form, res.data)
            onFormLoaded(dicData, form);
            onCascade(form);
        }).finally(() => {
            loading.value = false
        })
    };

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