<!-- 导航栏 -->
<template>
    <div class="table-box">
        <div style="padding-bottom: 16px">
            <el-button type="primary" @click="handleAdd"> 添加 </el-button>
        </div>
        <div class="card table-main">
            <SearchForm
                :search="search"
                :reset="reset"
                :formData="dataStore.searchFormData"
                :search-param="dataStore.searchParam"
            />
            <el-table :data="dataStore.tableData" style="width: 100%; margin-bottom: 20px; font-size: 14px" row-key="id" border>
                <el-table-column prop="id" label="id" />
                <el-table-column prop="name" label="导航名称" />
                <el-table-column prop="nav_name" label="导航栏分类" />
                <el-table-column prop="sort" label="导航排序">
                    <template #default="{ row }">
                        <div @click.stop="">
                            <el-input v-model="row.sort" @blur="handleBlur(row)" @input="handleInput(row)" />
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="status" label="显示" :width="100">
                    <template #default="{ row }">
                        {{ row.status === -1 ? "❌" : "✔️" }}
                    </template>
                </el-table-column>
                <el-table-column prop="blank" label="新窗口打开" :width="100">
                    <template #default="{ row }">
                        {{ row.blank === 0 ? "❌" : "✔️" }}
                    </template>
                </el-table-column>
                <el-table-column prop="created_at" label="发布时间" />
                <el-table-column label="操作" :width="160">
                    <template #default="scope">
                        <el-button type="primary" size="small" @click="getItemsRead(scope.row.id)">编辑</el-button>

                        <el-button size="small" type="danger" @click="getItemsDel(scope.row.id)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-drawer
                v-model="dataStore.visible"
                :show-close="true"
                :size="600"
                :close-on-click-modal="false"
                :close-on-press-escape="false"
                :before-close="handleBeforeClone"
                destroy-on-close
            >
                <template #header="{ titleId, titleClass }">
                    <h4 :id="titleId" :class="titleClass">{{ dataStore.title }}</h4>
                </template>
                <div>
                    <rulesForm
                        :ruleForm="dataStore.editRuleForm"
                        :formData="dataStore.editFormData"
                        :rules="dataStore.rules"
                        ref="formRef"
                        @handleSelectChangeEmits="handleSelectChangeEmits"
                    >
                        <el-input v-model="dataStore.editRuleForm.link" clearable style="width: 440px">
                            <template #append>
                                <el-tree-select
                                    lazy
                                    :props="treeProps"
                                    :load="getSystemUrls"
                                    show-checkbox
                                    v-model="selectedNodes"
                                    ref="treeRef"
                                    check-strictly
                                    :cache-data="dataStore.data"
                                    @check="handleCheck"
                                    accordion
                                    placeholder="请选择"
                                    style="padding: 0"
                                />
                            </template>
                        </el-input>
                    </rulesForm>
                </div>
                <template #footer>
                    <div style="flex: auto">
                        <el-button @click="handleResetClick">重置</el-button>
                        <el-button type="primary" @click="handleConfirmClick">确认</el-button>
                    </div>
                </template>
            </el-drawer>
        </div>
    </div>
</template>

<script setup lang="ts" name="webNavIndex">
import rulesForm from "@/components/rulesForm/index.vue";
import SearchForm from "@/components/SearchForm/index.vue";
import { messageBox } from "@/utils/messageBox";
import { useMsg } from "@/hooks/useMsg";
import { integerRexg } from "@/utils/regexp/index";
//列表接口
import {
    getItemsListApi,
    getItemsDelApi,
    getItemsSortApi,
    getItemsReadApi,
    getItemsSaveApi,
    getItemsListEditUpApi
} from "@/api/modules/nav";
import { getNavClassListApi } from "@/api/modules/navClass";
import { getSystemUrlsApi } from "@/api/modules/home";
//深拷贝方法
import { cloneDeep } from "lodash-es";
//表格和搜索條件
import { RULE_FORM, FORM_DATA, COLUMNS, EDIT_FORM_DATA, EDIT_RULE_FORM, RULES } from "./constant/index";

const formRef: any = ref(null);
// 数据源
const dataStore = reactive<any>({
    title: "添加导航",
    tableData: [], //表格数据
    editTableData: [], //添加|编辑里的表格数据
    editColumns: [], //添加|编辑里的表格配置项
    columns: COLUMNS, //列表配置项
    rules: cloneDeep(RULES), //抽屉表单验证
    editRuleForm: cloneDeep(EDIT_RULE_FORM),
    editFormData: cloneDeep(EDIT_FORM_DATA), //抽屉表单配置项
    searchParam: cloneDeep(RULE_FORM), // 搜索參數
    searchFormData: FORM_DATA, //搜索配置项
    visible: false,
    data: [],
    isFirstRequest: true,
    selectRow: {} //当前选择的row
});
const selectedNodes = ref("");
const treeRef = ref(null);
// 配置 tree-select 的属性
const treeProps = {
    children: "children",
    label: "label",
    value: "value"
};
// //用于判断模块地址请求是不是第一次
// let isFirstRequest = true;
const buildTree = (data: any, outerLinkTo: any = "") => {
    return data.map((item: any) => {
        const { name, id, url, data: childData = [], children: nestedChildren = [] } = item;
        const currentLinkTo = item.link_to || outerLinkTo;
        const value = id ? `${currentLinkTo}/${id}/${name}` : currentLinkTo || name;

        const combinedChildren = [...childData, ...nestedChildren];
        const childNodes = buildTree(combinedChildren, currentLinkTo);

        return {
            label: name,
            value,
            url,
            link_to: currentLinkTo,
            children: childNodes
        };
    });
};
const getSystemUrls = async (node: any, resolve: any) => {
    //第一次请求
    if (dataStore.isFirstRequest) {
        const result = await getSystemUrlsApi();
        if (result?.code === 0) {
            const children = buildTree(result?.data);
            dataStore.data = children;
            resolve(children);
            dataStore.isFirstRequest = false;
        }
    } else {
        //第二次请求
        if (node.data.children) {
            resolve(node.data.children);
        }
        if (!node.data.children.length && !node.data.url && node.level > 1) {
            const [link_to, id] = node?.data?.value?.split("/");
            const result = await getSystemUrlsApi({ link_to, id });
            if (result?.code === 0) {
                const children = buildTree(result?.data, link_to);
                resolve(children);
            } else {
                resolve([]);
            }
        }
    }
};

//导航栏类型
const getNavClassList = async () => {
    const result = await getNavClassListApi();
    if (result?.code === 0) {
        let arr: any[] = [];
        result?.data.forEach((item: any) => {
            arr.push({ value: item.id, label: item.name });
        });
        dataStore.editFormData[2].options = dataStore.searchFormData[1].options = arr;
    }
};
getNavClassList();
//详情接口
const getItemsRead = async (id: any) => {
    selectedNodes.value = "";
    dataStore.data = [];
    dataStore.title = "编辑Banner";
    dataStore.visible = true;

    const result = await getItemsReadApi(id);
    dataStore.title = "编辑导航";
    dataStore.visible = true;
    if (result?.code === 0) {
        dataStore.editRuleForm = result?.data;
        console.log(dataStore.editRuleForm, "===========>>>>");
        if (dataStore.editRuleForm.link && dataStore.editRuleForm.link_to) {
            let { id, name, link } = dataStore.editRuleForm.link_echo_data;
            if (!id || !name || !link) {
                return;
            }
            let obj: any = {
                label: name, // 确保这里的name是你想要显示的文本
                value: `${dataStore.editRuleForm.link_to}` + "/" + `${id}` + "/" + `${name}`,
                url: link,
                link_to: dataStore.editRuleForm.link_to,
                children: []
            };
            let data: any = [];
            data.push(obj);
            selectedNodes.value = obj.value;
            dataStore.data = data;
        }
    }
};
const handleCheck = (checkedNodes: any, values: any) => {
    const { checkedKeys } = values;
    if (checkedKeys.length) {
        dataStore.editRuleForm.link = checkedNodes.url;
        dataStore.editRuleForm.link_to = checkedNodes.link_to;
    } else {
        dataStore.editRuleForm.link = "";
        dataStore.editRuleForm.link_to = "";
    }
};
//删除
const getItemsDel = async (id: any) => {
    messageBox("你确定要删除?", async () => {
        const result = await getItemsDelApi(id);
        if (result?.code === 0) {
            const { msg } = result;
            useMsg("success", msg);
            getItemsList();
        }
    });
};

const handleInput = (row: any) => {
    row.sort = integerRexg(row.sort);
};
const handleBlur = (row: any) => {
    getItemsSort(row);
};
//排序
const getItemsSort = async (row: any) => {
    const result = await getItemsSortApi({ id: row.id, sort: row.sort });
    if (result?.code === 0) {
        useMsg("success", result?.msg);
        getItemsList();
    }
};

const addLabelRecursively = (data: any): any => {
    if (Array.isArray(data)) {
        // 如果传入的是数组，遍历数组中的每个元素并递归调用该函数
        return data.map(item => addLabelRecursively(item));
    } else if (typeof data === "object" && data !== null) {
        // 如果传入的是对象
        data.label = data.name;
        data.value = data.id;
        if (data.children && Array.isArray(data.children)) {
            // 如果对象有 children 属性且 children 是数组，递归处理 children
            data.children = addLabelRecursively(data.children);
        }
        return data;
    }
    return data;
};

//树状列表
const getItemsList = async () => {
    const result = await getItemsListApi(dataStore.searchParam);
    if (result?.code === 0) {
        let dataClone = cloneDeep(result?.data);
        dataStore.tableData = cloneDeep(dataClone);
        dataStore.editFormData[3].options = addLabelRecursively(cloneDeep(dataClone));
        dataStore.editFormData[3].options.unshift({ value: 0, label: "无" });
    }
};
getItemsList();

//添加导航
const getItemsSave = async () => {
    const result = await getItemsSaveApi(dataStore.editRuleForm);
    if (result?.code === 0) {
        const { msg } = result;
        useMsg("success", msg);
        dataStore.visible = false;
        resetForm();
        getItemsList();
        dataStore.isFirstRequest = true;
    }
};
const handleSelectChangeEmits = (params: any) => {
    console.log("123232", params);
    if (params.prop === "nav_id") {
        return;
    }
    dataStore.editRuleForm.pid = params?.id;
};
//更新
const getItemsListEditUp = async () => {
    const result = await getItemsListEditUpApi(dataStore.editRuleForm);
    if (result?.code === 0) {
        const { msg } = result;
        useMsg("success", msg);
        dataStore.visible = false;
        resetForm();
        getItemsList();
        dataStore.isFirstRequest = true;
    }
};
//抽屉确认
const handleConfirmClick = () => {
    if (!formRef.value!.ruleFormRef) return;
    formRef!.value!.ruleFormRef!.validate((valid: any) => {
        if (valid) {
            dataStore.title === "编辑导航" ? getItemsListEditUp() : getItemsSave();
            console.log("submit!");
        } else {
            console.log("error submit!");
            return false;
        }
    });
};
//重置验证状态
const resetFields = () => {
    if (!formRef.value!.ruleFormRef) return;
    formRef!.value!.ruleFormRef.resetFields();
};
//抽屉重置
const handleResetClick = () => {
    if (dataStore.title === "编辑导航") {
        getItemsRead(dataStore.editRuleForm.id);
    } else {
        resetFields();
    }
};
//添加
const handleAdd = () => {
    dataStore.title = "添加导航";
    dataStore.visible = true;
    selectedNodes.value = "";
};
const resetForm = () => {
    dataStore.editRuleForm = cloneDeep(EDIT_RULE_FORM);
    // dataStore.editRuleForm.link_to = "";
    // dataStore.editRuleForm.link = "";
};
//抽屉关闭前的钩子
const handleBeforeClone = () => {
    resetForm();
    resetFields();
    dataStore.visible = false;
    dataStore.isFirstRequest = true;
};

const search = () => {
    getItemsList();
};
const reset = () => {
    dataStore.searchParam.name = "";
    dataStore.searchParam.nav_id = "";
    dataStore.searchParam.Time = "";
    dataStore.searchParam.pid = "";
    getItemsList();
};
</script>

<style scoped lang="scss">
::v-deep(.el-input-group__append) {
    padding: 0;
}
</style>
