<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('runFlow.initiatorId')" prop="initiatorId">
                        <el-tooltip content="请输入用户名称进行模糊搜索" placement="top">
                            <el-select v-model="form.initiatorId" :placeholder="t('runFlow.inputInitiatorIdTip')" clearable filterable
                                       remote :remote-method="remoteMethod" :reserve-keyword="false">
                                <el-option v-for="(item, index) in dicData.initiatorId" :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('runFlow.flowName')" prop="flowName">
                        <el-input v-model="form.flowName" :placeholder="t('runFlow.inputFlowNameTip')"/>
                    </el-form-item>
                </el-col>

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

                <el-col :span="12" class="mb20">
                    <el-form-item :label="t('runFlow.startTime')" prop="startTime">
                        <el-date-picker type="datetime" :placeholder="t('runFlow.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('runFlow.endTime')" prop="endTime">
                        <el-date-picker type="datetime" :placeholder="t('runFlow.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('runFlow.invalidReason')" prop="invalidReason">
                        <el-input v-model="form.invalidReason" :placeholder="t('runFlow.inputInvalidReasonTip')" disabled/>
                    </el-form-item>
                </el-col>

                <el-col :span="12" class="mb20">
                    <el-form-item :label="t('runFlow.status')" prop="status">
                        <el-select v-model="form.status" :placeholder="t('runFlow.inputStatusTip')" clearable filterable disabled>
                            <el-option v-for="(item, index) in DIC_PROP.FLOW_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('runFlow.remark')" prop="remark">
                        <el-input v-model="form.remark" type="textarea" :placeholder="t('runFlow.inputRemarkTip')"/>
                    </el-form-item>
                </el-col>

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

                <el-col :span="12" class="mb20">
                    <el-form-item :label="t('runFlow.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="RunFlowDialog">

    import { useMessage } from "/@/hooks/message";
    import { getObj, addObj, putObj } from '/@/api/jsonflow/run-flow'
    import { useI18n } from "vue-i18n"
    import { rule } from '/@/utils/validate';
    import {onFormLoadedUrl, onLoadDicUrl, remoteMethodByKey} 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 dicData = reactive({});
    const onLoad = onLoadDicUrl();
    const onFormLoaded = onFormLoadedUrl({key: "initiatorId"});
    onMounted(() => {
        // onLoad(dicData);
    });
    // 提交表单数据
    const form = reactive({
        initiatorId: '',
        flowName: '',
        groupName: '',
        startTime: '',
        endTime: '',
        invalidReason: '',
        status: '',
        version: 0,
        createUser: '',
        createTime: '',
    });

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

        // 获取RunFlow信息
        if (id) {
            form.id = id
            getRunFlowData(id)
        }
    };

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

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

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