<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="100px" v-loading="loading" :disabled="operType === 'view'">
            <el-row :gutter="24">

                <el-col :span="12" class="mb20">
                    <el-form-item :label="t('flowVariable.flowInstId')" prop="flowInstId">
                        <el-input v-model="form.flowInstId" :placeholder="t('flowVariable.inputFlowInstIdTip')" clearable :disabled="operType !== 'add'"
                                   @change="cascadeChange('flowInstId', ['flowKey'])">
                        </el-input>
                    </el-form-item>
                </el-col>

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

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

                <el-col :span="12" class="mb20">
                    <el-form-item :label="t('flowVariable.varVal')" prop="varVal">
                        <el-input v-model="form.varVal" :placeholder="t('flowVariable.inputVarValTip')"/>
                    </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="FlowVariableDialog">

    import { useMessage } from "/@/hooks/message";
    import { getObj, addObj, putObj } from '/@/api/jsonflow/flow-variable'
    import { useI18n } from "vue-i18n"
    import { rule } from '/@/utils/validate';
    import {onCascadeChange} from "/@/flow/components/convert-name/convert";
    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 cascadeDic = reactive({});
    const onCascade = onCascadeChange(cascadeDic, {key: "flowInstId", cascades: ["flowKey"]});

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

    // 提交表单数据
    const form = reactive({
        flowInstId: '',
        flowKey: '',
        varKey: '',
        varVal: '',
    });

    // 定义校验规则
    const dataRules = ref({
        flowInstId: [{required: true, message: '流程实例ID不能为空', trigger: 'blur'}],
        flowKey: [{required: true, message: '流程名称不能为空', trigger: 'blur'}],
        varKey: [{required: true, message: '变量名不能为空', trigger: 'blur'}],
        varVal: [{required: true, message: '变量值不能为空', trigger: 'blur'}],
    })

    // 打开弹窗
    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();
        });

        // 获取FlowVariable信息
        if (id) {
            form.id = id
            getFlowVariableData(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 getFlowVariableData = (id: string) => {
        // 获取数据
        loading.value = true
        getObj(id).then((res: any) => {
            Object.assign(form, res.data)
            onCascade(form);
        }).finally(() => {
            loading.value = false
        })
    };

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