<template>
    <div style="height: 100%">
        <hc-tab-card :tabs="tabsData" :tab-key="tabsKey" @change="tabsChange">
            <div v-if="tabsKey === '1'" style="height: 100%">
                <el-row style="margin-bottom: 15px">
                    <el-button type="primary" plain @click="setClick(1)"
                        >设置为最高并卷层级</el-button
                    >
                    <el-button type="primary" plain @click="setClick(2)"
                        >设置为分类卷并卷</el-button
                    >
                    <el-button type="primary" plain @click="setClick(3)"
                        >设置为独立组卷</el-button
                    >
                </el-row>

                <div style="height: 100%">
                    <hc-card>
                        <div style="height: 100%">
                            <hc-card>
                                <el-select
                                    v-model="publictreeValue"
                                    clearable
                                    placeholder="请选择公有质检化分树"
                                    @change="treeIdChange"
                                    class="w-80"
                                >
                                    <el-option
                                        v-for="item in publictreeOptions"
                                        :key="item.id"
                                        :label="item.wbsName"
                                        :value="item.id"
                                    >
                                    </el-option>
                                </el-select>
                                <el-select
                                    v-model="testtreeValue"
                                    clearable
                                    placeholder="请选择试验化分树"
                                    @change="testTreeIdChange"
                                    class="w-80 ml-2"
                                >
                                    <el-option
                                        v-for="item in testtreeOptions"
                                        :key="item.id"
                                        :label="item.wbsName"
                                        :value="item.id"
                                    >
                                    </el-option>
                                </el-select>
                                <div class="hc-tab-scroll-class-second mt-2">
                                    <el-scrollbar v-loading="treeLoading">
                                        <hc-data-tree
                                            ref="secondTreeRef"
                                            is-load-menu
                                            :h-props="secondTreeProps"
                                            tree-key="id"
                                            :datas="secondTreeData"
                                            show-checkbox
                                            check-strictly
                                            @load-menu="secondTreeMenu"
                                            @menu-tap="secondTreeMenuClick"
                                        >
                                            <template #name="{ data }">
                                                <template
                                                    v-if="
                                                        Number(
                                                            data.archiveAutoGroupSelect
                                                        ) === 1
                                                    "
                                                >
                                                    <div
                                                        v-if="
                                                            Number(
                                                                data.archiveAutoType
                                                            ) === 1
                                                        "
                                                        class="config_type"
                                                    >
                                                        最
                                                    </div>
                                                    <div
                                                        v-if="
                                                            Number(
                                                                data.archiveAutoType
                                                            ) === 2
                                                        "
                                                        class="config_type"
                                                    >
                                                        分
                                                    </div>
                                                    <div
                                                        v-if="
                                                            Number(
                                                                data.archiveAutoType
                                                            ) === 3
                                                        "
                                                        class="config_type"
                                                    >
                                                        独
                                                    </div>
                                                </template>
                                                <span
                                                    class="text-16px font-400"
                                                    >{{ data.title }}</span
                                                >
                                            </template>
                                        </hc-data-tree>
                                    </el-scrollbar>
                                </div>
                            </hc-card>
                        </div>
                    </hc-card>
                </div>
            </div>
            <!-- 工程文件入口配置 -->
            <div v-if="tabsKey === '2'">
                <entryConfig
                    :rightData="rightData"
                    :wbsId="treeSelectId"
                ></entryConfig>
            </div>
        </hc-tab-card>
        <!-- 设置最高层级 -->
        <hc-dialog
            :title="titleName"
            v-model="highVisible"
            @save="setRecordsHandle"
            @close="highVisible = false"
        >
            <el-checkbox-group v-model="checkList" class="wraplabel">
                <div v-for="node in nodesList" :key="node.id">
                    <el-checkbox
                        :label="node.pathName"
                        :value="node.id"
                        style="margin-bottom: 10px"
                    ></el-checkbox>
                </div>
            </el-checkbox-group>
        </hc-dialog>

        <!-- 查看配置 -->
        <hc-dialog v-model="configVisible" title="查看配置">
            <div v-if="configInfo && configInfo.type">
                <div class="mb-2">
                    <span>配置类别：</span>
                    <span v-if="configInfo.type == 1">最高并卷层级</span>
                    <span v-if="configInfo.type == 2">分类并卷</span>
                    <span v-if="configInfo.type == 3">独立组卷</span>
                </div>
                <template v-if="configInfo.type !== 2">
                    <div class="config-allname">
                        {{ configInfo.data.allName }}
                    </div>
                </template>
                <template v-else>
                    <hc-data-tree
                        :datas="configInfo.data"
                        :h-props="{ label: 'nodeName' }"
                        show-checkbox
                        :check-strictly="true"
                        :default-checked-keys="checkedKeys"
                        :autoExpandKeys="checkedKeys"
                        tree-key="id"
                        ref="configtree"
                        @check="configCheckChange"
                    ></hc-data-tree>
                </template>
            </div>
            <div style="text-align: center; font-size: 22px" v-else>
                该节点尚未配置
            </div>

            <template #footer>
                <el-button @click="configVisible = false">取消查看</el-button>
                <el-button
                    v-if="configInfo && configInfo.type == 2"
                    type="primary"
                    @click="changeConfig"
                    >确认修改配置</el-button
                >
            </template>
        </hc-dialog>
    </div>
</template>
<script setup>
import { ref, onMounted } from "vue";
import entryConfig from "../entry-config.vue";
import wbsApi from "~api/desk/wbs";
import mainApi from "~api/project/tree";
import archiveApi from "~api/desk/archive-tree";
import { getArrValue } from "js-fast-way";
import { HcDelMsg } from "hc-vue3-ui";
onMounted(() => {
    getPublictreeoptions();
    getTesttreeOptions();
});
const tabsKey = ref("1");
const tabsData = ref([
    { key: "1", name: "立卷规则" },
    { key: "2", name: "工程文件入口配置" },
]);
const tabsChange = (item) => {
    tabsKey.value = item.key;
    splitOptions.value = {
        sizes: [45, 45],
        snapOffset: 0,
        minSize: [300, 300],
    };
};
const splitOptions = { sizes: [45, 45], snapOffset: 0, minSize: [300, 300] };
//选择公有质检划分树
const publictreeValue = ref("");
const testtreeValue = ref("");
const treeSelectId = ref("");
const treeIdChange = (val) => {
    getSecondTreeData(val);
    getRightData(val);
    treeSelectId.value = val;
    if (testtreeValue.value) {
        testtreeValue.value = "";
    }
};
const testTreeIdChange = (val) => {
    treeSelectId.value = val;
    getSecondTreeData(val);
    getRightData(val);
    if (publictreeValue.value) {
        publictreeValue.value = "";
    }
};
const publictreeOptions = ref([]);
const testtreeOptions = ref([]);
const getPublictreeoptions = async () => {
    const { code, data } = await wbsApi.getWbsList(1);
    if (code == 200) {
        publictreeOptions.value = getArrValue(data);
    }
};
const getTesttreeOptions = async () => {
    const { code, data } = await wbsApi.getWbsList(2);
    if (code == 200) {
        testtreeOptions.value = getArrValue(data);
    }
};
//立卷规则树
const secondTreeRef = ref(null);

const secondTreeData = ref([]);
const secondTreeProps = {
    label: "title",
};

//立卷规则树右键菜单
const secondTreeMenu = (_, resolve) => {
    resolve([
        { icon: "eye", label: "查看配置", key: "rank" },
        { icon: "delete-bin", label: "删除", key: "del" },
    ]);
};
//立卷规则树
const treeLoading = ref(false);
const getSecondTreeData = async (wbsId) => {
    treeLoading.value = true;
    const { data } = await mainApi.allTree({
        projectId: 0,
        wbsId,
    });
    treeLoading.value = false;
    secondTreeData.value = getArrValue(data);
};
const secondTreeMenuClick = async ({ key, data, node }) => {
    if (key === "rank") {
        configInfo.value = null;
        const {
            data: res,
            code,
            msg,
        } = await archiveApi.getArchiveAutoRule({
            nodeId: data.id, //归档树节点的id 或者 挂载wbs节点的ID（具体哪个ID待定）
            iswbsNode: data.iswbsNode, //是否是wbs节点
            projectId: 0, //   系统级为0  项目级为项目id
            wbsNode2ArchiveTreeNodeId: data.wbsNode2ArchiveTreeNodeId, // 这个树节点里面有（iswbsNode为true需传）
            wbsId: treeSelectId.value, // 这个就是一开始上面选择划分树的id（iswbsNode为true需传）
        });
        console.log(res, "res");

        if (code == 200 && msg == "操作成功") {
            if (res.type) {
                configInfo.value = res;
            } else if (res.archiveAutoType) {
                configInfo.value = {
                    type: 2,
                    data: res.tree,
                };
                checkedKeys.value = res?.selectNodeIds.split(",");
            } else {
                configInfo.value = {};
            }
            configVisible.value = true;
        }
    } else if (key === "del") {
        HcDelMsg(async (resolve) => {
            const { code } = await archiveApi.removeArchiveAutoRule({
                nodeId: data.id,
                iswbsNode: data.iswbsNode, //是否是wbs节点   flase 不是 true 是 （先false,具体怎么区分后面再看）
                projectId: 0, //   系统级为0  项目级为项目id
            });
            resolve(); //关闭弹窗的回调
            if (code !== 200) return;
            window.$message.success("删除成功");
            getSecondTreeData(treeSelectId.value);
        }).then();
    }
};
const titleName = ref("");
const archiveAutoType = ref(1);
const setName = (type) => {
    switch (type) {
        case 1:
            archiveAutoType.value = 1;
            titleName.value = "设置最高并卷层级";
            break;
        case 2:
            archiveAutoType.value = 2;
            titleName.value = "设置分类并卷层级";
            break;
        case 3:
            archiveAutoType.value = 3;
            titleName.value = "设置单独并卷层级";
            break;
    }
};
const highVisible = ref(false);
const checkList = ref([]);
const nodesList = ref([]);

//设置为最高并卷层级

const setClick = (type) => {
    if (!publictreeValue.value && !testtreeValue.value) {
        window.$message({
            message: "请先在下拉框选择树，在勾选树节点，再进行设置",
            type: "warning",
        });
        return false;
    }
    const treeRef = secondTreeRef.value?.getRef(); //树的原始ref
    const nodes = treeRef.getCheckedNodes(); //获取选中的节点
    console.log(nodes, "nodes");

    if (nodes.length < 1) {
        window.$message({
            message: "请先勾选节点，再进行设置",
            type: "warning",
        });
        return false;
    }
    let ids = [];
    nodes.forEach((element) => {
        element.pathName = getTreeNodePath(element, "secondTreeRef");
        ids.push(element.id);
    });
    console.log(nodes, "nodes");
    checkList.value = ids;
    nodesList.value = nodes;
    setName(type);
    highVisible.value = true;
};
//获取树节点名字路径
const getTreeNodePath = (node, refName) => {
    let nodeInfo = secondTreeRef.value.treeRef.getNode(node.id);
    let pathArr = [];
    while (nodeInfo.parent) {
        pathArr.push(nodeInfo.data.title);
        nodeInfo = nodeInfo.parent;
    }
    return pathArr.reverse().join("/");
};

const setRecordsHandle = async () => {
    const { code, msg } = await archiveApi.saveArchiveAutoRule({
        archiveAutoType: archiveAutoType.value, //最高1  分类2  独立3
        selectNodeIds: checkList.value.join(","), //鼠标选择的节点ID（只要鼠标选择的节点，选择节点的下级子节点那种不要），逗号拼接
        iswbsNode: nodesList.value[0].iswbsNode, //是否是wbs节点
        projectId: 0, //   系统级为0  项目级为项目id
    });

    if (code == 200 && msg == "操作成功") {
        window.$message({
            type: "success",
            message: "设置成功",
        });

        if (publictreeValue.value) {
            treeIdChange(treeSelectId.value);
        } else {
            testTreeIdChange(treeSelectId.value);
        }

        highVisible.value = false;
    }
};

//查看配置
const configtree = ref(null);
const configVisible = ref(false);
const configInfo = ref({});
const checkedKeys = ref([]);
const configCheckChange = (_, { checkedNodes }) => {
    let array = checkedNodes;
    for (let index = 1; index < array.length; index++) {
        const element = array[index];
        if (element.iswbsNode !== array[0].iswbsNode) {
            //取消勾选
            configtree.value.treeRef.setChecked(data.id, false, false);
            window.$message({
                message: "非wbs节点不能和wbs节点一起设置规则",
                type: "warning",
            });
            return;
        }
    }
};
const changeConfig = async () => {
    let keys = configtree.value.treeRef.getCheckedKeys();
    let nodes = configtree.value.treeRef.getCheckedNodes();
    console.log(nodes);
    const { code, msg } = await archiveApi.updateArchiveAutoRule({
        archiveAutoType: 2, //最高1  分类2  独立3
        archiveAutoGroupId: configInfo.value.data.archiveAutoGroupId,
        selectNodeIds: keys.join(","), //鼠标选择的节点ID（只要鼠标选择的节点，选择节点的下级子节点那种不要），逗号拼接
        iswbsNode: nodes[0].iswbsNode, //是否是wbs节点
        projectId: 0, //   系统级为0  项目级为项目id
    });

    if (code == 200) {
        window.$message({
            type: "success",
            message: msg,
        });
        configVisible.value = false;
    }
};

//工程文件入口配置
const rightData = ref([]);
const getRightData = async (id) => {
    const { data, code } = await archiveApi.archiveTreetree({
        projectId: 0,
        wbsId: id,
    });
    if (code == 200) {
        rightData.value = getArrValue(data);
        console.log(rightData.value, " rightData.value");
    }
};
</script>

<style scoped lang="scss">
.hc-tab-scroll-class-second {
    position: relative;
    height: calc(100% - 42px);
}
.hc-tab-scroll-class-second :deep(.hc-tree-node .data-custom-tree-node .label) {
    display: flex;
}
.hc-tab-scroll-class-second :deep(.config_type) {
    position: relative;
    height: 18px;
    width: 18px;
    font-size: 14px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #fb5c5c;
    color: white;
    border-radius: 3px;
    margin-right: 5px;
}
</style>
