<template>
    <el-dialog :title="title" v-model="visible" width="60%"
               :close-on-click-modal="false" draggable>
        <el-form ref="dataFormRef" :model="form" :rules="dataRules" label-width="110px" v-loading="loading" :disabled="operType === 'view'">
            <el-row :gutter="24">
                <el-col :span="12" class="mb20">
                    <el-form-item :label="t('distPerson.code')" prop="code">
                        <el-select v-model="form.code" :placeholder="t('distPerson.inputCodeTip')" clearable filterable
                                   @change="cascadeChange('code', ['flowInstId'])">
                            <el-option v-for="(item, index) in dicData.code" :key="index" :label="item.code" :value="item.code"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>

                <el-col :span="12" class="mb20">
                    <el-form-item :label="t('distPerson.flowKey')" prop="flowInstId">
                        <el-select v-model="form.flowInstId" :placeholder="t('runJob.inputFlowKeyTip')" clearable filterable
                                   @change="cascadeChange('flowInstId', ['runNodeId'])">
                            <el-option v-for="(item, index) in cascadeDic.flowInstId" :key="index" :label="item.flowName" :value="item.id"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>

                <el-col :span="12" class="mb20" v-if="operType !== 'view'">
                    <el-form-item :label="t('distPerson.runNodeId')" prop="runNodeId">
                        <el-select v-model="form.runNodeId" :placeholder="t('distPerson.inputRunNodeIdTip')" clearable filterable
                                   @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-col>

                <el-col :span="12" class="mb20" v-if="operType !== 'view'">
                    <el-form-item :label="t('distPerson.runJobId')" prop="runJobId">
                        <el-select v-model="form.runJobId" :placeholder="t('distPerson.inputRunJobIdTip')" clearable filterable @change="runJobIdChange">
                            <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-col>

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

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

                <el-col :span="12" class="mb20">
                    <el-form-item :label="t('distPerson.roleId')" prop="roleId">
                        <el-tooltip content="请输入名称进行模糊搜索" placement="top">
                            <el-select v-model="form.roleId" :placeholder="t('distPerson.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('distPerson.jobName')" prop="jobName">
                        <el-input v-model="form.jobName" :placeholder="t('distPerson.inputJobNameTip')"/>
                    </el-form-item>
                </el-col>

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

<!--                <el-col :span="12" class="mb20">
                    <el-form-item :label="t('distPerson.isNowRun')" prop="isNowRun" disabled>
                        <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-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="DistPersonDialog">

    import { useMessage } from "/@/hooks/message";
    import { getObj, addObj, putObj } from '/@/api/jsonflow/dist-person'
    import { useI18n } from "vue-i18n"
    import { rule } from '/@/utils/validate';
    import {onCascadeChange, onFormLoadedUrl, onLoadDicUrl, remoteMethodAllByKey} from "/@/flow/components/convert-name/convert";
    import {setPropsDataValue, setPropsNull} from "/@/flow/support/common";
    import {handleChangeJobType} from "/@/flow";
    import {DIC_PROP} from "/@/flow/support/dict-prop";
    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 dicData = reactive({});
    const cascadeDic = reactive({});
    const onLoad = onLoadDicUrl({key: "code"});
    const onFormLoaded = onFormLoadedUrl(...PROP_CONST.LOAD_USER_ROLE);
    const onCascade = onCascadeChange(cascadeDic, {key: "code", cascades: ["flowInstId"]}, {key: "flowInstId", cascades: ["runNodeId"]}, {key: "runNodeId", cascades: ["runJobId"]});
    onMounted(() => {
        // onLoad(dicData);
    });

    function cascadeChange(key, cascades){
        onCascade(form, {key: key, cascades: cascades});
    }

    function runJobIdChange(newVal) {
        let fields = ['flowKey', 'flowNodeId', 'nodeJobId', 'jobType', 'userKey', 'valType', 'isNowRun'];
        if (!newVal) {
            setPropsNull(form, ...fields)
            return
        }
        const runJob = cascadeDic.runJobId.find(f => f.id === newVal)
        setPropsDataValue(form, runJob, fields)
        if (form.valType !== DIC_PROP.VAL_TYPE[1].value) {
            form.runJobId = null
            useMessage().info("当前节点任务为非分配类型的任务，不允许单独分配参与者");
        }
    }
    // 提交表单数据
    const form = reactive({
        code: '',
        runNodeId: '',
        runJobId: '',
        roleId: '',
        jobType: '',
        userKey: '',
        flowInstId: '',
        flowKey: '',
    });

    // 定义校验规则
    const dataRules = ref({
        code: [{required: true, message: '工单编号不能为空', trigger: 'blur'}],
        flowInstId: [{required: true, message: '流程名称不能为空', trigger: 'blur'}],
        // runNodeId: [{required: true, message: '节点名称不能为空', trigger: 'blur'}],
        // runJobId: [{required: true, message: '任务名称不能为空', trigger: 'blur'}],
        jobType: [{required: true, message: '参与者类型不能为空', trigger: 'blur'}],
    })

    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();
        });

        // 获取DistPerson信息
        if (id) {
            form.id = id
            getDistPersonData(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 getDistPersonData = (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>
