from flask import Flask, request, jsonify
import numpy as np

from train.newnetwork import step

app = Flask(__name__)


def getinfo(data_array):
    """
    模拟的getinfo方法 - 实际应用中替换为您的真实算法
    这里返回固定示例数据，实际使用时替换为您的计算逻辑
    """
    # 示例返回数据 - 实际应替换为您的算法计算结果
    array = step(5, 3, data_array)
    print(array)
    uav1 = []
    uav1.append(data_array[0] + array[0])
    uav1.append(data_array[1] + array[1])
    uav2 = []
    uav2.append(data_array[3] + array[2])
    uav2.append(data_array[4] + array[3])
    uav3 = []
    uav3.append(data_array[6] + array[4])
    uav3.append(data_array[7] + array[5])
    res= []
    res.append(uav1)
    res.append(uav2)
    res.append(uav3)
    return {
        "user_target_com_rate": [],
        "device_target_pos": res,
        "user_target_pos_auc": [],
        "flight_types": [60, 60, 60],
        "target_deployment": []
    }


@app.route('/process', methods=['POST'])
def process_data():
    try:
        # 解析JSON输入
        input_data = request.json

        # 验证数据结构
        if 'data' not in input_data:
            return jsonify({"error": "Missing 'data' field"}), 400

        data = input_data['data']

        # 提取并处理deviceState字段
        device_state = data.get('deviceState', [])
        extracted_device = []
        for item in device_state:
            # 取每个元素的前三位，过滤掉无效值
            valid_values = [x for x in item[:3] if x is not None and isinstance(x, (int, float))]
            extracted_device.extend(valid_values)

        # 提取并处理userPos字段
        user_pos = data.get('userPos', [])
        extracted_user = []
        for pos in user_pos:
            # 过滤无效坐标
            if len(pos) >= 2 and all(isinstance(x, (int, float)) for x in pos[:2]):
                extracted_user.extend(pos[:2])

        # 合并所有数据形成大数组
        combined_array = extracted_device + extracted_user

        print(combined_array)

        # 调用getinfo方法（这里模拟实现）
        result = getinfo(combined_array)

        # 构建响应
        response = {
            "user_target_com_rate": result.get("user_target_com_rate", []),
            "device_target_pos": result.get("device_target_pos", []),
            "user_target_pos_auc": result.get("user_target_pos_auc", []),
            "flight_types": result.get("flight_types", []),
            "target_deployment": result.get("target_deployment", [])
        }

        return jsonify(response)

    except Exception as e:
        return jsonify({"error": str(e)}), 500


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)