<template>
    <div>
        <el-form ref="dataFormRef" :model="props.currFlowForm" :rules="dataRules" label-width="150px"
                 v-loading="loading"
                 label-position="left"
                 :disabled="operType === 'view'">
            <el-row :gutter="24">
                <el-col :span="12" class="mb20" :offset="6">
                    <el-form-item :label="t('flowApplication.flowKey')" prop="flowKey">
                        <el-input v-model="props.currFlowForm.flowKey" clearable
                                  :placeholder="t('flowApplication.inputFlowKeyTip')"/>
                    </el-form-item>
                </el-col>

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

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

                <el-col :span="12" class="mb20" :offset="6">
                    <el-form-item :label="t('flowApplication.groupName')" prop="groupName">
                        <el-select v-model="props.currFlowForm.groupName" style="width: 83%!important;"
                                   :placeholder="t('flowApplication.inputGroupNameTip')"
                                   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" :offset="6">
                    <el-form-item :label="t('flowApplication.type')" prop="type">
                        <el-select v-model="props.currFlowForm.type" :disabled="!!validateRunFlow(props)"
                                   :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" :offset="6" v-if="props.currFlowForm.type === DIC_PROP.FORM_TYPE[1].value">
                    <el-tooltip content="当表单设计的页面为空时，可配置本地自定义主表单Vue页面路径" placement="top">
                        <el-form-item :label="t('tabsOption.path')" prop="path">
                            <el-input v-model="props.currFlowForm.path" :placeholder="t('tabsOption.inputPathTip')" clearable>
                            </el-input>
                        </el-form-item>
                    </el-tooltip>
                </el-col>

                <el-col :span="12" class="mb20" :offset="6">
                    <el-form-item :label="t('flowApplication.tableName')" prop="tableName">
                        <el-tooltip content="若自行调用接口保存表单数据，则此处需为空" placement="top">
                            <el-select v-model="props.currFlowForm.tableName" @clear="props.currFlowForm.tableName = null"
                                       :placeholder="t('flowApplication.inputTableNameTip')" style="width: 83%!important;"
                                       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-button
                                type="primary" size="small" round style="margin-left: 10px"
                                @click="addUpdateTableName()"
                        >{{ props.currFlowForm.tableName ? '修改表' : '新增表'}}
                        </el-button>
                    </el-form-item>
                </el-col>

                <el-col :span="12" class="mb20" :offset="6" v-if="!validateRunFlow(props)">
                    <el-form-item :label="t('flowApplication.permission')" prop="permission">
                        <el-tooltip content="请输入角色名称进行模糊搜索，默认所有人都可以发起该流程" placement="top">
                            <el-select v-model="props.currFlowForm.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" :offset="6">
                    <el-form-item :label="t('flowApplication.subTableName')" prop="subTableName">
                        <el-tooltip content="当存在多个关联子表时，多个子表名称名顺序与《关联子表属性》顺序一一对应" placement="top">
                            <el-select v-model="props.currFlowForm.subTableName" :placeholder="t('flowApplication.inputSubTableNameTip')" style="width: 83%!important;"
                                       @change="changeSubTableName" clearable filterable multiple>

                                <el-option v-for="(item, index) in dicData.tableName" :key="index"
                                           :label="item.tableName" :value="item.tableName">
                                    <span> {{ item.tableName }} </span>
                                    <span style="float: right; color: #409EFF" @click="addUpdateTableName(item.tableName, true)"> 点击修改 </span>
                                </el-option>
                            </el-select>
                        </el-tooltip>

                        <el-button
                                type="primary" size="small" round style="margin-left: 10px"
                                @click="addUpdateTableName(null, true)"
                        >新增子表
                        </el-button>
                    </el-form-item>
                </el-col>

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

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

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

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

                <el-col :span="12" class="mb20" v-if="!validateRunFlow(props)" :offset="6">
                    <el-tooltip content="在审批时默认展示的第1个页面。当存在多个默认展示页面时，优先展示排序值最小的" placement="top">
                        <el-form-item :label="t('tabsOption.isActive')" prop="isActive">
                            <el-radio-group v-model="props.currFlowForm.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-tooltip>
                </el-col>

                <el-col :span="12" class="mb20" v-if="!validateRunFlow(props)" :offset="6">
                    <el-tooltip content="在审批时不会显示审批按钮，在页面点提交按钮会自动流转到下一步" placement="top">
                        <el-form-item :label="t('tabsOption.isAutoAudit')" prop="isAutoAudit">
                            <el-radio-group v-model="props.currFlowForm.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-tooltip>
                </el-col>

                <el-col :span="12" class="mb20" :offset="6">
                    <el-form-item :label="t('flowApplication.status')" prop="status">
                        <el-radio-group v-model="props.currFlowForm.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>

        <!-- 编辑、新增  -->
        <create-table ref="createTableRef" @refreshDone="createTableDone" />
    </div>
</template>

<script setup lang="ts" name="FlowApplicationForm">
    import {useMessage, useMessageBox} from "/@/hooks/message";
    import * as runApplication from "/@/api/order/run-application";
    import * as flowApplication from "/@/api/order/flow-application";
    import other from '/@/utils/other';
    import {notifyLeft, stringifyWithFunctions, validateRunFlow} from "/@/flow";
    import {useI18n} from "vue-i18n"
    import {
        onFormLoadedUrl,
        onLoadDicUrl,
        onUpdateDicData,
        remoteMethodByKey
    } from "/@/flow/components/convert-name/convert";
    import {validateNull} from "/@/utils/validate";
    import {DIC_PROP} from "../../support/dict-prop";
    import {validateFormTypeSave, vueKey} from "/@/api/order/order-key-vue";
    import {PROP_CONST} from "../../support/prop-const";

    const {t} = useI18n();
    const {proxy} = getCurrentInstance();
    const props = defineProps({
        currFlowForm: {
            type: Object,
            default: null,
        }
    });
    // 引入组件
    const IconSelector = defineAsyncComponent(() => import('/@/components/IconSelector/index.vue'));
    const CreateTable = defineAsyncComponent(() => import('/@/views/order/create-table/form.vue'));

    // 定义变量内容
    const dataFormRef = ref();
    const loading = ref(false);
    const operType = ref(false);
    // 定义字典
    const dicData = reactive({});
    const onLoad = onLoadDicUrl({key: "groupName"}, {key: "tableName"});
    const onFormLoaded = onFormLoadedUrl({key: "permission"});
    const onUpdate = onUpdateDicData({key: "groupName"});
    onMounted(async () => {
        await onLoad(dicData);
        await onFormLoaded(dicData, props.currFlowForm);
        let isNoGroupName = !props.currFlowForm.groupName && dicData.groupName.length > 0;
        if (isNoGroupName) {
            props.currFlowForm.groupName = dicData.groupName[0].groupName
        }
    });

    const data = reactive({subTableName: null, updateSubTableName: null, isSubTableName: false});

    // 定义校验规则
    const dataRules = ref({
        flowKey: [{required: true, message: '流程KEY不能为空', trigger: 'blur'}],
        icon: [{required: true, message: '表单图标不能为空', trigger: 'blur'}],
        type: [{required: true, message: '表单类型不能为空', trigger: 'blur'}],
        formName: [{required: true, message: '表单名称不能为空', trigger: 'blur'}],
        groupName: [{required: true, message: '分组名称不能为空', trigger: 'blur'}],
        status: [{required: true, message: '状态不能为空', trigger: 'blur'}],
    })

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

    function changeSubTableName() {
        if (data.isSubTableName) {
            if (data.subTableName) props.currFlowForm.subTableName = data.subTableName
            return
        }
        if (!validateNull(props.currFlowForm.subTableName)) {
            return
        }
        props.currFlowForm.subMainField = null
        props.currFlowForm.mainSubProp = null
    }

    function addUpdateTableName(subTableName?, isSubTableName?) {
        data.isSubTableName = isSubTableName
        if (isSubTableName && subTableName) {
            data.subTableName = props.currFlowForm.subTableName
            data.updateSubTableName = subTableName
        }
        let tableName = isSubTableName ? subTableName : props.currFlowForm.tableName;
        if (tableName) {
            if (tableName === PROP_CONST.COMMON.tableName) {
                notifyLeft('当前表为系统表，请勿修改', 'warning')
            } else {
                let find = dicData.tableName.find(f => f.tableName === tableName);
                proxy.$refs.createTableRef.openDialog('edit', find.id)
            }
        } else {
            proxy.$refs.createTableRef.openDialog('add')
        }
    }

    function createTableDone(tableName, operType, isOnSubmit) {
        if (data.isSubTableName) {
            if (isOnSubmit && operType === 'edit' && data.updateSubTableName !== tableName){
                let includes = props.currFlowForm.subTableName.includes(data.updateSubTableName);
                if (includes) {
                    // 修改表名
                    let findIndex = props.currFlowForm.subTableName.findIndex(f => f === data.updateSubTableName);
                    props.currFlowForm.subTableName.splice(findIndex, 1, tableName)
                }
            } else if (isOnSubmit && operType === 'add'){
                props.currFlowForm.subTableName.push(tableName)
            }
            data.isSubTableName = false
            data.updateSubTableName = null
            data.subTableName = null
        } else if (isOnSubmit){
            props.currFlowForm.tableName = tableName
        }
        if (!isOnSubmit) return
        const onLoad = onLoadDicUrl({key: "tableName"});
        onLoad(dicData)
    }

    async function validatePreSave() {
        const valid = await dataFormRef.value.validate().catch(() => {});
        if (!valid) {
            notifyLeft('请先完善表单设置内容', 'warning')
            return false;
        }
        let isSys = props.currFlowForm.type === DIC_PROP.FORM_TYPE[1].value;
        if (isSys && !props.currFlowForm.path) {
            notifyLeft('当前表单类型为系统表单，【PC端路径】不能为空', 'warning')
            return false
        }
        if(!validateNull(props.currFlowForm.subTableName)) {
            if (!props.currFlowForm.subMainField || !props.currFlowForm.mainSubProp) {
                notifyLeft('请填写 关联主表列名 或者 关联子表属性', 'warning')
                return false
            }
        }
        return true
    }

    function validateOtherSave() {
        let isDesign = props.currFlowForm.type !== DIC_PROP.FORM_TYPE[1].value;
        if (isDesign && !props.currFlowForm.formInfo) {
            notifyLeft('当前表单类型为设计表单，请先完善第二项设计的表单内容', 'warning')
            return false
        }
        return true
    }

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

    const handleSubmit = async (callback, status) => {
        if (status) {
            props.currFlowForm.status = status
        }
        let preSave = await validatePreSave();
        if (!preSave) return
        if (!validateOtherSave()) return
        let formJson = other.deepClone(props.currFlowForm)
        formJson.formInfo = stringifyWithFunctions(formJson.formInfo)

        validateFormTypeSave(formJson)
        try {
            loading.value = true;
            // 判断是否为低代码
            if (validateRunFlow(props) && props.currFlowForm.tableName) {
                await runApplication.putObjNoStatus(formJson)
            } else {
                await flowApplication.addObj(formJson);
            }
            props.currFlowForm.formSetting = true
            notifyLeft('当前表单设置保存成功')
            if (callback) callback()
        } catch (err: any) {
            useMessage().error(err);
        } finally {
            loading.value = false;
        }
    }

    // 暴露变量
    defineExpose({
        handleSubmit, validatePreSave, validateOtherSave
    });
</script>
