import math
import random

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import pandas as pd
import constants as C
import Users


def gauss_markov_model(positions, step_size, max_range, ):
    # 使用高斯-马尔科夫模型生成随机位置变化，考虑更长时间范围的随机性
    delta = np.random.normal(0, step_size, size=positions.shape)
    new_positions = positions + delta

    # 限制位置在给定范围内
    new_positions = np.clip(new_positions, 0, max_range)
    # print(new_positions)

    return new_positions

def generate_users_pos(users,slot,num):
    U=[]
    U.append(users)
    for i in range(num):
        users=gauss_markov_model(users, slot*C.v, C.max_range, )
        U.append(users)
    print(U)
    return U
def generate_users_pos_in_file(users,slot,num):
    U=[]
    U.append(users)
    for i in range(num):
        # users=gauss_markov_model(users, slot*C.v, C.max_range, )
        users = random_pos(users, slot * C.v, C.max_range)
        U.append(users)
    print(U)
    U=np.array(U)
    np.save('dynamic_users2.npy', U)
    # 从文件加载NumPy数组
    return U
def get_users_pos_from_file():
    U = np.load('dynamic_users2.npy')
    # 打印加载的数组
    # print("Loaded Data:")
    # print(U)
    # u1=U[2][1]
    # u2=U[3][1]
    # print(math.sqrt((u1[0]-u2[0])**2+(u1[1]-u2[1])*2))

    return U

def random_pos(positions, step_size, max_range,):
    angles = np.random.uniform(0,2*np.pi, len(positions))
    # angels=np.full((1, len(positions)), np.pi/4)
    # Generate random distances within the outer circle
    distances = step_size

    # Convert polar coordinates to Cartesian coordinates
    x = positions[:, 0] + distances * np.cos(angles)
    y = positions[:, 1] + distances * np.sin(angles)
    new_positions=[]
    for i in range(len(x)):
        new_positions.append(np.array([x[i],y[i]]))
    new_positions=np.array(new_positions)
    new_positions = np.clip(new_positions, 0, max_range)
    print(new_positions)
    return new_positions

def random_r(users):
    r_c = {}
    r_p={}
    for i in range(len(users)):
        r_c[i] = random.randint(1,4)
        r_p[i]=random.randint(1,4)
    return r_c,r_p

def generate_random_r_in_file(users,num,filename):
    #80% 1,2 20% 3,4
    a=random.random()
    dic={}
    length=len(users)
    for i in range(length):
        dic[str(i)]=[]
    df=pd.DataFrame(dic)
    for i in range(num):
        r=[]
        for j in range(length):
            a=random.random()
            if a>0.8:
                b=random.random()
                if b>=0.8:
                    r.append(3)
                else:
                    r.append(4)
            else:
                b = random.random()
                if b >= 0.7:
                    r.append(1)
                else:
                    r.append(2)
        # r=[random.randint(1,4) for i in range(length)]
        df.loc[len(df)] = r  # 通过 loc 添加一行
    # print(df)
    # 将 DataFrame 存入 CSV 文件
    df.to_csv(filename, index=False)

def read_csv_to_df(file_path):
    df = pd.read_csv(file_path)
    # 选择 DataFrame 中的一行（例如，第一行）

    # 打印结果
    # print(row_dict)
    return df

def get_r_c_and_r_p(df_c,df_p,index):
    selected_c = df_c.iloc[index]
    selected_p = df_p.iloc[index]
    # 将选定的行转换为字典
    r_c = {int(key): value for key, value in selected_c.to_dict().items()}
    r_p = {int(key): value for key, value in selected_p.to_dict().items()}
    return r_c,r_p


users=Users.getUsers("./data3.csv")
# generate_users_pos(users,10,5)
# generate_random_r_in_file(users,50,'r_p.csv')
# generate_users_pos_in_file(users,10,30)
U=get_users_pos_from_file()
# print(len(U))
# df_c=read_csv_to_df('r_c.csv')
# df_p=read_csv_to_df('r_p.csv')
# r_c,r_p=get_r_c_and_r_p(df_c,df_p,0)
# print(r_c,r_p)
# U=get_users_pos_from_file()
def update(frame, user_positions, sc, step_size, max_range,):
    user_positions = gauss_markov_model(user_positions, step_size, max_range, )
    # user_positions=random_pos(user_positions, step_size, max_range,)

    sc.set_offsets(user_positions)
    return sc,


def create_dynamic_plot(num_users, max_range, step_size,):
    # 初始化用户位置
    user_positions = np.random.uniform(0, max_range, size=(num_users, 2))

    # 创建散点图
    fig, ax = plt.subplots()
    sc = ax.scatter(user_positions[:, 0], user_positions[:, 1])

    # 设置图形的标题和坐标轴标签
    ax.set_title('Dynamic Point Plot with Gauss-Markov Model')
    ax.set_xlabel('X-axis')
    ax.set_ylabel('Y-axis')

    # 使用FuncAnimation实现动态效果
    animation = FuncAnimation(fig, update, frames=300, fargs=(user_positions, sc, step_size, max_range,), interval=100)

    # 返回FuncAnimation对象
    return animation
def draw_dynamic_users():
    # 设置参数
    num_users = 15
    max_range = 1000
    step_size = 10
    persistence_factor = 1

    # 创建动态点位图
    dynamic_plot = create_dynamic_plot(num_users, max_range, step_size,)

    # 显示动画
    plt.show()

# draw_dynamic_users()