<template>
    <div class="table-box">
        <div style="padding-bottom: 16px">
            <el-button type="primary" @click="handleAdd"> 添加 </el-button>
            <el-button type="primary" @click="handleExport"> 导出 </el-button>
        </div>
        <ProTable
            ref="proTableRef"
            :formData="dataStore.formData"
            :columns="dataStore.columns"
            :request-api="getBannerListApi"
            :init-param="dataStore.initParam"
        >
            <template #image="scope">
                <el-image :src="scope.row.image ? h + scope.row.image : ''" style="width: 60px; height: 60px" />
            </template>
            <template #sort="scope">
                <el-input v-model="scope.row.sort" @blur="handleBlur(scope.row)" @input="handleInput(scope.row)"></el-input>
            </template>
            <template #status="scope">
                <el-tag :type="scope.row.status == 1 ? 'success' : 'danger'" effect="dark">{{
                    scope.row.status == 1 ? "启用" : "禁用"
                }}</el-tag>
            </template>
            <template #operation="scope">
                <el-button size="small" type="primary" @click="getBannerRead(scope.row.id)">编辑</el-button>
                <el-button size="small" type="danger" @click="getBannerDel(scope.row.id)">删除</el-button>
            </template>
        </ProTable>
        <el-drawer
            v-model="dataStore.visible"
            :show-close="true"
            :size="980"
            :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"
                    @handleRadioGroupEmits="handleRadioGroupEmits"
                >
                    <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
                                accordion
                                :cache-data="dataStore.data"
                                @check="handleCheck"
                                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>
</template>

<script setup lang="ts" name="bannerListIndex">
import rulesForm from "@/components/rulesForm/index.vue";
import ProTable from "@/components/ProTable/index.vue";
import { messageBox } from "@/utils/messageBox";
import { useMsg } from "@/hooks/useMsg";
import { useExport } from "@/hooks/useExport";
import { integerRexg } from "@/utils/regexp/index";
import { getProductCategoryListApi } from "@/api/modules/productList";
// import { addLabelValue } from "@/utils/addLabelValue";
// 图片地址
import { h } from "@/utils/url";
// 列表接口
import {
    getBannerListApi,
    getBannerDelApi,
    getBannerReadApi,
    getBannerListSortApi,
    getBannerUpApi,
    getBannerListSaveApi,
    getBannerListExportApi,
    getBannerClassListApi
} from "@/api/modules/banner";
import { addLabelValue } from "@/utils/addLabelValue";

import { getSystemUrlsApi } from "@/api/modules/home";
// 深拷贝方法
import { cloneDeep } from "lodash-es";
// 表格和搜索條件
import { RULE_FORM, FORM_DATA, COLUMNS, EDIT_FORM_DATA, EDIT_FORM_DATA1, EDIT_RULE_FORM, RULES, RULES1 } from "./constant/index";
// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTableRef = ref<any>(null);
const formRef: any = ref(null);
// 数据源
const dataStore = reactive<any>({
    title: "添加Banner",
    columns: COLUMNS, // 列表配置项
    rules: cloneDeep(RULES), // 抽屉表单验证
    editRuleForm: cloneDeep(EDIT_RULE_FORM),
    editFormData: cloneDeep(EDIT_FORM_DATA), // 抽屉表单配置项
    initParam: cloneDeep(RULE_FORM), // 初始化搜索条件|重置搜索条件
    ruleForm: cloneDeep(RULE_FORM), // 搜索參數
    formData: FORM_DATA, // 搜索配置项 dataStore.formData
    visible: false,
    data: [],
    isFirstRequest: true
});

const selectedNodes = ref<any>(null);

const treeRef = ref(null);

// 配置 tree-select 的属性
const treeProps = {
    children: "children",
    label: "label",
    value: "value"
};

//产品分类(后端大佬说直接掉列表接口)
const getProductCategoryList = async () => {
    const result = await getProductCategoryListApi();
    if (result?.code === 0) {
        let dataClone: any = cloneDeep(result?.data);
        dataStore.editFormData[7].options = addLabelValue(dataClone);
    }
};

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
        };
    });
};
// let isFirstRequest = true;
const handleRadioGroupEmits = (value: any) => {
    if (value === "video") {
        dataStore.editFormData = EDIT_FORM_DATA1;
        dataStore.rules = RULES1;
        getBannerClassEditList();
    }

    if (value === "image") {
        dataStore.isFirstRequest = true;
        dataStore.editFormData = EDIT_FORM_DATA;
        dataStore.rules = RULES;
        getBannerClassEditList();
    }
};

const getSystemUrls = async (node: any, resolve: any) => {
    //第一次请求
    if (dataStore.isFirstRequest) {
        const result = await getSystemUrlsApi();
        if (result?.code === 0) {
            const children = buildTree(result?.data);
            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 setImgOrVideo = (result: any) => {
    if (result?.data?.type === "image") {
        dataStore.editFormData = cloneDeep(EDIT_FORM_DATA);
    }
    if (result?.data?.type === "video") {
        dataStore.editFormData = cloneDeep(EDIT_FORM_DATA1);
    }

    getBannerClassEditList();
};
// 详情
const getBannerRead = async (id: any) => {
    selectedNodes.value = "";
    dataStore.data = [];
    dataStore.title = "编辑Banner";
    dataStore.visible = true;
    const result = await getBannerReadApi(id);
    if (result?.code === 0) {
        dataStore.editRuleForm = result?.data;
        // setImgOrVideo(result);
        await setImgOrVideo(result);
        dataStore.editRuleForm = await result?.data;
        getProductCategoryList();

        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 getBannerUp = async () => {
    if (dataStore.editRuleForm.type === "video") {
        dataStore.editRuleForm.link_to = "";
        dataStore.editRuleForm.link = "";
    }
    if (dataStore.editRuleForm.type === "image") {
        dataStore.editRuleForm.video = "";
    }
    const result = await getBannerUpApi(dataStore.editRuleForm);
    if (result?.code === 0) {
        dataStore.visible = false;
        dataStore.editRuleForm = cloneDeep(EDIT_RULE_FORM);
        formRef!.value!.ruleFormRef.resetFields();
        proTableRef?.value?.getTableList();
        dataStore.isFirstRequest = true;
    }
};
//详情里的分类
const getBannerClassEditList = async () => {
    const result = await getBannerClassListApi();
    if (result?.code === 0) {
        dataStore.formData[1].options = addLabelValue(result?.data);
        dataStore.editFormData.forEach((item: any) => {
            if (item.prop === "banner_id") {
                item.options = addLabelValue(result?.data);
            }
        });
    }
};
getBannerClassEditList();
// 新增
const getBannerListSave = async () => {
    const result = await getBannerListSaveApi(dataStore.editRuleForm);
    if (result?.code === 0) {
        dataStore.visible = false;
        dataStore.editRuleForm = cloneDeep(EDIT_RULE_FORM);
        useMsg("success", result?.msg);
        dataStore.isFirstRequest = true;
        formRef!.value!.ruleFormRef.resetFields();
        proTableRef?.value?.getTableList();
    }
};
// 导出接口
const getArticleListExport = async () => {
    const result = await getBannerListExportApi({
        ...proTableRef?.value?.searchParam,
        ...proTableRef?.value?.pageable
    });
    await useExport(result);
};
// 导出
const handleExport = () => {
    getArticleListExport();
};
// 抽屉确认
const handleConfirmClick = () => {
    if (!formRef.value!.ruleFormRef) return;
    formRef!.value!.ruleFormRef!.validate((valid: any) => {
        if (valid) {
            dataStore.title === "编辑Banner" ? getBannerUp() : getBannerListSave();
            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 === "添加Banner") {
        console.log("12323");
        resetFields();
    } else {
        getBannerRead(dataStore.editRuleForm.id);
    }
};
// 添加
const handleAdd = () => {
    dataStore.title = "添加Banner";
    dataStore.visible = true;
    dataStore.editRuleForm = cloneDeep(EDIT_RULE_FORM);
    (dataStore.editFormData = cloneDeep(EDIT_FORM_DATA)), // 抽屉表单配置项
        getBannerClassEditList();
    // getBannerClassList();
    getProductCategoryList();
};
// 抽屉关闭前的钩子
const handleBeforeClone = () => {
    dataStore.editRuleForm = cloneDeep(EDIT_RULE_FORM);
    (dataStore.editFormData = cloneDeep(EDIT_FORM_DATA)), // 抽屉表单配置项
        resetFields();
    dataStore.visible = false;
    dataStore.isFirstRequest = true;
};

// 删除
const getBannerDel = async (id: any) => {
    messageBox("你确定要删除?", async () => {
        const result = await getBannerDelApi(id);
        if (result?.code === 0) {
            const { msg } = result;
            useMsg("success", msg);
            proTableRef?.value?.getTableList();
        }
    });
};
// 排序
const getBannerListSort = async (row: any) => {
    const result = await getBannerListSortApi({ id: row.id, sort: row.sort });

    if (result?.code === 0) {
        useMsg("success", result?.msg);
        proTableRef?.value?.getTableList();
    }
};

// 排序 input 框失焦
const handleBlur = (row: any) => {
    getBannerListSort(row);
};
// 排序 input 输入
const handleInput = (row: any) => {
    row.sort = integerRexg(row.sort);
};
</script>

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