<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('flowApplication.flowKey')" prop="flowKey">
                        <el-input v-model="form.flowKey" :placeholder="t('flowApplication.inputFlowKeyTip')" clearable/>
                    </el-form-item>
                </el-col>

                <el-col :span="12" class="mb20">
                    <el-form-item :label="t('flowApplication.formName')" prop="formName">
                        <el-input v-model="form.formName" :placeholder="t('flowApplication.inputFormNameTip')" maxlength="20" show-word-limit clearable/>
                    </el-form-item>
                </el-col>

                <el-col :span="12" class="mb20">
                    <el-form-item :label="t('flowApplication.icon')" prop="icon">
                        <IconSelector :placeholder="$t('flowApplication.inputIconTip')" v-model="form.icon" />
                    </el-form-item>
                </el-col>

                <el-col :span="12" class="mb20">
                    <el-form-item :label="t('flowApplication.groupName')" prop="groupName">
                        <el-select v-model="form.groupName" :placeholder="t('flowApplication.inputGroupNameTip')"  style="width: 80%!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('flowApplication.type')" prop="type">
                        <el-select v-model="form.type" :placeholder="t('flowApplication.inputTypeTip')" clearable filterable>
                            <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" v-if="form.type === DIC_PROP.FORM_TYPE[1].value">
                    <el-form-item :label="t('tabsOption.path')" prop="path">
                        <el-input v-model="form.path" :placeholder="t('tabsOption.inputPathTip')" clearable>
                        </el-input>
                    </el-form-item>
                </el-col>

                <el-col :span="12" class="mb20">
                    <el-form-item :label="t('flowApplication.tableName')" prop="tableName">
                        <el-tooltip content="若自行调用接口保存表单数据，则此处需为空" placement="top">
                            <el-select v-model="form.tableName" :placeholder="t('flowApplication.inputTableNameTip')" clearable filterable>
                                <el-option v-for="(item, index) in dicData.tableName" :key="index" :label="item.tableName" :value="item.tableName"></el-option>
                            </el-select>
                        </el-tooltip>
                    </el-form-item>
                </el-col>

                <el-col :span="12" class="mb20">
                    <el-form-item :label="t('flowApplication.permission')" prop="permission">
                        <el-tooltip content="请输入角色名称进行模糊搜索，默认所有人都可以发起该流程" placement="top">
                            <el-select v-model="form.permission" :placeholder="t('flowApplication.inputPermissionTip')" clearable filterable multiple
                                       remote :remote-method="remoteMethod" :reserve-keyword="false">
                                <el-option v-for="(item, index) in dicData.permission" :key="index" :label="item.roleName" :value="item.roleId"></el-option>
                            </el-select>
                        </el-tooltip>
                    </el-form-item>
                </el-col>

                <el-col :span="12" class="mb20">
                    <el-form-item :label="t('flowApplication.subTableName')" prop="subTableName">
                        <el-tooltip content="当存在多个关联子表时，多个子表名称名顺序与《关联子表属性》顺序一一对应" placement="top">
                            <el-select v-model="form.subTableName" :placeholder="t('flowApplication.inputSubTableNameTip')"
                                       @change="changeSubTableName" clearable filterable multiple>
                                <el-option v-for="(item, index) in dicData.tableName" :key="index" :label="item.tableName" :value="item.tableName"></el-option>
                            </el-select>
                        </el-tooltip>
                    </el-form-item>
                </el-col>

                <el-col :span="12" class="mb20" v-if="!validateNull(form.subTableName)">
                    <el-tooltip content="当关联子表名称存在时，可配置子表中关联【主表主键】的列名，如main_id" placement="top">
                        <el-form-item :label="t('flowApplication.subMainField')" prop="subMainField">
                            <el-input v-model="form.subMainField" :placeholder="t('flowApplication.inputSubMainFieldTip')"></el-input>
                        </el-form-item>
                    </el-tooltip>
                </el-col>

                <el-col :span="12" class="mb20" v-if="!validateNull(form.subTableName)">
                    <el-tooltip content="当关联子表名称存在时，可配置主表中关联【子表集合数据】的属性名，如subFormList。多个子表属性名以逗号分割，与《关联子表名称》顺序一一对应" placement="top">
                        <el-form-item :label="t('flowApplication.mainSubProp')" prop="mainSubProp">
                            <el-input v-model="form.mainSubProp" :placeholder="t('flowApplication.inputMainSubPropTip')"></el-input>
                        </el-form-item>
                    </el-tooltip>
                </el-col>

                <el-col :span="12" class="mb20">
                    <el-form-item :label="t('flowApplication.remark')" prop="remark">
                        <el-input v-model="form.remark" type="textarea" :placeholder="t('flowApplication.inputRemarkTip')"/>
                    </el-form-item>
                </el-col>

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

                <el-col :span="12" class="mb20">
                    <el-form-item :label="t('tabsOption.isActive')" prop="isActive">
                        <el-radio-group v-model="form.isActive">
                            <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-col :span="12" class="mb20">
                    <el-form-item :label="t('tabsOption.isAutoAudit')" prop="isAutoAudit">
                        <el-radio-group v-model="form.isAutoAudit">
                            <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-col :span="12" class="mb20">
                    <el-form-item :label="t('flowApplication.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-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="FlowApplicationDialog">

    import {useMessage, useMessageBox} from "/@/hooks/message";
    import { getObj, addObj, putObj } from '/@/api/order/flow-application'
    import { useI18n } from "vue-i18n"
    import {rule, validateNull} from '/@/utils/validate';
    import {
        onFormLoadedUrl,
        onLoadDicUrl,
        onUpdateDicData,
        remoteMethodByKey
    } from "/@/flow/components/convert-name/convert";
    import {notifyLeft} from "/@/flow";
    import {setPropsNull} from "../../support/common";
    import {DIC_PROP} from "../../support/dict-prop";
    import {validateFormTypeSave, vueKey} from "/@/api/order/order-key-vue";
    const emit = defineEmits(['refresh']);

    const { t } = useI18n();
    // 引入组件
    const IconSelector = defineAsyncComponent(() => import('/@/components/IconSelector/index.vue'));
    // 定义变量内容
    const dataFormRef = ref();
    const visible = ref(false);
    const loading = ref(false);
    const operType = ref(false);
    const title = ref('');
    // 定义字典
    const dicData = reactive({});
    const onLoad = onLoadDicUrl({key: "groupName"}, {key: "tableName"});
    const onUpdate = onUpdateDicData({key: "groupName"});
    const onFormLoaded = onFormLoadedUrl({key: "permission"});
    onMounted(() => {
        onLoad(dicData);
    });
    // 提交表单数据
    const form = reactive({
        flowKey: '',
        icon: '',
        formName: '',
        groupName: '',
        tableName: '',
        permission: '',
        remark: '',
        status: '-1',
        isActive: '1',
        isAutoAudit: '0',
        sort: 1,
    });

    // 定义校验规则
    const dataRules = ref({
        flowKey: [{required: true, message: '流程KEY不能为空', trigger: 'blur'}],
        icon: [{required: true, message: '表单图标不能为空', trigger: 'blur'}],
        formName: [{required: true, message: '表单名称不能为空', trigger: 'blur'}],
        groupName: [{required: true, message: '分组名称不能为空', trigger: 'blur'}],
        isActive: [{required: true, message: '默认展示不能为空', trigger: 'blur'}],
        isAutoAudit: [{required: true, message: '提交时自动审批不能为空', trigger: 'blur'}],
        sort: [{required: true, message: '排序值不能为空', trigger: 'blur'}],
        type: [{required: true, message: '表单类型不能为空', trigger: 'blur'}],
        status: [{required: true, message: '状态不能为空', trigger: 'blur'}],
    })

    // 打开弹窗
    const openDialog = (type: string, id: string) => {
        visible.value = true
        operType.value = type;
        setPropsNull(form, 'id', 'flowKey', 'defFlowId')

        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();
            // 获取FlowApplication信息
            if (id) {
                form.id = id
                getFlowApplicationData(id)
            }
        });
    };

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

    function changeSubTableName() {
        form.subMainField = null
        form.mainSubProp = null
    }

    function remoteMethod(query: string) {
        remoteMethodByKey(query, onLoad, dicData, 'roleName', "permission")
    }

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

        if (form.type === DIC_PROP.FORM_TYPE[1].value) {
            if (!form.path) {
                notifyLeft('当前表单类型为系统表单，【PC端路径】不能为空', 'warning')
                return false
            }
        }
        if(!validateNull(form.subTableName)) {
            if (!form.subMainField || !form.mainSubProp) {
                notifyLeft('请填写 关联主表列名 或者 关联子表属性', 'warning')
                return false
            }
        }
        let isDesign = form.type !== DIC_PROP.FORM_TYPE[1].value;
        if (isDesign && !form.formInfo) {
            notifyLeft('当前表单类型为设计表单，请先完善第二项设计的表单内容', 'warning')
            return false
        }
        validateFormTypeSave(form)
        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 getFlowApplicationData = (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>
