<template>
    <hc-drawer
        v-model="isShow"
        to-id="hc-main-box"
        is-close
        @close="drawerClose"
    >
        <div class="hc-project-wbs-tree flex">
            <div class="header hc-flex">
                <div class="name flex-1">
                    {{ dataInfo.wbsName }}
                </div>
                <div class="hc-flex">
                    <el-button
                        hc-btn
                        type="primary"
                        v-if="curTreeNode && curTreeNode.level == 2"
                        >导入划分</el-button
                    >
                    <el-button
                        hc-btn
                        type="primary"
                        v-if="!isShowInfo"
                        @click="showInfoClick"
                        >元素设置</el-button
                    >
                    <el-button
                        hc-btn
                        type="primary"
                        v-if="isShowInfo"
                        @click="hideInfoClick"
                        >元素公式设置</el-button
                    >

                    <el-button hc-btn type="warning" @click="nodeParamClick"
                        >节点参数设置</el-button
                    >
                </div>
            </div>
            <div class="body">
                <hc-body split>
                    <template #left>
                        <hc-card scrollbar>
                            <template #header>
                                <hc-search-input
                                    v-model="searchTreeName"
                                    @search="searchTreeNameClick"
                                    @clear="searchTreeNameClick"
                                >
                                    <template #prepend>
                                        <el-select
                                            v-model="queryType"
                                            placeholder="类型"
                                            style="width: 75px"
                                        >
                                            <el-option label="节点" value="1" />
                                            <el-option label="表名" value="2" />
                                        </el-select>
                                    </template>
                                </hc-search-input>
                            </template>
                            <hc-lazy-tree
                                v-if="isTreeMode"
                                :root-menu="treeMenuData"
                                :menus="treeMenuDatas"
                                :h-props="treeProps"
                                tree-key="id"
                                @load="treeLoadNode"
                                @node-tap="treeNodeTap"
                                @menu-tap="treeMenuClick"
                                :autoExpandKeys="autoExpandKeys"
                            >
                                <template #nodeName="{ data }">
                                    <span class="text-16px font-400">{{
                                        data.nodeName
                                    }}</span>
                                </template>
                            </hc-lazy-tree>
                            <template v-if="isTreeMode === false">
                                <hc-data-tree
                                    defaultExpandAll
                                    ref="treeRef"
                                    :h-props="treeProps"
                                    tree-key="id"
                                    :datas="treeData"
                                    @node-tap="treeNodeTap"
                                >
                                    <template #name="{ data }">
                                        <span class="text-16px font-400">{{
                                            data.title
                                        }}</span>
                                    </template>
                                </hc-data-tree>
                            </template>
                        </hc-card>
                    </template>
                    <hc-card class="hc-desk-system-unit-temp">
                        <template v-if="!isNullES(nodeInfo.id)">
                            <div class="body-top" v-if="isShowInfo">
                                <hc-card title="节点信息">
                                    <hc-table
                                        :is-index="false"
                                        :column="nodeTableColumn"
                                        :datas="nodeTableData"
                                    >
                                        <template #nodeType="{ row }">{{
                                            getDictionaryName(
                                                majorDatatype,
                                                row.nodeType,
                                                true
                                            )
                                        }}</template>
                                    </hc-table>
                                </hc-card>
                            </div>
                            <div class="body-content">
                                <hc-card title="当前已创建的元素表">
                                    <template #extra>
                                        <el-button
                                            v-if="isShowInfo"
                                            size="small"
                                            type="primary"
                                            @click="createNew"
                                            >创建元素表</el-button
                                        >
                                        <el-button
                                            v-if="isShowInfo"
                                            size="small"
                                            type="warning"
                                            @click="editEleClick"
                                            >编辑元素表单</el-button
                                        >
                                        <el-button
                                            v-if="isShowInfo"
                                            size="small"
                                            type="success"
                                            @click="sortClick"
                                            >排序</el-button
                                        >
                                    </template>
                                    <hc-table
                                        :column="tableColumn"
                                        :datas="tableData"
                                        :loading="tableLoading"
                                        :is-index="false"
                                        :is-current-row="false"
                                    >
                                        <template #tableType="{ row }">{{
                                            getDictionaryName(
                                                tableTypelist,
                                                row.tableType,
                                                true
                                            )
                                        }}</template>
                                        <template #tableOwner="{ row }">{{
                                            getDictionaryName(
                                                ownerTypeList,
                                                row.tableOwner,
                                                true
                                            )
                                        }}</template>
                                        <template #action="{ row, index }">
                                            <el-link
                                                v-if="isShowInfo"
                                                type="warning"
                                                @click="editRowClick(row)"
                                                >编辑</el-link
                                            >
                                            <el-link
                                                v-else
                                                type="warning"
                                                @click="editFormulaClick(row)"
                                                >编辑元素公式</el-link
                                            >
                                            <el-link
                                                type="danger"
                                                @click="rowDelClick(row)"
                                                >删除</el-link
                                            >
                                        </template>
                                    </hc-table>
                                </hc-card>
                            </div>
                        </template>
                        <hc-empty v-else title="请先点击左侧树节点" />
                    </hc-card>
                </hc-body>
            </div>
        </div>

        <!-- 树节点调整排序 -->
        <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>

        <!-- 树节点新增修改 -->
        <TreeNodeEditDialog
            v-model="isAddEditShow"
            :node="formModel"
            :type="Number(wbsType)"
            :wid="dataInfo.id"
            :tree-props="treeProps"
            :node-type="majorDatatype"
            :major-type="majorDataTypeList"
            :title="modalTreeTitle"
            @close="addEditClose"
            @change="treeNodeEditChange"
        />
        <!-- 创建新的元素表 -->
        <createNewExcel
            v-model="isCreateShow"
            @close="createClose"
            :node="nodeDetail"
            :wid="dataInfo.id"
            :tableTypelist="tableTypelist"
            :ownerTypeList="ownerTypeList"
            :title="modalTitle"
            :tableId="tableId"
            :initTableName="initTableName"
            :initTableId="initTableId"
            :eKey="eKey"
        ></createNewExcel>
        <!-- 编辑元素表信息 -->
        <editElePage
            v-model="editEleShow"
            @close="editClose"
            :tableTypelist="tableTypelist"
            :ownerTypeList="ownerTypeList"
            :tab="tableData"
        ></editElePage>

        <!-- 表单调整排序 -->
        <tableSort
            v-model="tableSortShow"
            @close="tableSortShowClose"
            :tab="tableData"
        >
        </tableSort>

        <!-- 编辑元素公式 -->
        <editFormulaDialog
            v-model="editFormulaShow"
            @close="editFormulaClose"
            :tableId="tableId"
        >
        </editFormulaDialog>
    </hc-drawer>
    <!-- 节点参数设置 -->
    <nodeParamDialog
        v-model="nodeParamShow"
        @close="nodeParamClose"
        :nodeId="nodeInfo.id"
        :scopeType="1"
        :nodeInfo="nodeInfo"
    >
    </nodeParamDialog>
</template>

<script setup>
import { nextTick, ref, watch, onMounted } from "vue";
import { HcDelMsg } from "hc-vue3-ui";
import { getDictionaryData, getDictionaryName } from "~src/utils/tools";
import { getStoreValue, setStoreValue } from "~uti/storage";
import tableSort from "./table-sort.vue";
import editFormulaDialog from "./edit-formula-dialog.vue";
import {
    arrToId,
    deepClone,
    getArrValue,
    getObjValue,
    isNullES,
} from "js-fast-way";
import mainApi from "~api/wbs/tree";
import mainWbsApi from "~api/wbs/wbsforelement";

import { useAppStore } from "~src/store";
import TreeNodeEditDialog from "./tree-node-edit.vue";
import createNewExcel from "./create-new-excel.vue";
import editElePage from "./edit-ele.vue";
import nodeParamDialog from "./node-param-dialog.vue";
//缓存
const store = useAppStore();
const userInfo = ref(store.getUserInfo);
watch(
    () => store.getUserInfo,
    (info) => {
        userInfo.value = info;
    },
    { immediate: true, deep: true }
);
const props = defineProps({
    data: {
        type: Object,
        default: () => ({}),
    },
});

const emit = defineEmits(["close"]);

//双向绑定
const isShow = defineModel("modelValue", {
    default: false,
});

//监听数据
const dataInfo = ref(props.data);

const wbsType = ref(props.data.wbsType);
watch(
    () => props.data,
    (data) => {
        dataInfo.value = data;
        wbsType.value = data.wbsType;
    },
    { immediate: true, deep: true }
);

//监听显示
watch(isShow, (val) => {
    if (val) getDataApi();
    getMajorList();

    getOwnerTypelist();
    getTableTypelist(Number(wbsType.value - 1));
});
//渲染完成
onMounted(() => {
    autoExpandKeys.value = getStoreValue("autoExpandKeys") || [];
});

//处理相关数据
const majorDatatype = ref([]);
const getDataApi = async () => {
    isTreeMode.value = true;
    const type = wbsType.value;
    let code = "";
    if (type === 5) {
        code = "lar_node_type"; //征拆
    } else if (type === 2) {
        code = "trial_node_type"; //试验
    } else if (type === 3) {
        code = "meter_node_type"; //计量
    } else {
        {
            code = "wbs_node_type"; //质检
        }
    }
    majorDatatype.value = await getDictionaryData(code, false);
};
//树搜索
const queryType = ref("1");
const searchTreeName = ref("");
const searchTreeNameClick = async () => {
    if (isNullES(searchTreeName.value)) {
        isTreeMode.value = true;
    } else {
        isTreeMode.value = false;
        await getSearchData();
    }
};

const getSearchData = async () => {
    const { id } = getObjValue(dataInfo.value);
    const { data } = await mainApi.getQueryValueByType({
        wbsId: id,
        type: queryType.value,
        queryValue: searchTreeName.value,
        projectId: "",
    });
    treeData.value = data;
};
//节点详情
const nodeDetail = ref({});

const getNodeDetail = async (data1, node) => {
    let parentName = "";
    if (node.parent.data) {
        parentName = node.parent.data.title;
    }

    const { data } = await mainApi.getDetail(data1.id, node);
    nodeInfo.value = data;
    nodeDetail.value = data;
    formModel.value = data;
    formModel.value.parentName = parentName;
    nodeInfo.value.parentName = parentName;
    nodeInfo.value.nodeTypeName = getDictionaryName(
        majorDatatype.value,
        data.nodeType
    );
    defaultCheckedKeys.value = nodeDetail.value.mixRatioTestIds
        ? nodeDetail.value.mixRatioTestIds.split(",")
        : [];
    const res = getObjValue(data);
    nodeTableData.value = [res];
};
//内业资料类型
const majorDataTypeList = ref([]);
const getMajorList = async () => {
    majorDataTypeList.value = await getDictionaryData("major_data_type", false);
};

//树配置
const isTreeMode = ref(false);
const treeProps = {
    label: "title",
    children: "children",
    isLeaf: function (data) {
        if (data.hasChildren && data.isExistForm != 1) {
            return false;
        } else if (data.hasChildren && data.isExistForm == 1) {
            return true;
        } else {
            return true;
        }
    },
};
const treeData = ref([]);
const autoExpandKeys = ref([]);
const defaultCheckedKeys = ref([]);
//懒加载树
const treeLoadNode = async ({ item, level }, resolve) => {
    const { tenant_id } = getObjValue(userInfo.value);
    const parentId = level === 0 ? 0 : item.id;
    const { id } = getObjValue(dataInfo.value);
    const { data } = await mainApi.getLazytree({
        parentId: parentId,
        wbsId: id,
        tenantId: tenant_id,
    });
    resolve(getArrValue(data));
};

//树菜单根节点
const treeMenuData = [
    { icon: "add-circle", label: "新增节点", key: "add" },
    { icon: "draft", label: "编辑节点", key: "edit" },
    { icon: "delete-bin", label: "删除节点", key: "del" },
];
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 treeMenuClick = async ({ key, data, node, keys }) => {
    nodeInfo.value = data;
    autoExpandKeys.value = keys || [];
    setStoreValue("autoExpandKeys", keys);
    if (key === "add") {
        formModel.value = {};
        let parentName = "";
        if (node.parent.data) {
            parentName = node.parent.data.title;
        }
        formModel.value.parentName = parentName;

        await getNodeDetail(data, node);
        formModel.value.parentId = data.id;
        formModel.value.id = "";
        formModel.value.nodeName = "";
        formModel.value.partitionCode = "";
        formModel.value.uniqueCode = "";

        formModel.value.majorDataType = "";
        formModel.value.fullName = "";

        await nextTick();
        if (
            nodeInfo.value.nodeType == 6 ||
            nodeInfo.value.isExistForm == 1 ||
            nodeInfo.value.unitName ||
            nodeInfo.value.className
        ) {
            window.$message({
                type: "warning",
                message: "该节点下无法新增节点",
            });
            return;
        }
        isAddEditShow.value = true;

        modalTreeTitle.value = "新增节点";
    } else if (key === "edit") {
        formModel.value = deepClone(data);
        formModel.value.nodeName = formModel.value.title;

        getNodeDetail(data, node);
        await nextTick();
        isAddEditShow.value = true;
        modalTreeTitle.value = "编辑节点";
    } else if (key === "rank") {
        const pid = node.parent.data.id;
        const { data } = await mainApi.findWbsTreeSameLevel({ parentId: pid });
        tableSortingData.value = getArrValue(data);
        isSortingShow.value = true;
    } else if (key === "del") {
        HcDelMsg(async (resolve) => {
            const { code } = await mainApi.remove(data.id);
            resolve(); //关闭弹窗的回调
            if (code !== 200) return;
            window.$message.success("删除成功");
            setTreeMode();
        }).then();
    }
};

//树节点被点击
const nodeInfo = ref({});
const curTreeNode = ref({});
const treeNodeTap = async ({ data, node, keys }) => {
    curTreeNode.value = node;
    autoExpandKeys.value = keys || [];
    setStoreValue("autoExpandKeys", keys);
    await getNodeDetail(data, node);
    await getTableData();
};

//节点信息
const nodeTableColumn = ref([
    { key: "nodeName", name: "当前节点", align: "center" },
    { key: "nodeType", name: "节点类型", align: "center" },
    { key: "parentName", name: "上级节点", align: "center" },
]);
const nodeTableData = ref([]);
//表格数据
const tableColumn = ref([
    { key: "tableName", name: "表单名称" },
    { key: "elementTotal", name: "元素总量" },
    { key: "fillRate", name: "填报率" },
    { key: "tableType", name: "表单类型" },
    { key: "tableOwner", name: "所属方" },
    { key: "action", name: "操作", align: "center" },
]);
const tableData = ref([{}]);

//获取表格数据
const tableLoading = ref(false);

//获取数据
const getTableData = async () => {
    tableData.value = [];
    const { id } = nodeInfo.value;
    tableLoading.value = true;
    const { data } = await mainApi.selectByNodeTable({
        id,
    });
    tableLoading.value = false;
    const res = getArrValue(data);

    tableData.value = res;
};
//获取表单类型
const tableTypelist = ref([]);
const getTableTypelist = async (type) => {
    //计量管理，征拆划分，实验划分，WBS树管理，日志树管理
    const types = [
        "table_type",
        "trial_table_type",
        "table_type",
        "table_type",
        "table_type",
    ];
    const data = await getDictionaryData(types[type]);
    tableTypelist.value = getArrValue(data);
};
const ownerTypeList = ref([]);
const getOwnerTypelist = async () => {
    const data = await getDictionaryData("owner_type");
    ownerTypeList.value = getArrValue(data);
};

//新增、编辑节点
const isAddEditShow = ref(false);
const modalTreeTitle = ref("新增节点");
const formModel = ref({});

//新增、编辑节点提交

//关闭 新增、编辑节点
const addEditClose = () => {
    isAddEditShow.value = false;
    formModel.value = {};
};
//编辑节点被修改
const treeNodeEditChange = () => {
    isAddEditShow.value = false;
    formModel.value = {};
    console.log("编辑节点被修改");
    setTreeMode();
};
//树重加载
const setTreeMode = () => {
    isTreeMode.value = false;
    nodeInfo.value = {};
    tableData.value = [];
    setTimeout(() => {
        isTreeMode.value = true;
    }, 500);
};

//排序
const isSortingShow = ref(false);
const tableSortingRef = ref(null);

//排序表
const tableSortingColumn = [{ key: "nodeName", name: "节点名称" }];
const tableSortingData = 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.wbsTreeSort(arr);
    sortingLoading.value = false;
    if (!error && code === 200) {
        window?.$message?.success("操作成功");
        sortingClose();
        setTreeMode();
    }
};

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

//关闭抽屉
const drawerClose = () => {
    isShow.value = false;
    isTreeMode.value = false;
    nodeInfo.value = {};
    emit("close");
};
const tableId = ref("");
const initTableName = ref("");
const initTableId = ref("");
const eKey = ref("");
const editRowClick = (row) => {
    isCreateShow.value = true;
    modalTitle.value = row.tableName + "元素编辑";
    tableId.value = row.id;
    initTableName.value = row.initTableName;
    initTableId.value = row.initTableId;
    eKey.value = row.ekey;
};
const rowDelClick = async (row) => {
    console.log("删除");
    HcDelMsg(async (resolve) => {
        const { isRes } = await mainWbsApi.removeTable({ id: row.id });
        resolve(); //关闭弹窗的回调
        if (!isRes) return;
        getTableData();
    });
};

//创建新的元素表
const isCreateShow = ref(false);
const modalTitle = ref("创建新的元素表");
const createClose = () => {
    isCreateShow.value = false;
    getTableData();
};
const createNew = () => {
    const { id } = nodeInfo.value;
    tableId.value = "";
    if (id) {
        isCreateShow.value = true;
        modalTitle.value = "创建新的元素表";
        tableId.value = "";
    } else {
        window.$message.warning("请先选择在哪个节点下创建表");
    }
};
//编辑元素表单
const editEleShow = ref(false);

const editClose = () => {
    editEleShow.value = false;
    getTableData();
};
const editEleClick = () => {
    const { id } = nodeInfo.value;

    if (id) {
        editEleShow.value = true;
    } else {
        window.$message.warning("请先选择编辑哪个节点");
    }
};

// 元素表排序
const tableSortShow = ref(false);
const sortClick = () => {
    tableSortShow.value = true;
};
const tableSortShowClose = () => {
    tableSortShow.value = false;
    getTableData();
};

//按钮切换
const isShowInfo = ref(true);
const hideInfoClick = () => {
    const { id } = nodeInfo.value;
    if (id) {
        isShowInfo.value = false;
    } else {
        window.$message.warning("请先选择左侧节点");
    }
};
const showInfoClick = () => {
    isShowInfo.value = true;
};
//编辑元素公式
const editFormulaShow = ref(false);
const editFormulaClose = () => {
    editFormulaShow.value = false;
};
const editFormulaClick = (row) => {
    const { id } = nodeInfo.value;
    if (id) {
        tableId.value = row.id;
        editFormulaShow.value = true;
    } else {
        window.$message.warning("请先选择左侧节点");
    }
};
//节点参数设置
const nodeParamShow = ref(false);
const nodeParamClose = () => {
    nodeParamShow.value = false;
};
const nodeParamClick = () => {
    const { id } = nodeInfo.value;
    if (id) {
        nodeParamShow.value = true;
    } else {
        window.$message.warning("请先选择左侧节点");
    }
};
</script>

<style lang="scss">
.hc-desk-system-unit-temp .el-card {
    .hc-card-item-box {
        height: auto;
        padding: 10px 14px;
        .hc-card-item-header {
            color: #4a4a4a;
            margin-bottom: 6px;
        }
    }
    .hc-card-item-box + .hc-card-item-box {
        margin-top: 20px;
    }
}
.border-class {
    position: relative;
    height: 300px;
    border: 1px solid #dddfe6;
}
</style>
<style scoped lang="scss">
.hc-project-wbs-tree {
    position: relative;
    background: #ececec;
    border-radius: 4px;
    height: 100%;
    flex-direction: column;
    overflow: hidden;
    .header {
        color: white;
        background: #54565a;
        padding: 10px 14px;
        flex-shrink: 0;
        .name {
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
    }
    .body {
        flex: 1;
        flex-basis: auto;
        position: relative;
    }
}
</style>
<style lang="scss">
.hc-project-wbs-tree .body {
    .el-card.hc-card-box {
        --el-card-padding: 12px;
        --el-card-border-radius: 5px;
    }
    .hc-page-split-content {
        position: relative;
        .body-top {
            position: relative;
            height: 119.5px;
        }
        .body-content {
            position: relative;
            margin-top: 10px;
            height: calc(100% - 129.5px);
        }
    }
}
</style>
