import { cloneDeep } from "lodash-es";
// import { convertSpanToDiv } from "@/utils/convertSpanToDiv";
const hasIdRecursive = (data: any, targetId: any) => {
    for (let i = 0; i < data.length; i++) {
        const item = data[i];
        if (item.id === targetId) {
            return true;
        }
        if (item.children && item.children.length > 0) {
            if (hasIdRecursive(item.children, targetId)) {
                return true;
            }
        }
    }
    return false;
};

const htmlDecode = (html: any) => {
    let e: any = document.createElement("div");
    e.innerHTML = html;

    // 关键：在解码后添加样式处理
    const detailAllElements = e.querySelectorAll(".o_detail_all");
    detailAllElements.forEach((detailAll: HTMLElement) => {
        // 为文字类子元素添加居中样式
        let textElements: any = [
            ...Array.from(detailAll.querySelectorAll<HTMLElement>(".o_detail_text")),
            ...Array.from(detailAll.querySelectorAll<HTMLElement>(".o_detail_small")),
            ...Array.from(detailAll.querySelectorAll<HTMLElement>(".o_detail_title"))
        ];

        textElements.forEach((el: any) => {
            // 保留原有样式，追加居中样式（避免覆盖已有样式）
            el.style.textAlign = "center";
            // 如果需要强制覆盖，可添加 !important
            // el.style.textAlign = 'center !important';
        });
    });

    if (e.childNodes.length > 1) {
        return e.innerHTML;
    } else {
        return e.childNodes[0].innerHTML;
    }
};

//将参数分离
export const initDetailParams = (dataStore: any, data: any, editorRef: any) => {
    let is = hasIdRecursive(dataStore.options, data.category_id);
    //基本信息
    dataStore.basicInfoRuleForm = cloneDeep({
        name: data.name,
        short_name: data.short_name,
        spu: data.spu,
        is: is,
        category_id1: is ? data.category_id : data.category_name,
        category_id: data.category_id,
        category_name: data.category_name,
        params: data.params,
        sort: data.sort,
        is_show: data.is_show,
        is_new: data.is_new,
        is_hot: data.is_hot,
        is_sale: data.is_sale,
        status: data.status,
        seo_title: data.seo_title,
        seo_keywords: data.seo_keywords,
        seo_desc: data.seo_desc,
        stock_qty: data.stock_qty,
        id: data.id
    });

    //详情
    if (!data.detail) {
        dataStore.detail = "";
        editorRef?.value?.clearEditor(); // 调用子组件的清空方法
    } else {
        dataStore.detail = htmlDecode(data.detail); //htmlDecode(data.detail);
    }

    //图片
    dataStore.imgInfoData.cover_image = data.cover_image;
    dataStore.imgInfoData.video_url = data.video_url;
    dataStore.imgInfoData.skus = data.skus;
    dataStore.imgInfoData.video_img = data.video_img;

    //相关信息及下载
    if (data.related) {
        dataStore.relatedTableData = cloneDeep(data.related);
    }
};
