<template>
    <el-dialog v-model="visible" :title="titleMap[mode]" :width="860" :close-on-click-modal="false" @closed="$emit('closed')">
        <el-form ref="formRef" :model="form" :rules="rules" label-width="120">
            <el-row>
                <el-col v-if="props.projectId != 1" :md="12" :xs="24">
                    <el-form-item label="所属项目" prop="projectId">
                        <el-select v-model="form.projectId" filterable :disabled="mode != 'add'" placeholder="请选择所属项目">
                            <el-option v-for="item in $TOOL.data.get('PROJECT')" :key="item.fpiId" :label="item.projectName" :value="item.fpiId"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :md="12" :xs="24">
                    <el-form-item label="上级节点" prop="parentId">
                        <el-tree-select v-model="form.parentId" v-bind="treeSelectProps" :disabled="mode != 'add'"></el-tree-select>
                    </el-form-item>
                </el-col>
                <el-col :md="12" :xs="24">
                    <el-form-item label="节点名称" prop="nodeName">
                        <el-input v-model="form.nodeName" placeholder="请输入节点名称"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :md="12" :xs="24">
                    <el-form-item label="节点排序" prop="nodeSeq">
                        <el-input-number v-model="form.nodeSeq" :min="0" step-strictly :controls="false" placeholder="请输入节点排序"></el-input-number>
                    </el-form-item>
                </el-col>
                <el-col :md="12" :xs="24">
                    <el-form-item label="节点状态" prop="nodeStatus">
                        <el-select v-model="form.nodeStatus" filterable placeholder="请选择节点状态">
                            <el-option v-for="(label, key) in nodeStatusDic" :key="key" :label="label" :value="key"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :md="12" :xs="24">
                    <el-form-item label="计划开始时间">
                        <el-date-picker v-model="form.planStartTime" type="datetime" :clearable="false" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择计划开始时间"></el-date-picker>
                    </el-form-item>
                </el-col>
                <el-col :md="12" :xs="24">
                    <el-form-item label="计划完成时间">
                        <el-date-picker v-model="form.planFinishTime" type="datetime" :clearable="false" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择计划完成时间"></el-date-picker>
                    </el-form-item>
                </el-col>
                <el-col :md="12" :xs="24">
                    <el-form-item label="实际开始时间">
                        <el-date-picker v-model="form.actualStartTime" type="datetime" :clearable="false" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择实际开始时间"></el-date-picker>
                    </el-form-item>
                </el-col>
                <el-col :md="12" :xs="24">
                    <el-form-item label="实际完成时间">
                        <el-date-picker v-model="form.actualFinishTime" type="datetime" :clearable="false" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择实际完成时间"></el-date-picker>
                    </el-form-item>
                </el-col>
                <el-col :xs="24">
                    <el-form-item label="可选事项">
                        <el-select v-model="form.todoIdList" filterable clearable multiple collapse-tags collapse-tags-tooltip :max-collapse-tags="2" placeholder="请选择可选事项">
                            <el-option v-for="item in filterTodoL" :key="item.id" :label="item.content" :value="item.id"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :xs="24">
                    <el-form-item label="描述内容">
                        <el-input v-model="form.remark" type="textarea" :rows="4" placeholder="请输入描述内容"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>

        <template #footer>
            <el-button :loading="isSaving" type="primary" auto-insert-space @click="submit">保存</el-button>
            <el-button auto-insert-space @click="visible = false">取消</el-button>
        </template>
    </el-dialog>
</template>

<script setup>
import XEUtils from "xe-utils";
import API from "@/api";
import TOOL from "@/utils/tool";
import { nodeStatusDic } from "@/views/milestone/main";

const $emit = defineEmits(["success", "closed"]);
const props = defineProps({
    projectId: { type: Number, default: TOOL.data.get("PROJECT_ID") }
});

const visible = ref(false);
const isSaving = ref(false);

const mode = ref("add");
const titleMap = reactive({
    add: "新增",
    add_child: "新增子节点",
    edit: "修改"
})

const form = ref({
    id: null,
    projectId: null,
    parentId: "0",
    nodeName: null,
    nodeSeq: null,
    nodeStatus: null,
    planStartTime: null,
    planFinishTime: null,
    actualStartTime: null,
    actualFinishTime: null,
    todoIdList: [],
    remark: null
})
const rules = reactive({
    projectId: [{ required: true, message: "请选择所属项目" }],
    parentId: [{ required: true, message: "请选择上级节点" }],
    nodeName: [{ required: true, message: "请输入节点名称" }],
    nodeSeq: [{ required: true, message: "请输入节点排序" }],
    nodeStatus: [{ required: true, message: "请选择节点状态" }]
})

const treeSelectProps = reactive({
    popperClass: "vxe-table-slot--popper",
    data: [{ id: "0", nodeName: "根目录" }],
    filterable: true,
    checkStrictly: true,
    placeholder: "请选择上级节点",
    props: { label: "nodeName", value: "id" }
})

const todoTasks = ref([]);
const filterTodoL = computed(() => XEUtils.filter(todoTasks.value, item => item.planId == "-" || item.planId == form.value.id));
const getTreeData = async projectId => {
    const planRes = await API.milestone.plan.all({ orderBy: "nodeSeq_asc", projectId });
    treeSelectProps.data = XEUtils.toArrayTree([{ id: "0", nodeName: "根目录" }, ...planRes], { parentKey: "parentId", key: "id" });
    
    const taskRes = await API.milestone.matters.all({ orderBy: "sortNum_asc", projectId });
    todoTasks.value = taskRes;
}

watch(() => form.value.projectId, val => val && getTreeData(val));
const open = data => {
    visible.value = true;
    form.value.projectId = !XEUtils.isEmpty(data) ? data.projectId : props.projectId;

    if (!XEUtils.isEmpty(data)) {
        mode.value = "add_child";
        form.value.parentId = data.id;
    }
}

const setData = data => {
    open();
    mode.value = "edit";
    XEUtils.objectEach(form.value, (_, key) => XEUtils.set(form.value, key, XEUtils.get(data, key)));
}

const formRef = ref();
const submit = () => {
    formRef.value.validate(valid => {
        if (valid) {
            isSaving.value = true;
            API.milestone.plan[XEUtils.first(mode.value.split("_"))](form.value).then(() => {
                isSaving.value = false;
                ElMessage.success("操作成功");
                visible.value = false;
                $emit("success", mode.value);
            }).catch(() => isSaving.value = false);
        } else {
            return false;
        }
    });
}

defineExpose({
    open,
    setData
})
</script>

<style scoped>
.el-form {
    padding-right: calc(var(--el-dialog-padding-primary) + var(--el-message-close-size, 16px));
}
.el-form-item .el-input-number {width: 100%;}
.el-form-item .el-input-number :deep(.el-input__prefix) {margin-right: 8px;}
.el-form-item .el-input-number :deep(.el-input__inner) {text-align: unset;}

.el-form-item .el-select :deep(.el-select__selection) .el-select__selected-item .el-tag{max-width: 204px !important;}
</style>