<template>
    <hc-dialog
        v-model="isShow"
        title="分配WBS"
        widths="56rem"
        isTable
        @close="dialogClose"
        @save="submitClick"
        :loading="submitLoading"
    >
        <div v-loading="treeLoading">
            <el-scrollbar>
                <el-tree
                    :props="treeProps"
                    :load="treeLoad"
                    lazy
                    accordion
                    highlight-current
                    @node-click="treeClick"
                    :default-checked-keys="checkedLinkNodesKeys"
                >
                    <template #default="{ node, data }">
                        <span
                            class="custom-tree-node"
                            style="justify-content: flex-start"
                        >
                            <span>
                                <el-checkbox
                                    v-model="data.checked"
                                    v-if="!data.hasChildren"
                                    @change="handleCheckChange($event, data)"
                                ></el-checkbox
                            ></span>
                            {{ node.label }}
                        </span>
                    </template>
                </el-tree>
            </el-scrollbar>
        </div>
    </hc-dialog>
</template>
<script setup>
import { ref, watch, nextTick } from "vue";
import mainApi from "~api/desk/wbs";
import privateApi from "~api/wbs/private";
import { arrToId, getArrValue, getObjValue } from "js-fast-way";
import { useAppStore } from "~src/store";

//事件
const emit = defineEmits(["close"]);
//双向绑定
// eslint-disable-next-line no-undef
const isShow = defineModel("modelValue", {
    default: false,
});
const props = defineProps({
    projectId: {
        type: String,
        default: "",
    },
    wbsType: {
        type: [String, Number],
        default: "",
    },
    wbsId: {
        type: [String, Number],
        default: "",
    },
    data: {
        type: Object,
        default: () => ({}),
    },
    type: {
        type: [String, Number],
        default: "0", //私有wbs为1，独立表单库为0
    },
});
const store = useAppStore();
const userInfo = ref(store.getUserInfo);
watch(
    () => store.getUserInfo,
    (info) => {
        userInfo.value = info;
    },
    { immediate: true, deep: true }
);
const projectId = ref(props.projectId);
const wbsId = ref(props.wbsId);
const wbsType = ref(props.wbsType);
const dataInfo = ref(props.data);
const type = ref(props.type);
//监听数据
watch(
    () => [props.projectId, props.wbsId, props.wbsType, props.data, props.type],
    ([pid, wid, wtype, info, tpe]) => {
        projectId.value = pid;
        wbsId.value = wid;
        wbsType.value = wtype;
        dataInfo.value = info;
        type.value = tpe;
    },
    { deep: true }
);
//监听显示
watch(isShow, (val) => {
    selectData.value = [];
    if (val) {
        if (type.value === 1) {
            getLinekNodeTreelistData();
        }
    } else {
        emit("close");
    }
});
//获取关联的节点
const checkedLinkNodesKeys = ref([]);
const getLinekNodeTreelistData = async () => {
    const { data } = await privateApi.LinekNodeTreelist({
        pkeyid: dataInfo.value.pkeyId,
    });
    checkedLinkNodesKeys.value = getArrValue(data);
};
//关闭弹窗
const dialogClose = () => {
    selectData.value = [];
    isShow.value = false;
    emit("close");
};
//树
const treeProps = {
    label: "title",
    isLeaf: (item) => {
        return !item.hasChildren;
    },
};

//懒加载树
const treeLoading = ref(false);
const treeLoad = async (node, resolve) => {
    const { tenant_id } = getObjValue(userInfo.value);
    treeLoading.value = true;
    const parentId = node.level === 0 ? 0 : node.data.id;

    const { data } = await privateApi.getLazytree({
        parentId: parentId,
        wbsId: wbsId.value,
        tenantId: tenant_id,
        projectId: projectId.value,
        wbsType: wbsType.value,
    });
    treeLoading.value = false;
    resolve(getArrValue(data));
};

//树节点被点击

const treeClick = ({ id, type, nodeName }) => {};
const selectData = ref([]);
const handleCheckChange = (isCheck, data) => {
    if (isCheck) {
        selectData.value.push(data);
    } else {
        const index = selectData.value.indexOf(data);
        if (index !== -1) {
            selectData.value.splice(index, 1);
        }
    }
};
const submitLoading = ref(false);
const submitClick = async () => {
    const nodesIdArray = selectData.value.map((obj) => obj.primaryKeyId);
    const commaSeparatedIds = nodesIdArray.join(","); // 使用逗号连接数组中的所有元素

    if (type.value === 1) {
        submitLoading.value = true;
        const { code, error, msg } = await privateApi.LinekNodeTree({
            nodeids: commaSeparatedIds,
            pkeyid: dataInfo.value.id,
        });
        submitLoading.value = false;
        if (!error && code === 200) {
            window.$message.success(msg);
            dialogClose();
        }
    } else {
        submitLoading.value = true;
        const { code, error, msg } = await privateApi.syncFormToContractNode({
            nodeIds: commaSeparatedIds,
            projectId: projectId.value,
            primaryKeyId: dataInfo.value.id,
        });
        submitLoading.value = false;
        if (!error && code === 200) {
            window.$message.success(msg);
            dialogClose();
        }
    }
};
</script>
