<template>
    <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')" clearable filterable multiple
                                   remote :remote-method="remoteMethod" :reserve-keyword="false"
                                   :disabled="disabledFields.carbonCopyPerson">
                            <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>

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

    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 common from '/@/flow/support/common'
    import {paramsFilter, parseWithFunctions} from "/@/flow";
    import {deepClone} from "/@/utils/other";
    import * as runApplication from "/@/api/order/run-application";
    import {handleFormPrint, handleFormStartPerm} from "/@/flow/utils/form-perm";
    import {DIC_PROP} from "/@/flow/support/dict-prop";
    import {initCustomFormMethods} from "../index";
    import {currFormIsView} from "/@/api/order/order-key-vue";

    const { t } = useI18n();

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

    // 定义变量内容
    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);
        openForm(props.currJob.operType, props.currJob.id)
        props.currJob.onSubmit = onSubmit
        props.currJob.onTemp = onTemp
        props.currJob.getFormData = getFormData
    });

    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 openForm = (type: string, id: string) => {
        operType.value = type;

        // 重置表单数据
        nextTick(() => {
            dataFormRef.value?.resetFields();
            // 获取表单信息
            if (id) {
                rowEditInitData(type, id)
            }
        });
    };

    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));

    const methods = initCustomFormMethods({}, disabledFields)

    async function rowEditInitData(type, id) {
        // 处理表单权限 开始节点必须配置表单
        let res = await handleFormStartPerm(hiddenFields, disabledFields, null, props.currJob.defFlowId, null, null)
        await currFormIsView(methods, res.elTab, true, res.callback)
        if (type === 'add') {
            props.currJob.formId = id
            return
        }
        if (validateNull(props.currJob.formData)) return
        let data = parseWithFunctions(props.currJob.formData)
        Object.assign(form, data)
        await onFormLoaded(dicData, form);
        await initFormPermPrint()
    }

    async function initFormPermPrint() {
        // 处理表单权限
        await handleFormPrint(props.currJob, props.currJob.type, props.currJob.formId, '1')
        props.currJob.resolvePrintForm = printForm
        props.currJob.resolveClosePrint = closePrint
    }

    function printForm() {
        closePrint(true, false)
    }

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

    // 暂存
    const onTemp = async () => {
        let clone = {operType: operType.value, form: form};
        common.handleCloneSubmit(clone);
        try {
            loading.value = true;
            let formJson = saveInitData(form);
            await runApplication.tempStore(formJson)
            useMessage().success("暂存成功，请在【我的申请】查看");
            return true;
        } catch (err: any) {
            useMessage().error(err.msg);
        } finally {
            loading.value = false;
        }
    }

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

        let clone = {operType: operType.value, form: form};
        common.handleCloneSubmit(clone)
        try {
            loading.value = true;
            let formJson = saveInitData(form);
            props.currJob.status !== DIC_PROP.ORDER_STATUS[0].value ? await runApplication.addObj(formJson) : await runApplication.putObj(formJson);
            useMessage().success(t(formJson.id ? 'common.editSuccessText' : '发起成功，请在【我的申请】查看'));
            return true;
        } catch (err: any) {
            useMessage().error(err.msg);
        } finally {
            loading.value = false;
        }
    };

    function saveInitData(form) {
        closePrint(false, true)
        form = paramsFilter(form)
        props.currJob.formData = validateNull(form) ? undefined : form
        let formJson = deepClone(props.currJob)
        let clone = {operType: props.currJob.operType, form: formJson};
        common.handleCloneSubmit(clone)
        formJson.formData = JSON.stringify(formJson.formData)
        return formJson;
    }

    async function getFormData() {
        return saveInitData(form);
    }

</script>
