<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('formoption.type')" prop="type">
                        <el-select v-model="form.type" :placeholder="t('formoption.inputTypeTip')" clearable filterable
                                   @change="typeChange" :disabled="true">
                            <el-option v-for="(item, index) in DIC_PROP.FORM_DATA_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('formoption.formType')" prop="formType">
                        <el-select v-model="form.formType" :placeholder="t('formoption.inputFormTypeTip')" clearable filterable
                                   @change="formTypeChange" :disabled="disabledFields.formType">
                            <el-option v-for="(item, index) in DIC_PROP.FORM_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('formoption.formId')" prop="formId">
                        <el-select v-model="form.formId" :placeholder="t('formoption.inputFormIdTip')" clearable filterable
                                   @change="formIdChange">
                            <el-option v-for="(item, index) in dicData.formIdByType" :key="index"
                                       :label="item.formName" :value="item.id"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>

                <el-col :span="12" class="mb20" v-if="!hiddenFields.defFlowId">
                    <el-form-item :label="t('formoption.defFlowId')" prop="defFlowId">
                        <el-select v-model="form.defFlowId" :placeholder="t('formoption.inputDefFlowIdTip')" clearable filterable
                                   @change="cascadeChange('defFlowId', ['flowNodeId'])">
                            <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" v-if="!hiddenFields.flowNodeId">
                    <el-form-item :label="t('formoption.flowNodeId')" prop="flowNodeId">
                        <el-select v-model="form.flowNodeId" :placeholder="t('formoption.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" v-if="!hiddenFields.propId">
                    <el-form-item :label="t('formoption.propId')" prop="propId">
                        <el-input v-model="form.propId" :placeholder="t('formoption.inputPropIdTip')"/>
                    </el-form-item>
                </el-col>
                <el-col :span="12" class="mb20" v-if="!hiddenFields.label">
                    <el-form-item :label="t('formoption.label')" prop="label">
                        <el-input v-model="form.label" :placeholder="t('formoption.inputLabelTip')"/>
                    </el-form-item>
                </el-col>
                <el-col :span="12" class="mb20" v-if="!hiddenFields.prop">
                    <el-form-item :label="t('formoption.prop')" prop="prop">
                        <el-input v-model="form.prop" :placeholder="t('formoption.inputPropTip')"/>
                    </el-form-item>
                </el-col>
                <el-col :span="12" class="mb20" v-if="!hiddenFields.subForm">
                    <el-form-item :label="t('formoption.subForm')" prop="subForm">
                        <el-input v-model="form.subForm" :placeholder="t('formoption.inputSubFormTip')"/>
                    </el-form-item>
                </el-col>
                <el-col :span="12" class="mb20" v-if="!hiddenFields.propType">
                    <el-form-item :label="t('formoption.propType')" prop="propType">
                        <el-input v-model="form.propType" :placeholder="t('formoption.inputPropTypeTip')"/>
                    </el-form-item>
                </el-col>
                <el-col :span="12" class="mb20" v-if="!hiddenFields.permType">
                    <el-form-item :label="t('formoption.permType')" prop="type">
                        <el-radio-group v-model="form.permType">
                            <el-radio v-for="(item, index) in DIC_PROP.FORM_PERM_TYPE" :key="index" :label="item.value">
                                {{ item.label }}
                            </el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-col>
                <el-col :span="12" class="mb20" v-if="!hiddenFields.printInfo">
                    <el-form-item :label="t('formoption.printInfo')" prop="printInfo">
                        <el-input v-model="form.printInfo" :placeholder="t('formoption.inputPrintInfoTip')"/>
                    </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="FormOptionDialog">
    import { useMessage } from "/@/hooks/message";
    import { getObj, putObj } from '/@/api/jsonflow/form-option'
    import { useI18n } from "vue-i18n"
    import {setPropsValue} from "/@/flow/support/common";
    import {onCascadeChange, onLoadDicUrl} from "/@/flow/components/convert-name/convert";
    import {DIC_PROP} from "/@/flow/support/dict-prop";

    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: '',
        propId: '',
        label: '',
        prop: '',
        subForm: '',
        propType: '',
        permType: '',
        formType: '',
        formId: '',
        formName: '',
        path: '',
        printInfo: '',
        type: '',
    });

    // 定义校验规则
    const dataRules = ref({
        formType: [{required: true, message: '表单来源不能为空', trigger: 'blur'}],
        formId: [{required: true, message: '表单名称不能为空', trigger: 'blur'}],
        type: [{required: true, message: '数据类型不能为空', trigger: 'blur'}],
    })

    // 定义查询字典
    const dicData = reactive({});
    const cascadeDic = reactive({});
    const onLoad = onLoadDicUrl({key: "defFlowId"}, {key: "formId"});
    const onCascade = onCascadeChange(cascadeDic, {key: "defFlowId", cascades: ["flowNodeId"]});
    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
        }
    }

    // 打开弹窗
    const openDialog = async (type: string, id: string, dataType: 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()
            // 获取FormOption信息
            if (id) {
                form.id = id
                await getFormOptionData(id)
                await onCascade(form);
            }
            if (type === 'add') form.type = dataType
            typeChange(form.type);
        })
    };

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

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

    // 定义字段显隐
    const hiddenFields = reactive({
        defFlowId: true,
        flowNodeId: true,
        label: true,
        prop: true,
        propId: true,
        subForm: true,
        propType: true,
        permType: true,
        printInfo: true,
    });

    // 定义字段是否可编辑
    const disabledFields = reactive({
        formType: false,
    });

    const formTypeChange = (value) => {
        if (value) dicData.formIdByType = dicData.formId.filter(f => f.type === value)
        else dicData.formIdByType = []
    }

    const formIdChange = (value) => {
        if (!value) return
        let find = dicData.formIdByType.find(f => f.id === value);
        form.formName = find.formName
        form.path = find.path
    }

    const typeChange = (value) => {
        disabledFields.formType = false
        setPropsValue(hiddenFields, true, 'defFlowId', 'flowNodeId', 'propId', 'label', 'prop', 'subForm', 'propType', 'permType', 'printInfo')
        if (value === DIC_PROP.FORM_DATA_TYPE[0].value) {
            disabledFields.formType = true
            setPropsValue(hiddenFields, false, 'propId', 'label', 'prop', 'subForm', 'propType')
            form.formType = DIC_PROP.FORM_TYPE[1].value
        } else if (value === DIC_PROP.FORM_DATA_TYPE[1].value) {
            setPropsValue(hiddenFields, false, 'defFlowId', 'flowNodeId', 'propId', 'label', 'prop', 'subForm', 'propType', 'permType')
        } else {
            hiddenFields.printInfo = true
        }
        formTypeChange(form.formType)
    }

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