<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')" 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 v-if="operType !== 'view'">
            <div style="text-align: center">
            <span class="dialog-footer">
                <template v-if="form.status !== DIC_PROP.ORDER_STATUS[0].value">
                    <el-button type="primary" @click="onSubmit" :disabled="loading">{{ $t('jfI18n.initialBtn') }}</el-button>
                    <el-button @click="onRefresh()">{{ $t('common.cancelButtonText') }}</el-button>
                    <el-button type="primary" @click="onTemp" :disabled="loading">{{ $t('jfI18n.temp') }}</el-button>
                </template>
                <template v-else>
                    <el-button type="primary" @click="printForm" v-if="form.printInfo">{{
                            t('jfI18n.print')
                        }}
                    </el-button>
                    <el-button type="primary" @click="onSubmit" :disabled="loading">{{ $t('common.editBtn') }}</el-button>
                </template>
            </span>
            </div>
        </template>
        <template v-if="operType === 'view'">
            <footer class="el-dialog__footer">
                <div style="text-align: center">
                <span class="dialog-footer">
                    <el-button type="primary" @click="printForm" v-if="form.printInfo">{{
                            t('jfI18n.print')
                        }}
                    </el-button>
                </span>
                </div>
            </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="form" :elTab="data.elTab"></tinymce-view>
    </el-dialog>
    </div>
</template>

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

    import { useMessage } from "/@/hooks/message";
    import {getObj, addObj, putObj, tempStore} from '/@/api/order/ask-leave'
    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 {handleFormPrint, handleFormStartPerm} from "/@/flow/utils/form-perm";
    import {currFormIsView, orderKeyMap} from "/@/api/order/order-key-vue";
    import {deepClone} from "/@/utils/other";
    import {DIC_PROP} from "/@/flow/support/dict-prop";
    import {initCustomFormMethods} from "../index";

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

    // 定义变量内容
    const dataFormRef = ref();
    const visible = ref(false);
    const loading = ref(false);
    const operType = ref(false);
    const title = ref('');
    // 定义字典
    const dicData = reactive({});
    const onLoad = onLoadDicUrl();
    const onFormLoaded = onFormLoadedUrl({key: "carbonCopyPerson"});
    onMounted(async () => {
        // await onLoad(dicData);
        await openDialog(props.formData.type, props.formData.id)
    });

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

    // 提交表单数据
    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 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 openDialog = async (type: string, id: string) => {
        visible.value = true
        operType.value = type;
        form.id = ''

        if (type === 'add') {
            title.value = t('common.addBtn');
        } else if (type === 'edit') {
            title.value = t('common.editBtn');
        } else if (type === 'view') {
            title.value = t('common.viewBtn');
        } else if (type === 'copy') {
            title.value = t('common.copyBtn');
        }

        // 重置表单数据
        nextTick(async () => {
            dataFormRef.value?.resetFields();
            // 获取AskLeave信息
            if (id) {
                form.id = id
                await getAskLeaveData(id)
            }
            await initFormPermPrint()
        });

    };

    const data = reactive({
        showTinymceView: false,
        tinymceTitle: '',
        elTab: null
    })

    const methods = initCustomFormMethods(data, disabledFields)

    async function initFormPermPrint() {
        // 处理表单权限 开始节点必须配置表单
        let res = await handleFormStartPerm(hiddenFields, disabledFields, null, null, orderKeyMap.AskLeave, null);
        await currFormIsView(methods, res.elTab, true, res.callback)
        // 采用elTab配置的模板
        await handleFormPrint(form, res.elTab.type, res.elTab.id, '1')
        data.elTab = res.elTab
    }

    function printForm() {
        closePrint(true, false)
        data.tinymceTitle = '请假工单'
        data.showTinymceView = true
    }

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

    // 暂存
    const onTemp = async () => {
        closePrint(false, true)

        let clone = {operType: operType.value, form: form};
        common.handleCloneSubmit(clone);
        try {
            loading.value = true;
            await tempStore(form);
            useMessage().success(t(form.id ? 'common.editSuccessText' : 'common.addSuccessText'));
            visible.value = false;
            onRefresh();
        } catch (err: any) {
            useMessage().error(err.msg);
        } finally {
            loading.value = false;
        }
    }

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

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

        let clone = {operType: operType.value, form: form};
        common.handleCloneSubmit(clone)
        try {
            loading.value = true;
            form.status !== DIC_PROP.ORDER_STATUS[0].value ? await addObj(form) : await putObj(form);
            useMessage().success(t(form.id ? 'common.editSuccessText' : 'common.addSuccessText'));
            visible.value = false;
            onRefresh();
        } catch (err: any) {
            useMessage().error(err.msg);
        } finally {
            loading.value = false;
        }
    };

    const onRefresh = () => {
        emit('refresh');
    }

    // 初始化表单数据
    const getAskLeaveData = async (id: string) => {
        // 获取数据
        loading.value = true
        let res = await getObj(id)
        loading.value = false
        Object.assign(form, res.data)
        await onFormLoaded(dicData, form);
        let clone = {operType: operType.value, form: form};
        common.handleClone(clone);
    };

    async function getFormData() {
        const valid = await dataFormRef.value.validate().catch(() => {});
        if (!valid) return false;
        return form
    }

    // 暴露变量
    defineExpose({
        openDialog,
        getFormData
    });
</script>
