<template>
    <el-dialog :title="title" v-model="visible" width="60%"
               :close-on-click-modal="false" draggable>
        <el-form ref="dataFormRef" :model="form" :rules="dataRules" label-width="110px" v-loading="loading" :disabled="operType === 'view'">
            <el-row :gutter="24">
                <el-col :span="12" class="mb20">
                    <el-form-item :label="t('distPerson.delRoleId')" prop="delRoleId">
                        <el-tooltip content="请输入用户名称进行模糊搜索" placement="top">
                            <el-select v-model="form.delRoleId" :placeholder="t('distPerson.inputDelRoleIdTip')" clearable filterable
                                       remote :remote-method="remoteMethodDel" :reserve-keyword="false">
                                <el-option v-for="(item, index) in dicData.delRoleId" :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">
                    <el-form-item :label="t('distPerson.recRoleId')" prop="roleId">
                        <el-tooltip content="请输入用户名称进行模糊搜索" placement="top">
                            <el-select v-model="form.roleId" :placeholder="t('distPerson.inputRoleIdTip')" clearable filterable
                                       remote :remote-method="remoteMethod" :reserve-keyword="false">
                                <el-option v-for="(item, index) in dicData.users" :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">
                    <el-form-item :label="t('distPerson.delStartTime')" prop="delStartTime">
                        <el-date-picker type="datetime" :placeholder="t('distPerson.inputDelStartTimeTip')"
                                        v-model="form.delStartTime" :value-format="dateTimeStr"></el-date-picker>
                    </el-form-item>
                </el-col>

                <el-col :span="12" class="mb20">
                    <el-form-item :label="t('distPerson.delEndTime')" prop="delEndTime">
                        <el-date-picker type="datetime" :placeholder="t('distPerson.inputDelEndTimeTip')"
                                        v-model="form.delEndTime" :value-format="dateTimeStr"></el-date-picker>
                    </el-form-item>
                </el-col>

                <el-col :span="12" class="mb20">
                    <el-form-item :label="t('distPerson.delStatus')" prop="delStatus">
                        <el-radio-group v-model="form.delStatus">
                            <el-radio v-for="(item, index) in DIC_PROP.DELEGATE_STATUS" :key="index" :label="item.value" >
                                {{ getLabelByLanguage(item) }}
                            </el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-col>

            </el-row>
        </el-form>
        <template #footer v-if="operType !== 'view'">
        <span class="dialog-footer">
          <el-button @click="visible = false">{{ $t('common.cancelButtonText') }}</el-button>
          <el-button type="primary" @click="onSubmit" :disabled="loading">{{ $t('common.confirmButtonText') }}</el-button>
        </span>
        </template>
    </el-dialog>
</template>

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

    import { useMessage } from "/@/hooks/message";
    import { getObj, delegate } from '/@/api/jsonflow/dist-person'
    import { useI18n } from "vue-i18n"
    import {onFormLoadedUrl, onLoadDicUrl, remoteMethodByKey} from "/@/flow/components/convert-name/convert";
    const emit = defineEmits(['refresh']);

    const { t } = useI18n();

    // 定义变量内容
    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: "delRoleId"}, {key: "users", field: "roleId"});
    onMounted(() => {
        // onLoad(dicData);
    });

    // 提交表单数据
    const form = reactive({
        delRoleId: '',
        roleId: '',
        delStartTime: null,
        delEndTime: null,
        delStatus: '0',
    });

    // 定义校验规则
    const dataRules = ref({
        delRoleId: [{required: true, message: '委托人不能为空', trigger: 'blur'}],
        roleId: [{required: true, message: '接收人不能为空', trigger: 'blur'}],
        delStartTime: [{required: true, message: '委托开始时间不能为空', trigger: 'blur'}],
        delEndTime: [{required: true, message: '委托结束时间不能为空', trigger: 'blur'}],
        delStatus: [{required: true, message: '委托状态不能为空', trigger: 'blur'}],
    })

    // 打开弹窗
    const openDialog = (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');
        }

        // 重置表单数据
        nextTick(() => {
            dataFormRef.value?.resetFields();
        });

        // 获取DistPerson信息
        if (id) {
            form.id = id
            getDistPersonData(id)
        }
    };

    function remoteMethodDel(query: string) {
        remoteMethodByKey(query, onLoad, dicData, 'userName', "delRoleId")
    }

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

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

        try {
            loading.value = true;

            await delegate(form);
            useMessage().success(t(form.id ? 'common.editSuccessText' : 'common.addSuccessText'));
            visible.value = false;
            emit('refresh');
        } catch (err: any) {
            useMessage().error(err.msg);
        } finally {
            loading.value = false;
        }
    };

    // 初始化表单数据
    const getDistPersonData = (id: string) => {
        // 获取数据
        loading.value = true
        getObj(id).then((res: any) => {
            Object.assign(form, res.data)
            onFormLoaded(dicData, form);
        }).finally(() => {
            loading.value = false
        })
    };

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