<template>
    <div class="page-bg-wrap">
        <div class="top-toolbar">
            <a-space :size="10" wrap>
                <a-button style="margin-right: 10px" @click="close">
                    <slot name="icon">
                        <close-outlined />
                    </slot>
                    关闭
                </a-button>
                <a-button v-if="mode != 'view'" type="primary" @click="handleSubmit">
                    <slot name="icon">
                        <check-circle-outlined />
                    </slot>
                    确认
                </a-button>
            </a-space>
        </div>
        <component :is="dynamicComponent" ref="formRef" :fromPage="FromPageType.MENU" @form-mounted="onFormMounted" />
    </div>
</template>

<script setup>
import { useRouter } from 'vue-router';
import { FromPageType } from '/@/enums/workflowEnum';
import { ref, computed, onMounted, onBeforeMount, nextTick, defineAsyncComponent } from 'vue';
import { useMessage } from '/@/hooks/web/useMessage';
import { useI18n } from '/@/hooks/web/useI18n';
import { CheckCircleOutlined, StopOutlined, CloseOutlined } from '@ant-design/icons-vue';
import { useMultipleTabStore } from '/@/store/modules/multipleTab';
import useEventBus from '/@/hooks/event/useEventBus';

const dynamicComponent = ref(null);
const formType = ref('2'); // 0 新建 1 修改 2 查看
const formRef = ref();
const props = defineProps({});
const { bus, FORM_LIST_MODIFIED } = useEventBus();

const router = useRouter();
const { currentRoute } = router;

const { formPath } = currentRoute.value.query;
const pathArr = formPath.split('/');
const parentRoutePath = localStorage.getItem('parentRoutePath');
localStorage.removeItem('parentRoutePath');

const tabStore = useMultipleTabStore();
const formProps = ref(null);
const formId = ref(currentRoute.value?.params?.id);

const { notification } = useMessage();
const { t } = useI18n();
const hash = location.hash;
const mode = ref('read');
if (hash.indexOf('createForm') > 0) {
    mode.value = 'create';
} else if (hash.indexOf('updateForm') > 0) {
    mode.value = 'update';
} else if (hash.indexOf('viewForm') > 0) {
    mode.value = 'view';
}

dynamicComponent.value = defineAsyncComponent({
    loader: () => import(`./../../views/${pathArr[0]}/${pathArr[1]}/components/Form.vue`)
});

function onFormMounted(_formProps) {
    formProps.value = _formProps;
    setFormType();
}

async function setFormType() {
    const _mode = mode.value;
    if (_mode === 'create') {
        return;
    }
    await nextTick();
    if (_mode === 'view') {
        await formRef.value.setDisabledForm();
    }
    await formRef.value.setFormDataFromId(formId.value);
}

function close() {
    tabStore.closeTab(currentRoute.value, router, parentRoutePath);
}

async function handleSubmit() {
    try {
        const saveSuccess = await saveModal();
        if (saveSuccess) {
            notification.success({
                message: 'Tip',
                description: formType.value === '0' ? t('新增成功！') : t('修改成功！')
            }); //提示消息
            formRef.value.resetFields();
            setTimeout(() => {
                bus.emit(FORM_LIST_MODIFIED, { path: formPath, mode });
                close();
            }, 1000);
        }
    } finally {
    }
}

async function saveModal() {
    let saveSuccess = false;
    const _mode = mode.value;
    try {
        const values = await formRef.value?.validate();
        //添加隐藏组件
        if (formProps.hiddenComponent?.length) {
            formProps.hiddenComponent.forEach((component) => {
                values[component.bindField] = component.value;
            });
        }
        if (values !== false) {
            try {
                if (_mode === 'create') {
                    saveSuccess = await formRef.value.add(values);
                } else {
                    saveSuccess = await formRef.value.update({ values, rowId: formId.value });
                }
                return saveSuccess;
            } catch (error) { }
        }
    } catch (error) {
        console.error('saveModal Error: ', error);
    }
}
</script>

<style lang="less" scoped>
.page-bg-wrap {
    background-color: #fff;
}

.top-toolbar {
    min-height: 44px;
    margin-bottom: 12px;
    border-bottom: 1px solid #eee;
}
</style>
