<template>
    <hc-drawer
        v-model="isShow"
        to-id="hc-main-box"
        is-close
        @close="drawerClose"
    >
        <hc-body split :options="{ sizes: [14, 96] }">
            <template #left>
                <hc-card scrollbar>
                    <h3 class="mb-2">引用元素表</h3>
                    <ElTree
                        :load="treeLoadNode"
                        :props="treeProps"
                        accordion
                        highlight-current
                        lazy
                        @node-click="treeNodeTap"
                        v-if="isShowTree"
                    />
                </hc-card>
            </template>
            <hc-card>
                <template #header>
                    <div class="w-400px">
                        <hc-search-input
                            v-model="searchForm.titleName"
                            @search="searchClick"
                        />
                    </div>
                </template>
                <template #extra>
                    <el-button hc-btn type="primary" @click="quteEleTableClick"
                        >引用元素表单库</el-button
                    >
                    <el-button
                        hc-btn
                        type="danger"
                        @click="batchDel"
                        :loading="batchDelLoad"
                        >删除元素表</el-button
                    >
                </template>
                <hc-table
                    :column="tableColumn"
                    :datas="tableData"
                    :loading="tableLoading"
                    :index-style="{ width: 60 }"
                    is-check
                    :check-style="{ width: 29 }"
                    @selection-change="tableCheckChange"
                >
                    <template #action="{ row }">
                        <el-link type="primary" @click="linkExcelClick(row)"
                            >关联清表</el-link
                        >
                        <el-link
                            v-loading="editElementLoading"
                            type="primary"
                            @click="editElement(row)"
                            :disabled="row.excelIds == -1"
                            >编辑元素</el-link
                        >
                        <el-link
                            v-loading="adjustExcelLoading"
                            type="primary"
                            @click="adjustExcelClick(row)"
                            :disabled="row.excelIds == -1"
                            >调整表单</el-link
                        >
                        <el-link type="primary" @click="rowFormulaClick(row)"
                            >编辑公式</el-link
                        >
                        <el-link type="primary" @click="assignWbs(row)"
                            >分配WBS</el-link
                        >
                    </template>
                </hc-table>
                <template #action>
                    <hc-pages :pages="searchForm" @change="pageChange" />
                </template>
            </hc-card>
        </hc-body>
        <!-- 引用元素表 -->
        <quteElePage
            v-model="quteEleShow"
            :projectId="projectId"
            @close="quteEleClose"
        ></quteElePage>
        <!-- 关联清表 -->
        <HcAssociationList
            v-model="isAssociationShow"
            :info="associationInfo"
            :type="2"
        />
        <!-- 编辑元素 -->
        <HcEditElement
            v-model="isEditElementShow"
            :info="editElementInfo"
            :data="editElementData"
            :type="2"
            @to-page="editElementToPage"
        />
        <!-- 调整表单 -->
        <HcAdjustExcel
            v-model="isAdjustExcelShow"
            :info="adjustExcelInfo"
            :type="2"
        />
        <!-- 分配WBS -->
        <allocateWbs
            v-model="isAllocateShow"
            :wbsType="wbsType"
            :projectId="projectId"
            :data="allocateWbsInfo"
        ></allocateWbs>
    </hc-drawer>
</template>

<script setup>
import { ref, watch, nextTick } from "vue";
import { HcDelMsg } from "hc-vue3-ui";
import { getArrValue, arrToId, isNullES, deepClone } from "js-fast-way";
import privateApi from "~api/wbs/private";
import excelApi from "~api/exctab/exceltab";
import quteElePage from "./quteElePage.vue";
import HcAssociationList from "../association-list.vue";
import HcEditElement from "../edit-element.vue";
import HcAdjustExcel from "../adjust-excel.vue";
import allocateWbs from "./allocateWbs.vue";
//事件
const emit = defineEmits(["close"]);

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

//监听显示
watch(isShow, (val) => {
    if (val) getDataApi();
});
const props = defineProps({
    projectId: {
        type: String,
        default: "",
    },
    wbsType: {
        type: [String, Number],
        default: "",
    },
    wbsId: {
        type: [String, Number],
        default: "",
    },
});
const projectId = ref(props.projectId);
const wbsId = ref(props.wbsId);
const wbsType = ref(props.wbsType);
//监听数据
watch(
    () => [props.projectId, props.wbsId, props.wbsType],
    ([pid, wid, wtype]) => {
        projectId.value = pid;
        wbsId.value = wid;
        wbsType.value = wtype;
    },
    { deep: true }
);
//处理相关数据
const getDataApi = () => {};

//获取数据
const tabTypeLazyTree = async (parentId = "12345678910") => {
    //发起请求
    const { data } = await privateApi.tabTypeLazyTree({
        parentId,
        current: 1,
        size: 1000,
        projectId: projectId.value,
    });
    const records = getArrValue(data?.records);
    records.forEach((item) => {
        item.isLeaf = !item.hasChildren;
    });
    return { data: records, total: data?.total };
};
const isShowTree = ref(true);
const refreshTree = () => {
    isShowTree.value = false;

    setTimeout(() => {
        isShowTree.value = true;
    }, 1000);
};
const treeLoadNode = async (node, resolve) => {
    if (node.level === 0) {
        const resData = await tabTypeLazyTree();
        resolve(resData?.data);
    } else {
        const resData = await tabTypeLazyTree(
            node?.data?.primaryKeyId,
            "",
            false,
            {
                current: 1,
                size: 2000,
                projectId: projectId.value,
            }
        );
        resolve(resData?.data);
    }
};

//树节点被点击
const nodeInfo = ref({});
const treeProps = {
    label: "title",
    isLeaf: (item) => {
        return !item.hasChildren;
    },
};
const treeNodeTap = (data, node) => {
    nodeInfo.value = data;
    searchForm.value.parentId = data.id;

    if (node?.level === 1) {
        searchClick();
    } else if (node?.level === 2) {
        searchForm.value.total = 1;
        tableData.value = [data];
    }
};

//搜索表单
const searchForm = ref({ current: 1, size: 30, total: 0 });

//搜索
const searchClick = () => {
    const { parentId } = searchForm.value;
    if (isNullES(parentId)) {
        window?.$message?.warning("请先在左侧点击一个节点");
        return;
    }
    searchForm.value.current = 1;
    getTableData();
};

//分页
const pageChange = ({ current, size }) => {
    const { parentId } = searchForm.value;
    if (isNullES(parentId)) {
        window?.$message?.warning("请先在左侧点击一个节点");
        return;
    }
    searchForm.value.current = current;
    searchForm.value.size = size;
    getTableData();
};

//表格数据
const tableData = ref([]);
const tableColumn = ref([
    { key: "title", name: "名称" },
    { key: "elementTotal", name: "总量", width: 80, align: "center" },
    { key: "tabOwner", name: "所属方", width: 140, align: "center" },
    { key: "fillRate", name: "填报率", width: 80, align: "center" },
    { key: "action", name: "操作", width: 220, align: "center" },
]);

//获取表格数据
const tableLoading = ref(false);
const getTableData = async () => {
    tableData.value = [];
    tableLoading.value = true;
    const { data } = await privateApi.tabTypeLazyTree({
        ...searchForm.value,
        total: null,
        projectId: projectId.value,
    });
    tableLoading.value = false;
    tableData.value = getArrValue(data?.records);
    searchForm.value.total = data?.total || 0;
};

//表格被选择
const tableCheckKeys = ref([]);
const tableCheckChange = (rows) => {
    tableCheckKeys.value = rows;
};

//关联清表

const isAssociationShow = ref(false);
const associationInfo = ref({});

const linkExcelClick = async (item) => {
    associationInfo.value = item;
    await nextTick();
    isAssociationShow.value = true;
};

//公式配置
const rowFormulaClick = (row) => {};
//分配WBS
const isAllocateShow = ref(false);
const allocateWbsInfo = ref({});
const assignWbs = (row) => {
    allocateWbsInfo.value = row;
    isAllocateShow.value = true;
};

//编辑元素
const isEditElementShow = ref(false);
const editElementInfo = ref({});
const editElementData = ref({});
const editElementLoading = ref(false);
const editElement = async (row) => {
    editElementLoading.value = true;
    const { code, data } = await excelApi.getExcelHtml({ pkeyId: row.id });
    if (code !== 200 || isNullES(data)) {
        editElementLoading.value = false;
        window?.$message.warning("表单异常，请联系管理员");
        return;
    }
    editElementLoading.value = false;
    editElementInfo.value = row;
    editElementData.value = {
        pid: projectId.value,
        wbsid: wbsId.value,
    };
    await nextTick();
    isEditElementShow.value = true;
};
//编辑元素里的跳转页面
const editElementToPage = async (name) => {
    const row = deepClone(editElementInfo.value);
    //表单调整
    if (name === "adjustment") {
        adjustExcelInfo.value = deepClone(row);
        await nextTick();
        isAdjustExcelShow.value = true;
    }
    //公式配置
    if (name === "formula") {
        console.log("还没做");
    }
};

//调整表单
const isAdjustExcelShow = ref(false);
const adjustExcelLoading = ref(false);
const adjustExcelInfo = ref({});
const adjustExcelClick = async (row) => {
    const { primaryKeyId, excelIds } = row;
    if (isNullES(primaryKeyId) || isNullES(excelIds)) {
        window?.$message.warning("表单值异常，请联系管理员");
        return;
    }
    adjustExcelLoading.value = true;
    const { code, data } = await excelApi.getExcelHtml({
        pkeyId: primaryKeyId,
    });
    if (code !== 200 || isNullES(data)) {
        adjustExcelLoading.value = false;
        window?.$message.warning("表单异常，请联系管理员");
        return;
    }
    adjustExcelInfo.value = deepClone(row);
    adjustExcelLoading.value = false;
    isAdjustExcelShow.value = true;
};
//关闭抽屉
const drawerClose = () => {
    isShow.value = false;
    emit("close");
};
//删除元素表
const batchDelLoad = ref(false);
const batchDel = async () => {
    if (tableCheckKeys.value.length == 0) {
        window?.$message?.warning("请先选择一个元素");
        return;
    }
    HcDelMsg(async (resolve) => {
        //发起请求
        const ids = arrToId(tableCheckKeys.value);
        const { isRes } = await privateApi.delAprojectTab({
            projectId: projectId.value,
            primaryKeyIds: ids,
        });
        resolve(); //关闭弹窗
        if (!isRes) return;
        window.$message.success("删除成功");
        getTableData().then();
    });
};

//引用元素表单库
const quteEleShow = ref(false);
const quteEleTableClick = () => {
    quteEleShow.value = true;
};
const quteEleClose = () => {
    quteEleShow.value = false;
    getTableData().then();
    refreshTree();
};
</script>
