import { selectDataListByParam } from "../data/findData";
import { TABLENAME } from "../config/dbEnum";
import { updateManyData } from "../data/updateData";

/** 楼栋排序基础值（间隔100，便于中间插入） */
const BUILDING_BASE: Record<string, number> = {
    'A馆': 100,
    'B馆': 200,
    'C馆': 300,
};

/** 楼层排序偏移值 */
const FLOOR_OFFSET: Record<string, number> = {
    '一层': 1,
    '二层': 2,
    '三层': 3,
    '四层': 4,
};

/**
 * 根据楼栋和楼层计算 sort_order 值
 * 排序规则：A馆 > B馆 > C馆 > 其它；一层 > 二层 > 三层 > 四层 > 其它
 */
export function computeSortOrder(groups: string, type: string): number {
    const buildingBase = BUILDING_BASE[groups] ?? 900;
    const floorOffset = FLOOR_OFFSET[type] ?? 99;
    return buildingBase + floorOffset;
}

/**
 * 刷新所有区域的 sort_order（系统启动时执行）
 * 遍历所有区域，根据 groups + type 重新计算并更新 sort_order
 */
export async function refreshRegionSortOrder(): Promise<void> {
    const regionList = await selectDataListByParam(
        TABLENAME.区域表,
        {},
        ["id", "groups", "type", "sort_order"],
    );
    const regions = regionList.data || [];
    let updatedCount = 0;

    for (const r of regions) {
        const newVal = computeSortOrder(r.groups, r.type);
        if (r.sort_order !== newVal) {
            await updateManyData(TABLENAME.区域表, { id: r.id }, { sort_order: newVal });
            updatedCount++;
        }
    }

    console.log(`sort_order 刷新完成，共更新 ${updatedCount} 条区域记录`);
}

/**
 * 获取楼栋区域列表（供前端下拉选择）
 * @returns 区域列表，按 sort_order 排序
 */
export async function getRegionList( regionGroup: string ) {
    let where: any = { "%orderAsc%": "sort_order" };
    if (regionGroup) {
        where.groups = regionGroup;
    }
    let regionList = await selectDataListByParam(
        TABLENAME.区域表, 
        where,
        ["type", "groups"],
    );

    let regionGroupTypeArr: any = [];
    let regionMap: any = {};
    regionList.data.forEach((r: any) => {
        let regionArr = [];
        if (regionMap[r.groups]) {
            regionArr = regionMap[r.groups];
        }
        if (!regionGroupTypeArr.includes(r.groups + "-" + r.type)) {
            regionGroupTypeArr.push(r.groups + "-" + r.type);
            regionArr.push({regionType: r.type, regionGroup: r.groups});
            regionMap[r.groups] = regionArr;
        }
    });
    console.log("区域列表:", regionMap);

    return {
        list: regionMap
    };
}

/**
 * 获取所有区域列表（供前端下拉选择）
 * @returns 区域列表，按 sort_order 排序
 */
export async function getRegionAllList( regionGroup: string ) {
    let where: any = { "%orderAsc%": "sort_order" };
    if (regionGroup) {
        where.groups = regionGroup;
    }
    let regionList = await selectDataListByParam(
        TABLENAME.区域表, 
        where,
        ["id", "room_id", "name", "type", "groups"],
    );

    let regionGroupTypeArr: any = [];
    let regionMap: any = {};
    regionList.data.forEach((r: any) => {
        let regionArr = [];
        if (regionMap[r.groups]) {
            regionArr = regionMap[r.groups];
        }
        if (!regionGroupTypeArr.includes(r.groups + "-" + r.type)) {
            regionGroupTypeArr.push(r.groups + "-" + r.type);
            regionArr.push({regionKey: r.id, roomId: r.room_id, regionName: r.name, regionType: r.type, regionGroup: r.groups});
            regionMap[r.groups] = regionArr;
        }
    });
    console.log("区域列表:", regionMap);

    return {
        list: regionMap
    };
}

/**
 * 获取区域设备树
 * @returns 区域树
 */
export async function getRegionDevices() {
    // 查询所有区域
    let where: any = { "%orderAsc%": "sort_order" };
    let regionList = await selectDataListByParam(
        TABLENAME.区域表, 
        where,
        ["id", "room_id", "name", "type", "groups"],
    );
    const regions: any[] = regionList.data || [];
    if (regions.length === 0) return [];

    // 通过区域查询所有空调设备
    const regionIds = regions.map((r: any) => r.id);
    const deviceList = await selectDataListByParam(
        TABLENAME.设备表,
        { region_key: { "%in%": regionIds }, device_type: "空调" },
        ["device_id", "device_name", "region_key", "control_params"],
    );
    const devices: any[] = deviceList.data || [];

    // 将设备列表转成map形式：{regionKey:[{设备1},{设备2}]}
    const deviceMap: { [regionKey: number]: any[] } = {};
    for (const d of devices) {
        const rk = d.region_key;
        if (!deviceMap[rk]) deviceMap[rk] = [];
        deviceMap[rk].push({
            deviceId: d.device_id,
            deviceName: d.device_name || d.device_id,
            controlParams: d.control_params || null,
        });
    }

    // 循环区域，将区域转成树结构，并通过设备map将设备加入区域
    const groupMap: { [group: string]: { key: string; value: string; typeMap: { [type: string]: { key: string; value: string; sub: any[] } } } } = {};
    for (const r of regions) {
        const groupName = r.groups;
        const typeName = r.type;

        if (!groupMap[groupName]) {
            groupMap[groupName] = { key: groupName, value: groupName, typeMap: {} };
        }
        if (!groupMap[groupName].typeMap[typeName]) {
            groupMap[groupName].typeMap[typeName] = { key: typeName, value: typeName, sub: [] };
        }

        groupMap[groupName].typeMap[typeName].sub.push({
            regionKey: r.id,
            roomId: r.room_id,
            regionName: r.name,
            devices: deviceMap[r.id] || [],
        });
    }

    // 返回区域树
    const result: any[] = [];
    const sortedGroups = Object.keys(groupMap).sort();
    for (const groupName of sortedGroups) {
        const group = groupMap[groupName];
        const typeArr: any[] = [];
        const sortedTypes = Object.keys(group.typeMap).sort();
        for (const typeName of sortedTypes) {
            typeArr.push(group.typeMap[typeName]);
        }
        result.push({ key: group.key, value: group.value, sub: typeArr });
    }

    return result;
}