import type {ColInter, ItemType, OptionItemInter, TreeInter} from "@/utils/common-type";
import {cloneDeep} from "lodash-es";
import {createVNode, h, ref, watchEffect} from "vue"
import {checkNull, getLocalDate} from "../../commonMethods/commonMethods";
import type {Ref} from "vue"


export type UseFormatShowColsContext = {
    props: any;
    key: string
    saveURL?: string
    formatShowSaveFun?: any
    reload?: any
    spinning?: Ref<boolean>,
    selectChange?: any
    isShowTextOperate: boolean,
    rowBtnOption: any,
    headBtnOption: any,
    moreDetailClick?: any
};
export const UseFormatShowCols = function ({
                                               props,
                                               key,
                                               saveURL,
                                               formatShowSaveFun,
                                               reload,
                                               spinning,
                                               isShowTextOperate,
                                               rowBtnOption,
                                               headBtnOption,
                                               moreDetailClick
                                           }: UseFormatShowColsContext) {
    const innerCols = ref<any[]>([])
    watchEffect(() => {
            /* if(innerCols.value.length>0){
                 innerCols.value=[]
             }*/
            const Cols = props.tableParams.columns
            if (Cols.length > 0) {
                const cols = Cols.filter((item: ColInter) => {
                    return item.Visible == true;
                });
                for (let i = 0; i < cols.length; i++) {
                    let tempItem = {} as any
                    if (cols[i].Style.toLowerCase() === "textbox") {
                        tempItem = {
                            title: cols[i].title,
                            dataIndex: cols[i].Field,
                            width: cols[i].width,
                            resizable: true,
                            align: "left",
                            hideInSearch: !cols[i].ifshowInQueryForm, //是否生成到最终的查询面板中
                            defaultEditable: true,
                            editable: cols[i].isEdit,
                            customRender: ({record}: any) => {
                                return _getInputComponent(record, cols[i], moreDetailClick);
                            },
                        };
                    } else if (cols[i].Style.toLowerCase() === "checkbox") {
                        tempItem = {
                            title: cols[i].title,
                            dataIndex: cols[i].Field,
                            width: cols[i].width,
                            resizable: true,
                            align: 'center',
                            editable: true,
                            defaultEditable: true,
                            customRender: ({record}: any) => {
                                return _getCheckBox(record, cols[i]);
                            },
                            hideInSearch: cols[i].ifshowInQueryForm ? false : true,
                        };
                    } else if (cols[i].Style.toLowerCase() === "combox") {
                        tempItem = {
                            title: cols[i].title,
                            dataIndex: cols[i].Field,
                            width: cols[i].width,
                            resizable: true,
                            hideInSearch: !cols[i].ifshowInQueryForm, //是否生成到最终的查询面板中
                            editable: cols[i].isEdit,
                            defaultEditable: true,
                            align: cols[i].ifShowColor ? 'center' : 'left',
                            customRender: ({record}: any) => {
                                return _getComBoxLabel(record, cols[i]);
                            },
                        };
                    } else if (cols[i].Style.toLowerCase() === "tree") {
                        tempItem = {
                            title: cols[i].title,
                            dataIndex: cols[i].Field,
                            width: cols[i].width,
                            resizable: true,
                            editable: true,
                            defaultEditable: true,
                            customRender: ({record}: any) => {
                                const tempCol = props.tableParams.columns.find((item: ColInter) => {
                                    return item.Field == cols[i].Field
                                })
                                if (tempCol) {
                                    return _getTreeLabel(record, tempCol);
                                }
                            },
                            hideInSearch: cols[i].ifshowInQueryForm ? false : true,
                        };
                    } else if (cols[i].Style.toLowerCase() === "datetime" || cols[i].Style.toLowerCase() === "date") {
                        tempItem = {
                            title: cols[i].title,
                            dataIndex: cols[i].Field,
                            width: cols[i].width,
                            align: 'lef',
                            resizable: true,
                            editable: true,
                            defaultEditable: true,
                            customRender: ({record}: any) => {
                                if (checkNull(record[cols[i].Field])) {
                                    return ""
                                } else {
                                    return showTimeLabel(record, cols[i])
                                }

                            },
                            hideInSearch: cols[i].ifshowInQueryForm ? false : true,
                        }
                    } else {
                        //默认情况下，全部生成文本
                        tempItem = {
                            title: cols[i].title,
                            dataIndex: cols[i].Field,
                            width: cols[i].width,
                            resizable: true,
                            align: "left",
                            hideInSearch: !cols[i].ifshowInQueryForm, //是否生成到最终的查询面板中
                            defaultEditable: true,
                            editable: cols[i].isEdit,
                            customRender: ({record}: any) => {
                                return _getInputComponent(record, cols[i], moreDetailClick);
                            },
                        };
                    }
                    const sameTempItem = innerCols.value.find((item: any) => item.dataIndex === tempItem.dataIndex)
                    if (!sameTempItem) {
                        innerCols.value.push(tempItem);
                    }
                }
                const actionIndex = innerCols.value.findIndex((item: any) => item.dataIndex === 'ACTION')
                if (actionIndex !== -1) {
                    innerCols.value.splice(actionIndex, 1)
                }
                if (rowBtnOption?.ifShow || headBtnOption?.ifShow) {
                    let ifShowRow = rowBtnOption?.ifShow
                    if (typeof rowBtnOption?.ifShow === 'function') {
                        ifShowRow = rowBtnOption.ifShow()
                    }
                    let ifShowHead = headBtnOption?.ifShow
                    if (typeof headBtnOption?.ifShow === 'function') {
                        ifShowHead = headBtnOption.ifShow()
                    }
                    if (ifShowRow || ifShowHead) {
                        let btnNum = 0
                        btnNum = rowBtnOption.btnOption.btnNum
                        if (!btnNum) {
                            btnNum = rowBtnOption.btnOption.filter((item: any) => {
                                return item.visible
                            }).length
                        }
                        const rowBtnWidth = 30 * btnNum
                        innerCols.value.push({
                            //@ts-ignore
                            title: t("Formula.Common.Operate"),
                            align: 'center',
                            width: (rowBtnWidth) < 50 ? 50 : rowBtnWidth,
                            dataIndex: 'ACTION',
                            fixed: 'left',
                            customRender: ({record}: any) => {
                                return ifShowRow ? _getOperateIcon(record, rowBtnOption) : ''
                            },
                        })
                    }
                }
            }
        }
    )
    const _getInputComponent = function (record: OptionItemInter, col: ColInter, moreDetailClick: any) {
        const text = record[col.Field];
        let res = '' as any
        if (col.bgColor || col.ifGetMoreDetail) {
            let color = ''
            if (col.ifGetMoreDetail) {
                color = '#59aaf0'
            }
            res = (
                <span
                    style={{
                        display: "inline-block",
                        color: color,
                        padding: "3px",
                        borderRadius: "8px",
                        border: "#f0f8ff 0px solid",
                        cursor: col.ifGetMoreDetail ? 'pointer' : ''
                    }}
                   //@ts-ignore
                    onClick={col.ifGetMoreDetail ? moreDetailClick.bind(this, record) : () => {
                    }}
                >
            {text}
          </span>
            );
        }
        return res ? res : text
    }
    const _getCheckBox = (record: any, col: ColInter) => {
        const field = col.Field ? col.Field : col.dataIndex
        if (record[col.Field]) {
            return (
                <div style={{
                    width: '16px',
                    height: '16px',
                    'display': 'inline-block',
                }}>
                    <div
                        class="icon icon-check"
                        style={{
                            'display': 'flex',
                            "justify-content": "center",
                            "align-items": "center",
                            'color': 'white',
                            'background-color': '#386cf9',
                            width: '18px',
                            height: '18px',
                            padding: '7px',
                            fontSize: '10px',
                            border: '1px solid #d9d9d9',
                            'border-radius': '4px'
                        }}></div>
                </div>)
        }
        return <a-checkbox checked={record[field]} disabled={true}></a-checkbox>;
    };
    const _getComBoxLabel = (record: any, col: ColInter) => {
        let bgColor = "" as any;
        let color = "" as any;
        let res = "" as any;
        const field = col.Field ? col.Field : col.dataIndex
        let label = record[field]
        if (col.Option && col.Option.length > 0) {
            for (let i = 0; i < col.Option.length; i++) {
                if (col.Option[i].value == record[field]&&!checkNull(record[field]||col.Option[i].value === record[field])) {
                    if (col.Option[i].label) {
                        label = col.Option[i].label;
                        if (col.ifShowColor) {
                            color = col.Option[i].color;
                            bgColor = col.Option[i].bgColor;
                        }
                    }
                    break;
                }
            }
        }
        if (col.ifShowColor && label) {
            if (!bgColor) {
                bgColor = "#66c3ff";
            }
            if (!color) {
                color = "white";
            }
            res = (
                <span
                    style={{
                        boxSizing: 'border-box',
                        display: "inline-block",
                        backgroundColor: bgColor,
                        color: color,
                        padding: "0px",
                        borderRadius: "5px",
                        border: "#f0f8ff 3px solid",
                        fontSize: "12px",
                    }}
                >
            {label}
          </span>
            );
        }
        return res ? res : label;
    };
    const showTimeLabel = function (record: any, col: ColInter) {
        const field = col.Field ? col.Field : col.dataIndex
        let ifShowTime = true
        if (col.showTime === false || col.Style === 'Date') {
            ifShowTime = false
        }
        return (<span style={{}}>{getLocalDate(record[field], ifShowTime)}</span>)
    }
    const showColorComponent = function (record: any, col: ColInter) {
        const field = col.Field ? col.Field : col.dataIndex
        return (
            <colorPicker color={record[field]} disabled={true}
            ></colorPicker>)
    }
    const _getTreeLabel = (record: any, col: ColInter) => {
        // 如果treeOption为空，直接返回原始值
        if (!col.treeOption || !Array.isArray(col.treeOption) || col.treeOption.length === 0) {
            return record[col.Field];
        }

        // 创建一个Map来存储value和label的映射
        const valueLabelMap = new Map<string, string>();
        
        // 递归函数来构建Map
        const buildMap = (nodes: TreeInter[]) => {
            nodes.forEach(node => {
                if (node.value !== undefined && node.label !== undefined) {
                    valueLabelMap.set(String(node.value), node.label);
                }
                if (Array.isArray(node.children) && node.children.length > 0) {
                    buildMap(node.children);
                }
            });
        };

        // 只在第一次调用时构建Map，或者当treeOption发生变化时重新构建
        // if (!col._valueLabelMap || !col._treeOptionVersion) {
        if (!col._valueLabelMap) {
            buildMap(cloneDeep(col.treeOption));
            col._valueLabelMap = valueLabelMap;
            // col._treeOptionVersion = JSON.stringify(col.treeOption);
        }
       /* else if (col._treeOptionVersion !== JSON.stringify(col.treeOption)) {
            // 如果treeOption发生变化，重新构建Map
            valueLabelMap.clear();
            buildMap(cloneDeep(col.treeOption));
            col._valueLabelMap = valueLabelMap;
            col._treeOptionVersion = JSON.stringify(col.treeOption);
        }*/

        // 直接从Map中获取label，如果找不到则返回原始值
        const fieldValue = record[col.Field];
        return fieldValue !== undefined ? col._valueLabelMap.get(String(fieldValue)) || fieldValue : '';
    };
    const _getOperateIcon = (record: any, rowBtnOption: any) => {
        return (
            <div style="text-align:center;">
                {rowBtnOption.btnOption.filter((item: any) => {
                    return item.visible && item.customVisible(record)
                }).map(((item: any) => {
                    //@ts-ignore
                    return <i onClick={item.clickEvent.bind(this, record)}
                              title={item.title ? item.title : (item.zhTitle)}
                              className={item.icon}
                              style={{ 'color': item.color ? item.color : '#388ef4', marginLeft: 8 + 'px'}}></i>
                }))}
            </div>
        )
    }
    return {innerCols};
}

