import { ListIitem } from '@/api/base/BaseDataModel';
import { BaseTableProps, TableColumns } from '@/components/Table/src/types';
import { ref, unref } from 'vue';
import { v4 as uuidv4 } from 'uuid';
import { isArray, isArrayLength } from '@/utils/is';
import { cloneDeep } from '@/utils/cloneDeep';

/**
 * 测试表头的
 */
export function useDynamicMeterHead() {
    // 分区信息
    const zoningInformation = ref<Recordable[]>([
        {
            id: 1,
            items: [
                {
                    setValue: 5,
                    specialParametersId: '1',
                    partitionId: "5"
                },
                {
                    setValue: 6,
                    specialParametersId: '1',
                    partitionId: "6"
                },
                {
                    setValue: 7,
                    specialParametersId: '1',
                    partitionId: "7"
                },
                {
                    setValue: 8,
                    specialParametersId: '1',
                    partitionId: "8"
                }
            ]
        },
        {
            id: 2,
            items: [
                {
                    setValue: 1,
                    specialParametersId: '2',
                    partitionId: "5"
                },
                {
                    setValue: 2,
                    specialParametersId: '2',
                    partitionId: "6"
                },
                {
                    setValue: 3,
                    specialParametersId: '2',
                    partitionId: "7"
                },
                {
                    setValue: 4,
                    specialParametersId: '2',
                    partitionId: "8"
                }
            ]
        }
    ])
    // 
    const outputSource = ref<Recordable[]>([])
    // 表格表头数据
    const columnsDynamicMeterHead = ref<any[]>([])

    const initDynamicMeterHead = async (tableSpecialParameter: BaseTableProps) => {
        // 动态表头数据
        // console.log(zoningInformation, "动态表头数据");
        // if (!zoningInformation[0].items) return
        zoningInformation.value[0].items.forEach((item) => {
            columnsDynamicMeterHead.value.push({ label: `${item.partitionId}区`, prop: `partitionId${item.partitionId}`, slot: true, slotName: `partitionId${item.partitionId}` })
        })

        // 使用 reduce() 方法和对象字面量，将不同 id 对应的数据分别存储在不同的对象中
        const result = zoningInformation.value.reduce((acc, cur) => {
            acc[cur.id] = (acc[cur.id] || []).concat(cur.items);
            return acc;
        }, {});

        // 遍历 result 对象中的每个键，并将对应的值进行处理，将其转换为需要的数据格式
        for (let key of Object.keys(result)) {
            const items = result[key];
            const obj = {};
            items.forEach(item => {
                obj[`partitionId${item.partitionId}`] = item.setValue;
                obj['specialParametersId'] = item.specialParametersId;
            });

            outputSource.value.push(obj);
        }
        // console.log(outputSource, "以id为标识输出一个数组");
        // 合并表头
        tableSpecialParameter.columns = [...tableSpecialParameter.columns, ...columnsDynamicMeterHead.value]
        // 初始化数据
        tableSpecialParameter.dataSource = outputSource.value
    }

    // 用于转化为后端所需要 特殊参数list
    const transformDynamicMeterHead = (obj: Recordable) => {
        // 转化类似这种对象
        // const obj = {
        //     "partitionId5": 2,
        //     "specialParametersId": "1",
        //     "partitionId6": 1,
        //     "partitionId7": 7,
        //     "partitionId8": 8
        // };

        const result = Object.entries(obj)
            .filter(([key, value]) => key.includes("partitionId"))
            .map(([key, setValue]) => {
                const partitionId = Number(key.replace("partitionId", ""));
                const specialParametersId = obj.specialParametersId;
                return { setValue, partitionId, specialParametersId };
            });
        return result
    }

    return {
        initDynamicMeterHead,
        transformDynamicMeterHead,
        columnsDynamicMeterHead
    }
}

export function useDynamicMeterHeads() {
    // 表格行数据
    const outputSource = ref<Recordable[]>([])
    // 表格表头数据
    const columnsDynamicMeterHead = ref<any[]>([])

    const initDynamicMeterHead = async (tableSpecialParameter: BaseTableProps, zoningInformations: Recordable[]) => {
        if (!zoningInformations || zoningInformations.length === 0) return
        // 动态表头数据
        let newArray = [{
            id: uuidv4(),
            items: zoningInformations.map(item => ({
                setValue: '',
                specialParametersId: '',
                partitionId: item.id,
                partitionName: item.partitionName
            }))
        }];
        newArray[0].items.forEach((item) => {
            columnsDynamicMeterHead.value.push({ label: item.partitionName, prop: item.partitionId, slot: true, slotName: item.partitionId })
        })

        // 使用 reduce() 方法和对象字面量，将不同 id 对应的数据分别存储在不同的对象中
        const result = newArray.reduce((acc, cur) => {
            acc[cur.id] = (acc[cur.id] || []).concat(cur.items);
            return acc;
        }, {});

        // 遍历 result 对象中的每个键，并将对应的值进行处理，将其转换为需要的数据格式
        for (let key of Object.keys(result)) {
            const items = result[key];
            const obj = {};
            items.forEach(item => {
                obj[item.partitionId] = item.setValue;
                obj['specialParametersId'] = item.specialParametersId;
            });

            outputSource.value.push(obj);
        }
        // console.log(outputSource, "以id为标识输出一个数组");
        // 合并表头
        tableSpecialParameter.columns = [...tableSpecialParameter.columns, ...columnsDynamicMeterHead.value]
        // 初始化数据
        tableSpecialParameter.dataSource = outputSource.value
    }

    // 用于转化为后端所需要 特殊参数list
    const transformDynamicMeterHead = (obj: Recordable) => {
        // 转化类似这种对象
        // const obj = {
        //     "partitionId5": 2,
        //     "specialParametersId": "1",
        //     "partitionId6": 1,
        //     "partitionId7": 7,
        //     "partitionId8": 8
        // };

        const result = Object.entries(obj)
            .map(([key, setValue]) => {
                const partitionId = obj.partitionId
                const specialParametersId = obj.specialParametersId;
                return { setValue, partitionId, specialParametersId };
            });
        return result
    }

    return {
        initDynamicMeterHead,
        transformDynamicMeterHead,
        columnsDynamicMeterHead
    }
}

/**
 * 分区转表格表头数据
 */
export function useDealDynamicMeterHead() {
    // 表格表头数据
    const columnsDynamicMeterHead = ref<any[]>([])

    // 分区数据处理成表头数据
    const initDynamicMeterHead = (zoningInformations: Recordable[]) => {
        if (isArray(zoningInformations) && zoningInformations.length === 0) return []
        const columnsHead: TableColumns[] = []
        // 根据 orderNumber 序号排序
        const zoningInformationSort = zoningInformations.sort((a, b) => a.orderNumber - b.orderNumber)
        // 动态表头数据
        zoningInformationSort.forEach((item) => {
            columnsHead.push({ label: item.partitionName, align: "center", prop: item.id, slot: true, minWidth: 110, slotName: item.id })
        })
        columnsDynamicMeterHead.value = columnsHead
        // 合并表头
        // tableSpecialParameter.columns = [...tableSpecialParameter.columns, ...columnsDynamicMeterHead.value]
        return columnsHead
    }

    // 
    const transformDynamicMeterHeadData = () => {

    }

    // 用于转化为后端所需要 特殊参数list
    const transformDynamicMeterHead = (obj: Recordable) => {
        const result = Object.entries(obj)
            .map(([key, setValue]) => {
                const partitionId = obj.partitionId
                const specialParametersId = obj.specialParametersId;
                return { setValue, partitionId, specialParametersId };
            });
        return result
    }

    return {
        initDynamicMeterHead,
        transformDynamicMeterHead,
        columnsDynamicMeterHead
    }
}

// 初始化表头的返回的参数
type InitResultHead = {
    columns: TableColumns[]
    headNum: number
}
/**
 * 分区转表格表头数据v2
 */
export function useDealDynamicMeterHeadData(columns: TableColumns[]) {
    // 拷贝初始化 ==》 初始化 费用明细表头数据
    const cloneColumns: TableColumns[] = cloneDeep(columns)

    // 表格表头数据
    const columnsDynamicMeterHead = ref<any[]>([])
    // 分区数据处理成表头数据
    const initDynamicMeterHead = (zoningInformations: Recordable[], fieldId = 'id'): InitResultHead => {
        let headNum = 0
        if (isArray(zoningInformations) && zoningInformations.length === 0) return { headNum, columns: [] }
        clearMeterHead()
        const columnsHead: TableColumns[] = []
        // 动态表头数据
        // 根据 orderNumber 排序
        const zoningInformationSort = zoningInformations.sort((a, b) => a.orderNumber - b.orderNumber)
        zoningInformationSort.forEach((item) => {
            columnsHead.push({
                label: item.partitionName,
                align: "center",
                prop: item[fieldId],
                slot: true,
                minWidth: 110,
                slotName: item[fieldId]
            })
        })
        columnsDynamicMeterHead.value = columnsHead
        // 判断有分区过滤分区的占位符
        let currentColumnsData = isArrayLength(columnsHead) ? cloneColumns.filter(item => item.prop) : cloneColumns
        // 合并表头
        const columns = [...currentColumnsData, ...columnsHead]
        //目前分区数
        headNum = columnsHead.length
        return {
            columns,
            headNum
        }
    }

    // 用于转化为后端所需要 特殊参数list
    const transformDynamicMeterHead = (obj: Recordable) => {
        const result = Object.entries(obj)
            .map(([key, setValue]) => {
                const partitionId = obj.partitionId
                const specialParametersId = obj.specialParametersId;
                return { setValue, partitionId, specialParametersId };
            });
        return result
    }

    // 清空表格表头
    const clearMeterHead = () => {
        columnsDynamicMeterHead.value = []
    }

    return {
        initDynamicMeterHead,
        transformDynamicMeterHead,
        clearMeterHead,
        columnsDynamicMeterHead,
        cloneColumns
    }
}