<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">
                    <el-form-item :label="t('handoverFlow.type')" prop="type">
                        <el-select v-model="form.type" :placeholder="t('handoverFlow.inputTypeTip')" clearable
                                   filterable disabled>
                            <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.receiveDept')" prop="receiveDept">
                        <el-tooltip content="请输入部门名称进行模糊搜索" placement="top">
                            <el-select v-model="form.receiveDept" :placeholder="t('handoverFlow.inputReceiveDeptTip')"
                                       remote :remote-method="remoteMethodDept" :reserve-keyword="false"
                                       clearable filterable disabled>
                                <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')"
                                       remote :remote-method="remoteMethodUser" :reserve-keyword="false"
                                       clearable filterable disabled>
                                <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-row>
        </el-form>
        <template v-if="operType !== 'view'">
            <footer class="el-dialog__footer">
                <span class="dialog-footer">
                  <el-button type="primary" @click="methods.handleUpdate" :disabled="loading">{{
                          $t('common.confirmButtonText')
                      }}</el-button>
                </span>
            </footer>
        </template>
    </div>
</template>

<script setup lang="ts" name="HandoverDistributionForm">
    import {useMessage} from "/@/hooks/message";
    import {distributePerson, getObj} from '/@/api/order/handover-flow'
    import {useI18n} from "vue-i18n"
    import {rule} from '/@/utils/validate';
    import {onFormLoadedUrl, onLoadDicUrl, remoteMethodByKey} from "/@/flow/components/convert-name/convert";
    import * as orderVue from "/@/api/order/order-key-vue";

    const {t} = useI18n();
    const emits = defineEmits(["handleJob"]);
    // 定义变量内容
    const dataFormRef = ref();
    const loading = ref(false);
    const operType = ref(false);
    // 定义字典
    const dicData = reactive({});
    const onLoad = onLoadDicUrl();
    const onFormLoaded = onFormLoadedUrl({key: "receiveDept"}, {key: "receiveUser"});
    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({
        type: '',
        receiveDept: '',
        receiveUser: '',
    });

    // 定义校验规则
    const dataRules = ref({
        type: [{required: true, message: '交接类型不能为空', trigger: 'blur'}],
        receiveDept: [{required: true, message: '接收部门不能为空', trigger: 'blur'}],
        receiveUser: [{required: true, message: '接收人不能为空', trigger: 'blur'}],
    })

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

    const methods = {
        disableForm() {
            operType.value = "view"
        },
        enableForm() {
            operType.value = "flow"
        },
        async initJobData() {
            await orderVue.currElTabIsView(methods, props.currJob, props.currElTab.id, methods.handleUpdate)
            methods.handleGetObj(props.currJob.orderId)
        },
        handleGetObj(id) {
            getObj(id).then(response => {
                Object.assign(form, response.data)
                onFormLoaded(dicData, form);
                form.runJobId = props.currJob.id
            })
        },
        async handleUpdate() {
            try {
                loading.value = true;
                // 转岗或离职交接时需要分配接收人来接收未来任务
                let handoverReason = props.currJob.order.handoverReason;
                if (form.isNeedReceive && (handoverReason === '1' || handoverReason === '2') && !form.receiveUser) {
                    useMessage().error('转岗或离职交接时需要分配接收人来接收未来任务')
                    return
                }
                await distributePerson(form)
                orderVue.currElTabIsSave(props.currJob, props.currElTab.id, true, emits)
                useMessage().success('操作成功')
            } catch (err: any) {
                useMessage().error(err.msg);
            } finally {
                loading.value = false;
            }
        }
    }

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

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

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

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