<template>
    <div>
        <el-form ref="dataFormRef" :model="form" :rules="dataRules" label-width="90px" v-loading="loading"
                 :disabled="operType === 'view'">
            <el-row :gutter="24">
                <el-col :span="12" class="mb20" v-if="!hiddenFields.type">
                    <el-form-item :label="t('askLeave.type')" prop="type">
                        <el-input v-model="form.type" :placeholder="t('askLeave.inputTypeTip')" :disabled="disabledFields.type"/>
                    </el-form-item>
                </el-col>

                <el-col :span="12" class="mb20" v-if="!hiddenFields.startTime">
                    <el-form-item :label="t('askLeave.startTime')" prop="startTime">
                        <el-date-picker type="datetime" :placeholder="t('askLeave.inputStartTimeTip')" :disabled="disabledFields.startTime"
                                        v-model="form.startTime" :value-format="dateTimeStr"></el-date-picker>
                    </el-form-item>
                </el-col>

                <el-col :span="12" class="mb20" v-if="!hiddenFields.endTime">
                    <el-form-item :label="t('askLeave.endTime')" prop="endTime">
                        <el-date-picker type="datetime" :placeholder="t('askLeave.inputEndTimeTip')" :disabled="disabledFields.endTime"
                                        v-model="form.endTime" :value-format="dateTimeStr"></el-date-picker>
                    </el-form-item>
                </el-col>

                <el-col :span="12" class="mb20" v-if="!hiddenFields.days">
                    <el-form-item :label="t('askLeave.days')" prop="days">
                        <el-input v-model="form.days" :placeholder="t('askLeave.inputDaysTip')" :disabled="disabledFields.days"/>
                    </el-form-item>
                </el-col>

                <el-col :span="12" class="mb20" v-if="!hiddenFields.carbonCopyPerson">
                    <el-form-item :label="t('askLeave.carbonCopyPerson')" prop="carbonCopyPerson">
                        <el-tooltip content="请输入用户名称进行模糊搜索" placement="top">
                            <el-select v-model="form.carbonCopyPerson" :placeholder="t('askLeave.inputCarbonCopyPersonTip')" :disabled="disabledFields.carbonCopyPerson"
                                       remote :remote-method="remoteMethod" :reserve-keyword="false"
                                       clearable filterable multiple>
                                <el-option v-for="(item, index) in dicData.carbonCopyPerson" :key="index" :label="item.name"
                                           :value="item.userId">

                                </el-option>
                            </el-select>
                        </el-tooltip>
                    </el-form-item>
                </el-col>

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

                <el-col :span="12" class="mb20" v-if="!hiddenFields.imgUrls">
                    <el-form-item :label="t('askLeave.imgUrls')" prop="imgUrls">
                        <el-input v-model="form.imgUrls" :placeholder="t('askLeave.inputImgUrlsTip')" :disabled="disabledFields.imgUrls"/>
                    </el-form-item>
                </el-col>

            </el-row>
        </el-form>
        <template v-if="data.submitBtn">
            <footer class="el-dialog__footer">
                <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>
        </template>
        <template v-else>
            <footer class="el-dialog__footer">
                <span class="dialog-footer">
                    <el-button type="primary" @click="printForm" v-if="data.currFlowForm.printInfo">{{
                            t('jfI18n.print')
                        }}
                    </el-button>
                </span>
            </footer>
        </template>

        <!-- 打印表单 -->
        <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" :elTab="data.elTab"></tinymce-view>
        </el-dialog>
    </div>
</template>

<script setup lang="ts" name="CustomLeaveFlow">

    import {useMessage} from "/@/hooks/message";
    import {useI18n} from "vue-i18n"
    import {rule, validateNull} from '/@/utils/validate';
    import {onFormLoadedUrl, onLoadDicUrl, remoteMethodByKey} from "/@/flow/components/convert-name/convert.ts";
    import * as orderVue from "/@/api/order/order-key-vue";
    import * as runApplication from "/@/api/order/run-application";
    import {parseWithFunctions} from "/@/flow";
    import {deepClone} from "/@/utils/other";
    import {handleCustomFormPerm, handleFormPrint} from "/@/flow/utils/form-perm";
    import {initCustomFormMethods} from "../index";

    const {t} = useI18n();
    const emits = defineEmits(["handleJob"]);
    // 引入组件
    const TinymceView = defineAsyncComponent(() => import('/@/flow/components/tinymce/TinymceView.vue'));

    // 定义变量内容
    const dataFormRef = ref();
    const loading = ref(false);
    const operType = ref(false);
    // 定义字典
    const dicData = reactive({});
    const onLoad = onLoadDicUrl();
    const onFormLoaded = onFormLoadedUrl({key: "carbonCopyPerson"});
    onMounted(async () => {
        // await onLoad(dicData);
    });

    function remoteMethod(query: string) {
        remoteMethodByKey(query, onLoad, dicData, 'userName', "carbonCopyPerson")
    }

    // 提交表单数据
    const form = reactive({
        type: '',
        startTime: '',
        endTime: '',
        days: '',
        carbonCopyPerson: [],
        remark: '',
        imgUrls: '',
    });

    // 定义校验规则
    const dataRules = ref({
        startTime: [{required: true, message: '开始时间不能为空', trigger: 'blur'}],
        days: [{required: true, message: '请假天数不能为空', trigger: 'blur'}],
        remark: [{required: true, message: '请假事由不能为空', trigger: 'blur'}],
    })

    const props = defineProps({
        currJob: {
            type: Object,
            default: null,
        },
        currElTab: {
            type: Object,
            default: {},
        },
    });

    const data = reactive({
        currFlowForm: {},
        formData: {},
        showTinymceView: false,
        tinymceTitle: null,
        submitBtn: true,
        elTab: null
    })

    function initJobData() {
        handleGetObj(props.currJob.orderId)
    }

    const fieldsPerm = {
        type: false,
        startTime: false,
        endTime: false,
        days: false,
        carbonCopyPerson: false,
        remark: false,
        imgUrls: false,
    }
    // 定义字段显隐
    const hiddenFields = reactive(fieldsPerm);
    // 定义字段是否可编辑
    const disabledFields = reactive(deepClone(fieldsPerm));

    function handleGetObj(id) {
        runApplication.getObj(id).then(async resp => {
            let res = resp.data ? resp.data : {}
            data.currFlowForm = res
            let data2 = parseWithFunctions(res.formData)
            Object.assign(form, data2)
            await onFormLoaded(dicData, form);
            data.currFlowForm.runJobId = props.currJob.id
            data.formData = data2
            await initFormPermPrint()
        })
    }

    const methods = initCustomFormMethods(data, disabledFields, operType)

    async function initFormPermPrint() {
        let elTab = orderVue.currElTabIsExist(props.currJob, props.currElTab.id)
        // 处理表单权限
        let res = await handleCustomFormPerm(props, hiddenFields, disabledFields, elTab)
        // 判断是否仅查看
        await orderVue.currElTabIsView(methods, props.currJob, props.currElTab.id, submitForm, res.callback)
        // 采用elTab配置的模板
        await handleFormPrint(data.currFlowForm, elTab.type, elTab.id, '1')
        data.elTab = elTab
    }

    function printForm() {
        closePrint(true, false)
        data.tinymceTitle = data.currFlowForm.formName
        data.showTinymceView = true
    }

    function closePrint(isInit, isSave){
        if (isInit) {
            data.currFlowForm.formData = form
            data.currFlowForm.dicData = {carbonCopyPerson: dicData.carbonCopyPerson}
            data.currFlowForm['carbonCopyPerson.valueKey'] = 'userId'
            data.currFlowForm['carbonCopyPerson.showKey'] = 'name'
        } else {
            delete data.currFlowForm.dicData
            delete data.currFlowForm['carbonCopyPerson.valueKey']
            delete data.currFlowForm['carbonCopyPerson.showKey']
        }
        if (isSave) delete data.currFlowForm.printInfo
    }

    async function submitForm() {
        try {
            loading.value = true;
            let formJson = saveInitData(form);
            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().error(err.msg);
        } finally {
            loading.value = false;
        }
    }

    function saveInitData(form) {
        closePrint(false, true)
        data.currFlowForm.formData = validateNull(form) ? null : form
        let formJson = deepClone(data.currFlowForm)
        if (!validateNull(form)) {
            formJson.formData = Object.assign({}, data.formData, formJson.formData);
        }
        formJson.formData = JSON.stringify(formJson.formData)
        return formJson;
    }

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

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

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

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

