/**
 * 访问飞翼客户端API接口
 */
import asyncHandler from 'express-async-handler';
import * as feiyiClientBiz from '../biz/feiyiClient';
import { eccReqParamater } from '../util/verificationParam';
import { addData } from '../data/addData';
import { TABLENAME } from '../config/dbEnum';

export function setRouter(httpServer) {
    /** 网关设备列表 */
    httpServer.post('/api/qdm/feiyi/gateway/list', asyncHandler(getFeiyiGatewayList));
    /** 空调内机列表 */
    httpServer.post('/api/qdm/feiyi/indoorUnit/list', asyncHandler(getFeiyiIndoorUnitList));
    /** 空调内机控制 */
    httpServer.post('/api/qdm/feiyi/indoorUnit/control', asyncHandler(getFeiyiIndoorUnitControl));
}


/**
 * 网关设备列表
 */
 async function getFeiyiGatewayList(req, res) {
    let reqConf = {page:'Number', limit:'Number'};
    const NotMustHaveKeys = [ "page", "limit" ];
    let { page, limit } = eccReqParamater(reqConf, req.body, NotMustHaveKeys);
    const result = await feiyiClientBiz.getGatewayDeviceList(page, limit);
    res.success(result);
}

/**
 * 空调内机列表
 * @param page 当前页码，默认 1
 * @param limit 每页条数，默认 10 
 * @param buildingId 楼栋ID（可选）
 * @param floorId 楼层ID（可选）
 * @param roomId 区域ID（可选）
 * @param gatewayCode 网关设备ID（可选）
 */
async function getFeiyiIndoorUnitList(req, res) {
    let reqConf = {page:'Number', limit:'Number', roomId: 'String', indoorUnitAddressFull: 'String'};
    const NotMustHaveKeys = [ "page", "limit", "roomId", "indoorUnitAddressFull" ];
    let params = eccReqParamater(reqConf, req.body, NotMustHaveKeys);
    const result = await feiyiClientBiz.getIndoorUnitList(params);
    res.success(result);
}

/**
 * 空调内机控制
 * @param indoorUnitAddressFull 要控制的内机地址集合
 * @param workMode 1 制冷 2 制热 3 送风 4 除湿
 * @param openApiAction control 控制指令 / lock 锁定指令
 */
async function getFeiyiIndoorUnitControl(req, res) {
    let reqConf = { indoorUnitAddressFull: 'Array', workMode: 'Number', openApiAction: 'String' };
    const NotMustHaveKeys = [ "workMode", "openApiAction" ];
    let params = eccReqParamater(reqConf, req.body, NotMustHaveKeys);
    const result = await feiyiClientBiz.controlIndoorUnit(params);
    // 直接API控制日志
    const now = new Date();
    const operationTime = new Date();
    const logEntries = params.indoorUnitAddressFull.map((deviceId: string) => ({
        device_id: deviceId,
        device_type: '空调',
        operation_content: {
            option: '直接API控制',
            device_id: deviceId,
            time: operationTime,
            params: {
                workMode: params.workMode,
                openApiAction: params.openApiAction,
            },
            success: result.success,
            message: result.message || (result.success ? '控制成功' : '控制失败'),
        },
        status: result.success ? 1 : 0,
        created_at: now,
        updated_at: now,
    }));
    await addData(TABLENAME.设备日志表, logEntries);
    res.success(result);
}


