<template>
    <div style="height: 100%">
        <hc-page-split :options="splitOptions">
            <template #left>
                <hc-card>
                    <div style="height: 100%">
                        <hc-tab-card
                            :tabs="tabsData"
                            :tab-key="tabsKey"
                            @change="tabsChange"
                        >
                            <div
                                style="
                                    display: flex;
                                    flex-direction: column;
                                    background: white;
                                    height: 100%;
                                "
                            >
                                <div style="flex-shrink: 0">
                                    <hc-search-input
                                        v-model="queryValue"
                                        @search="searchTreeClick"
                                    />
                                </div>
                                <div
                                    style="
                                        position: relative;
                                        flex: 1;
                                        flex-basis: auto;
                                    "
                                >
                                    <hc-body scrollbar>
                                        <hc-lazy-tree
                                            v-if="isTreeMode"
                                            :h-props="treeProps"
                                            @load="treeLoadNode"
                                            tree-key="id"
                                            :menus="treeMenuDatas"
                                            @node-tap="treeNodeTap"
                                            @menu-tap="treeMenuClick"
                                            :autoExpandKeys="autoExpandKeys"
                                        />
                                    </hc-body>
                                </div>
                            </div>
                        </hc-tab-card>
                    </div>
                </hc-card>
            </template>
            <hc-card>
                <rightConfig></rightConfig>
            </hc-card>
        </hc-page-split>

        <!-- 新增/修改 -->
        <hc-dialog
            v-model="isAddEditShow"
            widths="24rem"
            is-footer-center
            :title="formModel.id ? '修改' : '新增'"
            @close="addEditClose"
        >
            <el-form
                ref="formRef"
                :model="formModel"
                :rules="formRules"
                label-position="top"
                label-width="auto"
            >
                <el-form-item label="节点名称：" prop="nodeName">
                    <el-input
                        v-model="formModel.nodeName"
                        clearable
                        placeholder="请输入节点名称"
                    />
                </el-form-item>

                <el-form-item label="岗位类型" prop="postType">
                    <el-select
                        v-model="formModel.postType"
                        filterable
                        clearable
                        block
                        placeholder="请选择岗位类型"
                    >
                        <el-option
                            v-for="item in jobTypeList"
                            :key="item.id"
                            :label="item.title"
                            :value="item.id"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="节点类型:" prop="nodeType">
                    <el-select
                        v-model="formModel.nodeType"
                        filterable
                        clearable
                        block
                        placeholder="请选择节点类型"
                    >
                        <el-option
                            v-for="item in nodeTypeList"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="工程类型" prop="projectType">
                    <el-select
                        v-model="formModel.projectType"
                        placeholder="工程类型"
                    >
                        <el-option
                            v-for="item in projectTypeList"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        ></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item
                    label="储存类型"
                    prop="storageType"
                    v-if="formModel.nodeType == 1"
                >
                    <el-select
                        v-model="formModel.storageType"
                        placeholder="请选择"
                    >
                        <el-option
                            v-for="item in storageTypeList"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <template v-if="formModel.nodeType == 2">
                    <el-form-item label="是否存储节点" prop="isStorageNode">
                        <el-select v-model="formModel.isStorageNode">
                            <el-option
                                v-for="item in storageNodeList"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            ></el-option>
                        </el-select>
                    </el-form-item>
                    <template v-if="formModel.isStorageNode == 1">
                        <el-form-item label="储存类型" prop="storageType">
                            <el-select
                                v-model="formModel.storageType"
                                placeholder="请选择"
                            >
                                <el-option
                                    v-for="item in storageTypeList"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                ></el-option>
                            </el-select>
                        </el-form-item>

                        <el-form-item
                            label="是否接口节点"
                            prop="isInterfaceNode"
                        >
                            <el-select v-model="formModel.isInterfaceNode">
                                <el-option
                                    v-for="item in interfaceNodeList"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                        <template v-if="formModel.isInterfaceNode == 1">
                            <el-form-item label="选择接口类型">
                                <el-select v-model="formModel.interfaceType">
                                    <el-option
                                        v-for="item in interfaceTypeList"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                    ></el-option>
                                </el-select>
                            </el-form-item>
                        </template>
                    </template>
                </template>
                <!-- 数字化文件上传 -->
                <template v-if="formModel.nodeType == 1">
                    <el-form-item label="关联类型" prop="associationType">
                        <el-select
                            v-model="formModel.associationType"
                            placeholder="请选择"
                        >
                            <el-option
                                v-for="item in associationTypeList"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            ></el-option>
                        </el-select>
                    </el-form-item>
                    <template v-if="formModel.associationType == 1">
                        <el-form-item label="内业资料类型" prop="majorDataType">
                            <el-checkbox-group
                                v-model="formModel.majorDataType"
                            >
                                <el-checkbox
                                    v-for="item in majorDataTypeList"
                                    :label="item.label"
                                    :value="item.value"
                                ></el-checkbox>
                            </el-checkbox-group>
                        </el-form-item>
                        <el-form-item label="显示层级" prop="displayHierarchy">
                            <el-select
                                v-model="formModel.displayHierarchy"
                                placeholder="请选择"
                            >
                                <el-option
                                    v-for="item in displayHierarchyList"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </template>
                    <template v-if="formModel.associationType == 2">
                        <el-form-item label="文件类型" prop="expDataType">
                            <el-checkbox-group v-model="formModel.expDataType">
                                <el-checkbox
                                    v-for="item in fileTypeList"
                                    :key="item.value"
                                    :label="item.label"
                                ></el-checkbox>
                            </el-checkbox-group>
                        </el-form-item>
                    </template>
                </template>
            </el-form>
            <template #footer>
                <el-button hc-btn @click="addEditClose">取消</el-button>
                <el-button
                    hc-btn
                    type="primary"
                    :loading="addEditLoading"
                    @click="addEditSubmit"
                    >提交</el-button
                >
            </template>
        </hc-dialog>
        <!-- 树节点调整排序 -->
        <hc-dialog
            v-model="isSortingShow"
            title="调整排序"
            widths="600px"
            is-table
            @close="sortingClose"
        >
            <hc-table
                ref="tableSortingRef"
                :column="tableSortingColumn"
                :datas="tableSortingData"
                is-row-drop
                is-sort
                quick-sort
                @row-drop="sortingRowDropTap"
                @row-sort="sortingRowSortTap"
            />
            <template #footer>
                <el-button hc-btn @click="sortingClose">取消</el-button>
                <el-button
                    hc-btn
                    type="primary"
                    :disabled="tableSortingData.length <= 0"
                    :loading="sortingLoading"
                    @click="sortingSubmit"
                    >提交</el-button
                >
            </template>
        </hc-dialog>
    </div>
</template>

<script setup>
import { onMounted, ref, nextTick } from "vue";
import mainApi from "~api/desk/archive-tree";
import rightConfig from "./wbs/archieveComponent/rightConfig.vue";
import {
    getArrValue,
    isNullES,
    formValidate,
    getObjValue,
    arrToId,
} from "js-fast-way";
import { getToken } from "~src/api/auth";
import { getDictionaryData, getDictionaryName } from "~src/utils/tools";
import roleApi from "~api/authority/role";
import { getStoreValue, setStoreValue } from "~uti/storage";
import { HcDelMsg } from "hc-vue3-ui";
onMounted(() => {
    autoExpandKeys.value = getStoreValue("autoExpandKeys") || [];
    getJobList();
    getDisplayHierarchyList();
    getMajorDataTypeList();
});
//页面分割
const splitOptions = { sizes: [50, 50], snapOffset: 0, minSize: [300, 300] };

const tabsKey = ref("1");
const tabsData = ref([
    { key: "1", name: "竣工档案目录" },
    { key: "2", name: "文书档案目录" },
]);
const tabsChange = (item) => {
    console.log(item);
};
//获取相关下拉框数据
const jobTypeList = ref([]);
const getJobList = async () => {
    const { code, data } = await roleApi.roleTree();
    if (code == 200) {
        jobTypeList.value = getArrValue(data);
    }
};

const nodeTypeList = [
    {
        label: "关联电子原生文件",
        value: 1,
    },
    {
        label: "数字化上传文件",
        value: 2,
    },
];

const projectTypeList = [
    {
        label: "水利水电工程",
        value: 1,
    },
    {
        label: "公路工程",
        value: 2,
    },
    {
        label: "全部",
        value: 3,
    },
];

const storageTypeList = [
    {
        label: "普通",
        value: 1,
    },
    {
        label: "竣工图",
        value: 2,
    },
    {
        label: "计量",
        value: 3,
    },
    {
        label: "质检",
        value: 4,
    },
    {
        label: "声像",
        value: 5,
    },
    {
        label: "隐蔽",
        value: 6,
    },
    {
        label: "原材试验",
        value: 7,
    },
    {
        label: "管理文件",
        value: 8,
    },
    {
        label: "变更令",
        value: 9,
    },
];
const storageNodeList = [
    //存储节点枚举
    {
        label: "是",
        value: 1,
    },
    {
        label: "否",
        value: 2,
    },
];
const interfaceNodeList = [
    //存储节点枚举
    {
        label: "是",
        value: 1,
    },
    {
        label: "否",
        value: 2,
    },
];
const interfaceTypeList = [
    //存储节点枚举
    {
        label: "试验接口",
        value: 1,
    },
    {
        label: "计量接口",
        value: 2,
    },
];
const associationTypeList = [
    {
        label: "质检资料",
        value: 1,
    },
    {
        label: "试验资料",
        value: 2,
    },
    {
        label: "影像资料",
        value: 3,
    },
    {
        label: "台账资料",
        value: 4,
    },
    {
        label: "首件资料",
        value: 5,
    },
    {
        label: "日志文件",
        value: 6,
    },
];
const fileTypeList = [
    {
        label: "配合比",
        value: 1,
    },
    {
        label: "原材",
        value: 2,
    },
    {
        label: "汇总",
        value: 3,
    },
    {
        label: "设备",
        value: 4,
    },
    {
        label: "外委(第三方)",
        value: 5,
    },
];

//显示层级
const displayHierarchyList = ref([]);
const getDisplayHierarchyList = async () => {
    displayHierarchyList.value = await getDictionaryData(
        "display_hierarchy",
        true
    );
};
//内页资料类型
const majorDataTypeList = ref([]);
const getMajorDataTypeList = async () => {
    majorDataTypeList.value = await getDictionaryData("major_data_type", true);
};
const queryValue = ref("");

const searchTreeClick = () => {
    console.log(queryValue.value);
};
const treeProps = {
    label: "title",
    children: "children",
    isLeaf: "hasChildren",
};
const autoExpandKeys = ref([]);
const treeMenuDatas = [
    { icon: "add-circle", label: "新增节点", key: "add" },
    { icon: "draft", label: "编辑节点", key: "edit" },
    { icon: "arrow-up-down", label: "排序节点", key: "rank" },
    { icon: "delete-bin", label: "删除节点", key: "del" },
];
const treeLoadNode = async ({ item, level }, resolve) => {
    if (level === 0) {
        let ks = await getLazyTree(0);
        if (ks.length) {
            resolve(ks);
        } else {
            archiveTreeInit();
        }
    } else {
        resolve(await getLazyTree(item.id));
    }
};
//树重加载

const getLazyTree = async (parentId) => {
    const token = getToken;
    const { data, code, msg } = await mainApi.lazyTree({
        parentId,
        token: token,
        projectId: 0,
    });

    if (code == 200 && msg == "操作成功") {
        data.forEach((val) => {
            val.hasChildren = !val.hasChildren;
        });
        return data;
    } else if (code == 200 && msg == "未查询到信息") {
        return [];
    }
};
const archiveTreeInit = async () => {
    const { data, msg, code } = await mainApi.archiveTreeInit();
    if (code == 200 && msg == "操作成功") {
        res.data.forEach((val) => {
            val.hasChildren = !val.hasChildren;
        });
        return data;
    } else if (code == 200 && msg == "未查询到信息") {
        return [];
    }
};
const getArchiveTreeDetail = async (param) => {
    console.log(param);
    const { code, msg, data } = await mainApi.archiveTreeDetail({
        id: param.id,
        projectId: 0,
    });

    if (code == 200) {
        formModel.value = data;
        formModel.value.nodeName = data.fullName; //节点名称

        if (data.expDataType) {
            let arr = data.expDataType.split(",");
            const numberArray = Array.from(arr, Number);
            formModel.value.expDataType = numberArray; //文件类型
        } else {
            formModel.value.expDataType = [];
        }
        if (data.majorDataType) {
            let arr = data.majorDataType.split(",");
            const numberArray = Array.from(arr, Number);
            formModel.value.majorDataType = numberArray;
        } else {
            formModel.value.majorDataType = [];
        }
    }
};
//树节点被点击
const nodeInfo = ref({});
const treeNodeTap = ({ data, keys }) => {
    nodeInfo.value = data;
    setStoreValue("autoExpandKeys", keys);
};
const treeParent = ref({});
//菜单被点击
const treeMenuClick = async ({ key, data, node, keys }) => {
    setStoreValue("autoExpandKeys", keys);
    nodeInfo.value = data;
    if (key === "add") {
        if (data.isStorageNode == 1) {
            window.$message.warning("该节点下不允许新增节点");
            return;
        }
        formModel.value = {};
        formModel.value.postType = data.postType;
        formModel.value.parentId = data.id;
        isAddEditShow.value = true;
    } else if (key === "edit") {
        getArchiveTreeDetail(data);
        treeParent.value = node.parent.data;
        isAddEditShow.value = true;
    } else if (key === "rank") {
        const pid = node.data.id;
        const { data } = await mainApi.getSameGradeNode({ id: pid });
        tableSortingData.value = getArrValue(data);
        isSortingShow.value = true;
    } else if (key === "del") {
        HcDelMsg(async (resolve) => {
            const { code } = await mainApi.remove({ id: data.id });
            resolve(); //关闭弹窗的回调
            if (code !== 200) return;
            window.$message.success("删除成功");
            setTreeMode();
        }).then();
    }
};

//新增、编辑节点
const isAddEditShow = ref(false);
const formRef = ref(null);
const formModel = ref({});
const formRules = {
    nodeName: { required: true, trigger: "blur", message: "请输入节点名称" },
    postType: { required: true, trigger: "blur", message: "请选择岗位类型" },
    nodeType: { required: true, trigger: "blur", message: "请选择节点类型" },
    projectType: { required: true, trigger: "blur", message: "请选择工程类型" },
    storageType: { required: true, trigger: "blur", message: "请选择储存类型" },
    isStorageNode: {
        required: true,
        trigger: "blur",
        message: "请选择是否存储节点",
    },
    isInterfaceNode: {
        required: true,
        trigger: "blur",
        message: "请选择是否接口节点",
    },
    associationType: {
        required: true,
        trigger: "blur",
        message: "请选择关联类型",
    },
    majorDataType: {
        required: true,
        trigger: "blur",
        message: "请选择内页资料类型",
    },
    displayHierarchy: {
        required: true,
        trigger: "blur",
        message: "请选择显示层级",
    },
    expDataType: { required: true, trigger: "blur", message: "请选择文件类型" },
};

//新增、编辑节点提交
const addEditLoading = ref(false);
const addEditSubmit = async () => {
    if (
        treeParent.value.postType &&
        treeParent.value.postType != formModel.value.postType
    ) {
        window.$message.warning("岗位类型必须和父级节点岗位类型一致");
        return;
    }
    //验证表单
    const isForm = await formValidate(formRef.value);
    if (!isForm) return false;
    addEditLoading.value = true;
    //处理表单
    const form = formModel.value;
    if (formModel.value.majorDataType) {
        formModel.value.majorDataType = formModel.value.majorDataType.join(",");
    }
    if (formModel.value.expDataType) {
        formModel.value.expDataType = formModel.value.expDataType.join(",");
    }

    //发起请求
    let res;
    if (isNullES(form.id)) {
        res = await mainApi.archiveTreeSave(form);
    } else {
        res = await mainApi.archiveTreeUpdate(form);
    }
    //处理结果
    const { error, code } = getObjValue(res);
    addEditLoading.value = false;
    if (!error && code === 200) {
        window?.$message?.success("操作成功");
        addEditClose();
        setTreeMode();
    }
};

//关闭 新增、编辑节点
const addEditClose = () => {
    isAddEditShow.value = false;
    formModel.value = {};
};

//树重加载
const isTreeMode = ref(true);

const setTreeMode = () => {
    isTreeMode.value = false;
    nodeInfo.value = {};

    setTimeout(() => {
        isTreeMode.value = true;
    }, 500);
    autoExpandKeys.value = getStoreValue("autoExpandKeys") || [];
};
//排序
const isSortingShow = ref(false);
const tableSortingRef = ref(null);

//排序表
const tableSortingColumn = [{ key: "nodeName", name: "节点名称" }];
const tableSortingData = ref([]);
const tableData = ref([]);
// 行拖拽
const sortingRowDropTap = async (rows) => {
    // 先清空，否则排序会异常
    tableData.value = [];
    await nextTick();
    tableData.value = rows;
};

// 点击排序
const sortingRowSortTap = async (rows) => {
    // 先清空，否则排序会异常
    tableData.value = [];
    await nextTick();
    tableData.value = rows;
};

//排序提交
const sortingLoading = ref(false);
const sortingSubmit = async () => {
    const arr = tableSortingData.value;
    if (arr.length <= 0) {
        window?.$message?.warning("暂无数据");
        return;
    }
    sortingLoading.value = true;

    const ids = arrToId(arr);
    const { error, code } = await mainApi.submitArchiveTreeSort(arr);
    sortingLoading.value = false;
    if (!error && code === 200) {
        window?.$message?.success("操作成功");
        sortingClose();
        setTreeMode();
    }
};

//关闭排序
const sortingClose = () => {
    isSortingShow.value = false;
    tableData.value = [];
};
</script>

<style scoped lang="scss"></style>
