<template>
    <el-dialog :title="title" v-model="visible" width="80%"
               :close-on-click-modal="false" draggable>
        <el-form ref="dataFormRef" :model="form" :rules="dataRules" label-width="130px" v-loading="loading" :disabled="operType === 'view'">
            <el-row :gutter="24">
                <el-col :span="12" class="mb20">
                    <el-form-item :label="t('defFlow.flowName')" prop="flowName">
                        <el-input v-model="form.flowName" :placeholder="t('defFlow.inputFlowNameTip')"/>
                    </el-form-item>
                </el-col>

                <el-col :span="12" class="mb20">
                    <el-form-item :label="t('defFlow.flowKey')" prop="flowKey">
                        <el-input v-model="form.flowKey" :disabled="operType === 'edit'" :placeholder="t('defFlow.inputFlowKeyTip')"/>
                    </el-form-item>
                </el-col>

                <el-col :span="12" class="mb20">
                    <el-form-item :label="t('defFlow.groupName')" prop="groupName">
                        <el-select v-model="form.groupName" :placeholder="t('defFlow.inputGroupNameTip')" style="width: 81%!important;"
                                   clearable filterable allowCreate defaultFirstOption>
                            <el-option v-for="(item, index) in dicData.groupName" :key="index" :label="item.groupName" :value="item.groupName"></el-option>
                        </el-select>

                        <el-button
                                type="primary" size="small" round style="margin-left: 10px"
                                @click="handleAddGroupName"
                        >新增分组
                        </el-button>
                    </el-form-item>
                </el-col>

                <el-col :span="12" class="mb20">
                    <el-form-item :label="t('defFlow.status')" prop="status">
                        <el-radio-group v-model="form.status">
                            <el-radio v-for="(item, index) in DIC_PROP.TEMP_STATUS" :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('defFlow.remark')" prop="remark">
                        <el-input v-model="form.remark" type="textarea" :placeholder="t('defFlow.inputRemarkTip')"/>
                    </el-form-item>
                </el-col>

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

                <el-col :span="12" class="mb20">
                    <el-form-item :label="t('defFlow.isIndependent')" prop="isIndependent">
                        <el-radio-group v-model="form.isIndependent">
                            <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="DefFlowDialog">

    import {useMessage, useMessageBox} from "/@/hooks/message";
    import {getObj, addObj, putObj, getByFlowName, tempStore} from '/@/api/jsonflow/def-flow'
    import { useI18n } from "vue-i18n"
    import { rule } from '/@/utils/validate';
    import {onLoadDicUrl, onUpdateDicData} from "/@/flow/components/convert-name/convert";
    import {deepClone} from "/@/utils/other";
    import {setPropsNullValue} from "/@/flow/support/common";
    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 onLoad = onLoadDicUrl({prefix: "defFlow", key: "groupName"});
    const onUpdate = onUpdateDicData({key: "groupName"});
    onMounted(() => {
        onLoad(dicData);
    });

    // 提交表单数据
    const form = reactive({
        flowName: '',
        flowKey: '',
        groupName: '',
        status: '-1',
        isIndependent: '0',
        remark: '',
        sort: 1,
    });
    // 初始表单数据
    const initForm = reactive(deepClone(form));

    // 校验是否已存在
    let validateIsExist = (rule, value, callback) => {
        // 修改判断相同id
        getByFlowName(value).then(response => {
            const result = response.data
            if (result !== null) {
                if (result.id !== form.id)
                    callback(new Error('流程名称已经存在'))
                else callback()
            } else {
                callback()
            }
        })
    }

    // 定义校验规则
    const dataRules = ref({
        flowName: [{required: true, message: '流程名称不能为空', trigger: 'blur'}/*, {validator: validateIsExist, trigger: 'blur'}*/],
        flowKey: [{required: true, message: '流程KEY不能为空', trigger: 'blur'}],
        groupName: [{required: true, message: '分组名称不能为空', trigger: 'blur'}],
        status: [{required: true, message: '状态不能为空', trigger: 'blur'}],
        sort: [{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');
        }

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

        // 获取DefFlow信息
        if (id) {
            form.id = id
            getDefFlowData(id)
        }
    };

    function handleAddGroupName() {
        useMessageBox().prompt("请输入新的分组名称")
            .then(({ value }) => {
                form.groupName = value
                onUpdate(dicData, form);
            })
    }

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

        try {
            loading.value = true;
            await tempStore(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 getDefFlowData = (id: string) => {
        // 获取数据
        loading.value = true
        getObj(id).then((res: any) => {
            Object.assign(form, res.data)
        }).finally(() => {
            loading.value = false
        })
    };

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