<template>
    <div>
        <div class="layout-padding-auto layout-padding-view">
            <form-render ref="formCreateRef" :currFlowForm="data.currFlowFormClone" v-if="!validateNull(data.currFlowFormClone)"
                         :initFormPermPrint="initFormPermPrint">
            </form-render>

        <footer class="el-dialog__footer" v-if="data.submitBtn">
            <span class="dialog-footer">
                <el-button type="primary" @click="printForm" v-if="data.currFlowForm.printInfo">{{
                        t('jfI18n.print')
                    }}
                </el-button>
                <el-button type="primary" @click="submitForm" :disabled="loading">{{
                        t('jfI18n.submit')
                    }}
                </el-button>
            </span>
        </footer>
        <footer class="el-dialog__footer" v-else>
            <span class="dialog-footer">
                <el-button type="primary" @click="printForm" v-if="data.currFlowForm.printInfo">{{
                        t('jfI18n.print')
                    }}
                </el-button>
            </span>
        </footer>
        </div>

        <!-- 打印表单 -->
        <el-dialog v-model="data.showTinymceView" top="20px" width="700px"
                   :title="data.tinymceTitle" append-to-body
                   @close="closePrint">
            <tinymce-view v-if="data.showTinymceView" :currFlowForm="data.currFlowForm"></tinymce-view>
        </el-dialog>
    </div>
</template>

<script setup lang="ts" name="RunApplicationForm">
    import * as runApplication from '/@/api/order/run-application'
    import * as orderVue from "/@/api/order/order-key-vue";
    import {parseWithFunctions} from "/@/flow";
    import {handleDesignFormPerm, handleFormPrint} from "/@/flow/utils/form-perm";
    import {useI18n} from "vue-i18n";
    import {useMessage} from "/@/hooks/message";
    import {validateNull} from "/@/utils/validate";
    import {deepClone} from "/@/utils/other";
    import {initJobDataByApp} from "/@/flow/support/extend";
    import {initFormMethods} from "../index";

    const emits = defineEmits(["handleJob"]);
    const FormRender = defineAsyncComponent(() => import('/@/flow/components/form-create/render.vue'));
    const formCreateRef = ref(null)
    // 引入组件
    const TinymceView = defineAsyncComponent(() => import('/@/flow/components/tinymce/TinymceView.vue'));

    const {t} = useI18n();
    const loading = ref(false);
    const props = defineProps({
        currJob: {
            type: Object,
            default: {},
        },
        currElTab: {
            type: Object,
            default: {},
        },
    });
    const data = reactive({
        // 兼容app端监听printInfo
        currFlowForm: {
            type: Object,
            default: {},
        },
        // 含可选表单formInfo
        currFlowFormClone: {},
        elTab: null,
        initFormData: {},
        showTinymceView: false,
        tinymceTitle: null,
        submitBtn: true
    })

    const methods = initFormMethods(formCreateRef, data)

    const $route = useRoute();
    async function initJobData() {
        // 兼容移动端
        await initJobDataByApp($route, props);
        // 判断是否存在该表单
        data.elTab = orderVue.currElTabIsExist(props.currJob, props.currElTab.id);
        handleGetObj(props.currJob.orderId)
    }

    function handleGetObj(id) {
        runApplication.getObj(id).then(async resp => {
            let form = resp.data ? resp.data : {}
            data.currFlowForm = form
            data.currFlowForm.runJobId = props.currJob.id
            rowEditInitData(form)
        })
    }

    function rowEditInitData(form: Object) {
        let formInfoStr = form.formInfo
        // 判断是否为可选表单
        if (data.elTab.id !== form.formId) formInfoStr = data.elTab.formInfo
        data.currFlowFormClone = deepClone(form)
        data.currFlowFormClone.formInfo = formInfoStr
        // 记录原始值
        let formData = parseWithFunctions(form.formData)
        Object.assign(data.initFormData, formData)
    }

    async function initFormPermPrint(cloneFormInfo) {
        let form = data.currFlowForm
        // 判断是否为可选表单
        let formType = form.type, formId = form.formId
        if (data.elTab.id !== form.formId) {
            formType = data.elTab.type
            formId = data.elTab.id
        }
        let res = await handleDesignFormPerm(props, cloneFormInfo, data.elTab, formType, formId);
        // 判断是否仅查看
        await orderVue.currElTabIsView(methods, props.currJob, props.currElTab.id, submitForm, res.callback, res.widgetList)
        await handleFormPrint(form, formType, formId, '1')
        return data.elTab;
    }

    function printForm() {
        data.currFlowForm.formData = formCreateRef.value.design.formData
        data.currFlowForm.modelRefList = []
        let children = formCreateRef.value.design.fApi.children;
        if (children && children.length > 0) {
            children.forEach(each => data.currFlowForm.modelRefList.push({model: each.model}))
        }
        data.currFlowForm.rule = formCreateRef.value.design.rule
        data.tinymceTitle = data.currFlowForm.formName
        data.showTinymceView = true
    }

    function closePrint(isSave){
        delete data.currFlowForm.modelRefList
        delete data.currFlowForm.rule
        if (isSave) delete data.currFlowForm.printInfo
    }

    async function submitForm() {
        try {
            loading.value = true;
            let state = await formCreateRef.value.design.fApi.validate();
            let formData = formCreateRef.value.design.formData
            if (!state || validateNull(formData)) {
                useMessage().warning("请输入表单信息");
                return
            }
            let formJson = saveInitData(formData);
            await runApplication.putObj(formJson)
            orderVue.currElTabIsSave(props.currJob, props.currElTab.id, true, emits)
            useMessage().success(t(formJson.id ? 'common.editSuccessText' : 'common.addSuccessText'));
        } catch (err: any) {
            useMessage().warning("请输入表单信息");
        } finally {
            loading.value = false;
        }
    }

    function saveInitData(form) {
        closePrint(true)
        data.currFlowForm.formData = validateNull(form) ? null : form
        let formJson = deepClone(data.currFlowForm)
        if (!validateNull(form)) {
            // 合并不同页面不同字段
            formJson.formData = Object.assign({}, data.initFormData, formJson.formData);
        }
        formJson.formData = JSON.stringify(formJson.formData)
        return formJson;
    }

    // 监听双向绑定
    watch(
        () => props.currJob.id,
        async () => {
            await initJobData();
        }
    );

    onMounted(async () => {
        await initJobData()
    });
</script>

<style lang="scss" scoped>
  .el-dialog__footer {
    text-align: center;
    margin-top: 10px;

    .dialog-footer {
      text-align: center;
    }
  }
</style>
