<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="120px" v-loading="loading" :disabled="operType === 'view'">
            <el-row :gutter="24">
                <el-col :span="12" class="mb20">
                    <el-form-item :label="t('flowrule.type')" prop="type">
                        <el-select v-model="form.type" :placeholder="t('flowrule.inputTypeTip')" clearable filterable>
                            <el-option v-for="(item, index) in DIC_PROP.PARAM_RULE_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('flowrule.valType')" prop="type">
                        <el-select v-model="form.valType" :placeholder="t('flowrule.inputValTypeTip')" clearable filterable>
                            <el-option v-for="(item, index) in DIC_PROP.VAL_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('flowrule.defFlowId')" prop="defFlowId">
                        <el-select v-model="form.defFlowId" :placeholder="t('flowrule.inputDefFlowIdTip')" clearable filterable
                                   @change="cascadeChange('defFlowId', ['flowNodeId', 'flowNodeRelId'])">
                            <el-option v-for="(item, index) in dicData.defFlowId" :key="index" :label="item.flowName" :value="item.id"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12" class="mb20">
                    <el-form-item :label="t('flowrule.flowNodeId')" prop="flowNodeId">
                        <el-select v-model="form.flowNodeId" :placeholder="t('flowrule.inputFlowNodeIdTip')" clearable filterable>
                            <el-option v-for="(item, index) in cascadeDic.flowNodeId" :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('flowrule.flowNodeRelId')" prop="flowNodeRelId">
                        <el-select v-model="form.flowNodeRelId" :placeholder="t('flowrule.inputFlowNodeRelIdTip')" clearable filterable>
                            <el-option v-for="(item, index) in cascadeDic.flowNodeRelId" :key="index" :label="item.label" :value="item.id"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>

                <el-col :span="12" class="mb20">
                    <el-form-item :label="t('flowrule.groupId')" prop="groupId">
                        <el-input v-model="form.groupId" :placeholder="t('flowrule.inputGroupIdTip')"/>
                    </el-form-item>
                </el-col>
                <el-col :span="12" class="mb20">
                    <el-form-item :label="t('flowrule.groupsType')" prop="groupsType">
                        <el-switch
                                v-model="form.groupsType"
                                active-value="0"
                                inactive-value="1"
                                inactive-text="或"
                                active-text="且">
                        </el-switch>
                    </el-form-item>
                </el-col>
                <el-col :span="12" class="mb20">
                    <el-form-item :label="t('flowrule.groupType')" prop="groupType">
                        <el-switch
                                v-model="form.groupType"
                                active-value="0"
                                inactive-value="1"
                                inactive-text="或"
                                active-text="且">
                        </el-switch>
                    </el-form-item>
                </el-col>
                <el-col :span="12" class="mb20">
                    <el-form-item :label="t('flowrule.varKeyVal')" prop="varKeyVal">
                        <el-input v-model="form.varKeyVal" :placeholder="t('flowrule.inputVarKeyValTip')"/>
                    </el-form-item>
                </el-col>

                <el-col :span="12" class="mb20">
                    <el-form-item :label="t('flowrule.operator')" prop="operator">
                        <el-select v-model="form.operator" :placeholder="t('flowrule.inputOperatorTip')" clearable filterable>
                            <el-option v-for="(item, index) in DIC_PROP.OPERATOR" :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('flowrule.varVal')" prop="varVal">
                        <el-input v-model="form.varVal" :placeholder="t('flowrule.inputVarValTip')"/>
                    </el-form-item>
                </el-col>

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

                <el-col :span="12" class="mb20">
                    <el-form-item :label="t('flowrule.paramFrom')" prop="paramFrom">
                        <el-select v-model="form.paramFrom" :placeholder="t('flowrule.inputParamFromTip')" clearable filterable>
                            <el-option v-for="(item, index) in DIC_PROP.PARAM_FROM" :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('flowrule.paramValType')" prop="paramValType">
                        <el-select v-model="form.paramValType" :placeholder="t('flowrule.inputParamValTypeTip')" clearable filterable>
                            <el-option v-for="(item, index) in DIC_PROP.PARAM_VAL_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('flowrule.targetProp')" prop="targetProp">
                        <el-input v-model="form.targetProp" :placeholder="t('flowrule.inputTargetPropTip')"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12" class="mb20">
                    <el-form-item :label="t('flowrule.paramType')" prop="paramType">
                        <el-select v-model="form.paramType" :placeholder="t('flowrule.inputParamTypeTip')" clearable filterable>
                            <el-option v-for="(item, index) in DIC_PROP.PARAM_TYPES" :key="index" :label="item.label" :value="item.value"></el-option>
                        </el-select>
                    </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="FlowRuleDialog">
    import { useMessage } from "/@/hooks/message";
    import { getObj, addObj, putObj } from '/@/api/jsonflow/flow-rule'
    import { useI18n } from "vue-i18n"
    import {onCascadeChange, onLoadDicUrl} from "/@/flow/components/convert-name/convert";
    import {handleChangeJobType} from "/@/flow";

    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({
        id: '',
        flowKey: '',
        defFlowId: '',
        flowNodeId: '',
        type: '',
        valType: '',
        groupId: '',
        groupsType: '0',
        groupType: '0',
        varKeyVal: '',
        operator: '',
        varVal: '',
        createUser: '',
        createTime: '',
        updateUser: '',
        updateTime: '',
    });

    // 定义校验规则
    const dataRules = ref({
        defFlowId: [{required: true, message: '流程名称不能为空', trigger: 'blur'}],
        type: [{required: true, message: '数据类型不能为空', trigger: 'blur'}],
        valType: [{required: true, message: '条件模式不能为空', trigger: 'blur'}],
        groupId: [{required: true, message: '同组条件ID不能为空', trigger: 'blur'}],
        groupsType: [{required: true, message: '条件组关系不能为空', trigger: 'blur'}],
        groupType: [{required: true, message: '组内条件关系不能为空', trigger: 'blur'}],
        varKeyVal: [{required: true, message: '表单字段不能为空', trigger: 'blur'}],
        operator: [{required: true, message: '运算符不能为空', trigger: 'blur'}],
        varVal: [{required: true, message: '校验值不能为空', trigger: 'blur'}],
    })

    // 定义查询字典
    const dicData = reactive({});
    const cascadeDic = reactive({});
    const onLoad = onLoadDicUrl({key: "defFlowId"}, {key: "users"}, {key: "roles"}, {key: "posts"}, {key: "depts"});
    const onCascade = onCascadeChange(cascadeDic, {key: "defFlowId", cascades: ["flowNodeId", "flowNodeRelId"]});
    onMounted(() => {
        onLoad(dicData);
    });

    function cascadeChange(key, cascades){
        onCascade(form, {key: key, cascades: cascades});
        if (key === 'defFlowId') {
            let find = dicData.defFlowId.find(f => f.id === form.defFlowId);
            if (find) form.flowKey = find.flowKey
            else form.flowKey = null
        }
    }

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

    // 打开弹窗
    const openDialog = async (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(async () => {
            dataFormRef.value.resetFields()
            // 获取FlowRule信息
            if (id) {
                form.id = id
                await getFlowRuleData(id)
                await onCascade(form);
            }
        })
    };

    // 提交
    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);
        } finally {
            loading.value = false;
        }
    }

    // 初始化表单数据
    const getFlowRuleData = async (id: string) => {
        // 获取数据
        loading.value = true
        let res = await getObj(id);
        Object.assign(form, res.data)
        loading.value = false
    };

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