<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="90px" v-loading="loading" :disabled="operType === 'view'">
            <el-row :gutter="24">
                <el-col :span="12" class="mb20">
                    <el-form-item :label="t('handoverFlow.code')" prop="code">
                        <el-input v-model="form.code" :placeholder="t('handoverFlow.inputCodeTip')" disabled/>
                    </el-form-item>
                </el-col>

                <el-col :span="12" class="mb20">
                    <el-form-item :label="t('handoverFlow.flowKey')" prop="flowKey">
                        <el-select v-model="form.flowKey" :placeholder="t('handoverFlow.inputFlowKeyTip')" clearable filterable disabled>
                            <el-option v-for="(item, index) in cascadeDic.flowKey" :key="index" :label="item.flowName" :value="item.flowKey"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>

                <el-col :span="12" class="mb20">
                    <el-form-item :label="t('handoverFlow.type')" prop="type">
                        <el-select v-model="form.type" :placeholder="t('handoverFlow.inputTypeTip')" clearable filterable>
                            <el-option v-for="(item, index) in DIC_PROP.HANDOVER_TYPE" :key="index" :label="item.label" :value="item.value"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>

                <el-col :span="12" class="mb20">
                    <el-form-item :label="t('handoverFlow.status')" prop="status">
                        <el-select v-model="form.status" :placeholder="t('handoverFlow.inputStatusTip')" clearable filterable>
                            <el-option v-for="(item, index) in DIC_PROP.HANDOVER_STATUS" :key="index" :label="item.label" :value="item.value"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>

                <el-col :span="12" class="mb20">
                    <el-form-item :label="t('handoverFlow.handoverReason')" prop="handoverReason">
                        <el-select v-model="form.handoverReason" :placeholder="t('handoverFlow.inputHandoverReasonTip')" clearable filterable>
                            <el-option v-for="(item, index) in DIC_PROP.HANDOVER_REASON" :key="index" :label="item.label" :value="item.value"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>

                <el-col :span="12" class="mb20">
                    <el-form-item :label="t('handoverFlow.handoverUserDept')" prop="handoverUserDept">
                        <el-select v-model="form.handoverUserDept" :placeholder="t('handoverFlow.inputHandoverUserDeptTip')" clearable filterable disabled>
                            <el-option v-for="(item, index) in dicData.handoverUserDept" :key="index" :label="item.name" :value="item.deptId"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>

                <el-col :span="12" class="mb20">
                    <el-form-item :label="t('handoverFlow.handoverUser')" prop="handoverUser">
                        <el-select v-model="form.handoverUser" :placeholder="t('handoverFlow.inputHandoverUserTip')" clearable filterable disabled>
                            <el-option v-for="(item, index) in dicData.handoverUser" :key="index" :label="item.name" :value="item.userId"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>

                <el-col :span="12" class="mb20">
                    <el-form-item :label="t('handoverFlow.receiveDept')" prop="receiveDept">
                        <el-tooltip content="请输入部门名称进行模糊搜索" placement="top">
                            <el-select v-model="form.receiveDept" :placeholder="t('handoverFlow.inputReceiveDeptTip')" clearable filterable
                                       remote :remote-method="remoteMethodDept" :reserve-keyword="false">
                                <el-option v-for="(item, index) in dicData.receiveDept" :key="index" :label="item.name" :value="item.deptId"></el-option>
                            </el-select>
                        </el-tooltip>
                    </el-form-item>
                </el-col>

                <el-col :span="12" class="mb20">
                    <el-form-item :label="t('handoverFlow.receiveUser')" prop="receiveUser">
                        <el-tooltip content="请输入用户名称进行模糊搜索" placement="top">
                            <el-select v-model="form.receiveUser" :placeholder="t('handoverFlow.inputReceiveUserTip')" clearable filterable
                                       remote :remote-method="remoteMethodUser" :reserve-keyword="false">
                                <el-option v-for="(item, index) in dicData.receiveUser" :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('handoverFlow.finishTime')" prop="finishTime">
                        <el-date-picker type="datetime" :placeholder="t('handoverFlow.inputFinishTimeTip')" v-model="form.finishTime" :value-format="dateTimeStr"></el-date-picker>
                    </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="HandoverFlowDialog">

    import { useMessage } from "/@/hooks/message";
    import { getObj, addObj, putObj } from '/@/api/order/handover-flow'
    import { useI18n } from "vue-i18n"
    import { rule } from '/@/utils/validate';
    import {
        onCascadeChange,
        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 cascadeDic = reactive({});
    const onLoad = onLoadDicUrl();
    const onFormLoaded = onFormLoadedUrl({key: "receiveDept"}, {key: "receiveUser"}, {key: "handoverUserDept"}, {key: "handoverUser"});
    const onCascade = onCascadeChange(cascadeDic, {key: "flowInstId", cascades: ["flowKey"]});
    onMounted(() => {
        // onLoad(dicData);
    });

    function remoteMethodDept(query: string) {
        remoteMethodByKey(query, onLoad, dicData, 'deptName', "receiveDept")
    }

    function remoteMethodUser(query: string) {
        remoteMethodByKey(query, onLoad, dicData, 'userName', "receiveUser")
    }

    // 提交表单数据
    const form = reactive({
        code: '',
        flowKey: '',
        type: '',
        status: '',
        handoverReason: '',
        handoverUser: '',
        handoverUserDept: '',
        receiveDept: '',
        receiveUser: '',
        flowInstId: '',
        finishTime: '',
    });

    // 定义校验规则
    const dataRules = ref({
        code: [{required: true, message: '编号不能为空', trigger: 'blur'}],
        flowKey: [{required: true, message: '业务类型不能为空', trigger: 'blur'}],
        type: [{required: true, message: '交接类型不能为空', trigger: 'blur'}],
        status: [{required: true, message: '状态不能为空', trigger: 'blur'}],
        handoverReason: [{required: true, message: '交接原因不能为空', trigger: 'blur'}],
        receiveDept: [{required: true, message: '接收部门不能为空', trigger: 'blur'}],
        receiveUser: [{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();
        });

        // 获取HandoverFlow信息
        if (id) {
            form.id = id
            getHandoverFlowData(id)
        }
    };

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

        try {
            loading.value = true;
            form.id ? await putObj(form) : await addObj(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 getHandoverFlowData = (id: string) => {
        // 获取数据
        loading.value = true
        getObj(id).then((res: any) => {
            Object.assign(form, res.data)
            onFormLoaded(dicData, form);
            onCascade(form);
        }).finally(() => {
            loading.value = false
        })
    };

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