import requests # type: ignore
import json
from datetime import datetime, timedelta
import pandas as pd
import xlsxwriter # type: ignore

def create_excel_with_chart(result_df, output_file):
    result_df['dPitch']=pd.to_numeric(result_df['dPitch'], errors='coerce')
    result_df['dRoll']=pd.to_numeric(result_df['dRoll'], errors='coerce')
    # 创建Excel写入器
    writer = pd.ExcelWriter(output_file, engine='xlsxwriter')
    
    # 将DataFrame写入Excel
    result_df.to_excel(writer, sheet_name='Data', startrow=25,index=False)
    
    # 获取工作簿和工作表对象
    workbook = writer.book
    worksheet = writer.sheets['Data']
    
    # 创建折线图
    chart = workbook.add_chart({'type': 'line'})
    
    # 配置图表数据
    max_row = len(result_df) +1  # +1因为第一行是标题
    chart.add_series({
        'name': 'dPitch',
        'categories': ['Data', 1+25, 0, max_row-1+25, 0],  # Date列作为X轴
        'values': ['Data', 1+25, 3, max_row-1+25, 3],      # dPitch列作为Y轴
    })
    
    # 设置图表标题和轴标签
    chart.set_title({'name': 'dPitch over Time'})
    chart.set_x_axis({'name': 'Date'})
    chart.set_y_axis({'name': 'dPitch'})
    chart.set_size({'width': 480, 'height': 320})
    
    # 设置日期格式的X轴
    chart.set_x_axis({'date_axis': True})
    
    # 将图表插入工作表
    worksheet.insert_chart('B2', chart)
    
    # 保存Excel文件
    writer.close()








url = "https://iot.raytue.com/prod-api/login"
payload = {
  "username": "admin",
  "password": "@raytue123",
  "sourceType": 1
}
headers = {
    'Content-Type': 'application/json'
}
# 发送POST请求
response = requests.post(url,  headers=headers, data=json.dumps(payload))

# 检查请求是否成功
if response.status_code == 200:
    # 解析并打印返回的数据
    data = response.json()
    print(json.dumps(data, indent=4))
else:
    # 打印错误信息
    print(f"请求失败，状态码：{response.status_code}，响应内容：{response.text}")

token= data["token"]
# 定义token和请求接口#
#token = "Bearer eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6IjcwNTdmNzIzLTY5NDUtNDgyZS04ZDViLTgyNjZjNjZhOTg2NCJ9.7Akf3R2AXpYNkGn3LhRkINZjRa7ZWUx1O3zCR6R6rcw5IF0083v5Jypv2OmKfItJxqLTNHLsNJGEVl74qC7FAA"
url = "https://iot.raytue.com/prod-api/data/center/deviceHistory"

# 定义请求的载荷
payload ={
  "deviceId": 278,
  "serialNumber": "D2367JBEYPY32",
  "identifierList": [
    {
      "identifier": "tiltData_time",
      "type": 1
    },
    {
      "identifier": "tiltData_dRoll",
      "type": 1
    },
    {
      "identifier": "tiltData_dPitch",
      "type": 1
    }
  ],
  "beginTime": "2025-05-30 11:45:12",
  "endTime": "2025-06-06 11:45:12"
}
# 设置请求头，包括Authorization
headers = {
    'Authorization': token,
    'Content-Type': 'application/json'
}

# 发送POST请求
response = requests.post(url, headers=headers, data=json.dumps(payload))

# 检查请求是否成功
if response.status_code == 200:
    # 解析并打印返回的数据
    data1 = response.json()
    # print(json.dumps(data1, indent=4))
else:
    # 打印错误信息
    print(f"请求失败，状态码：{response.status_code}，响应内容：{response.text}")

original_json = json.dumps(data1, indent=4)
# 将JSON字符串转换为Python字典
data_dict = json.loads(original_json)

# 初始化tiltData数组
tilt_data_array = []

# 遍历data数组
for item in data_dict['data']:
    # 获取时间戳作为键（这里我们不需要它作为最终输出的一部分，但用它来访问内部列表）
    timestamp_key = list(item.keys())[0]
    # 获取与该时间戳关联的数据列表
    data_list = item[timestamp_key]
    
    # 初始化一个空字典来存储组合后的数据
    combined_data = {}
    
    # 遍历数据列表，将相关数据合并到字典中
    for data in data_list:
        for key, value in data.items():
            combined_data[key] = value
    
    # 将组合后的数据字典添加到tiltData数组中
    tilt_data_array.append(combined_data)

# # 将结果插入回原始字典中的新键'tiltData'
# data_dict['tiltData'] = tilt_data_array

# # 将修改后的字典转换为JSON字符串并打印
# modified_json = json.dumps(data_dict, indent=4)
#print(tilt_data_array)
# print(len(tilt_data_array))

# 打开（或创建）TXT文件并写入字符串
# with open('output.txt', 'w', encoding='utf-8') as file:
#     file.write(str(tilt_data_array))
tilt_data = json.dumps(tilt_data_array)


# 转换为DataFrame
df = pd.DataFrame(json.loads(tilt_data))
#print(df['tiltData_time'])

# 将字符串时间转换为datetime对象
df['tiltData_time'] =pd.to_datetime( df['tiltData_time'].str.slice(stop=-6))

# 获取当前日期和时间
current_time = datetime.now()

# print(current_time)

# 计算前30天的日期列表
dates = [current_time - timedelta(days=i) for i in range(1, 31)]

# 初始化一个空的DataFrame来存储结果
result_df = pd.DataFrame(columns=['Date', 'Time', 'dRoll', 'dPitch'])

# 遍历前30天的日期
for date in dates:
    # 获取当天上午的数据
    # print("--------------------------------------------------------------------")
    # print(date.date())

    day_data = df[(df['tiltData_time'].dt.date == date.date()) & (df['tiltData_time'].dt.hour < 12)]
    # print(day_data)
    # print("--------------------------------------------------------------------")
    # print(day_data)
    # 如果当天有数据，则找到最接近10点30分的数据
    if not day_data.empty:
        # 计算每个数据与10点30分的时间差
        time_diffs = abs(day_data['tiltData_time']- pd.to_datetime(f'{date.date()} 10:30:00'))
        print("--------------------------------------------------------------------")
        print(time_diffs.idxmin())
    #     # 找到时间差最小的数据

        closest_data = df.iloc[time_diffs.idxmin()]
        print(closest_data)
        # 将数据添加到结果DataFrame中
        result_df = result_df._append({
            'Date': closest_data['tiltData_time'].date(),
            'Time': closest_data['tiltData_time'].time(),
            'dRoll': closest_data['tiltData_dRoll'],
            'dPitch': closest_data['tiltData_dPitch']
        }, ignore_index=True)

# 按照时间从小到大排序
result_df = result_df.sort_values(by=['Date', 'Time'])
reportname ='report'+ str(datetime.now().date()).replace("-", "") + '.xlsx'

# 将结果保存到Excel表格中
result_df.to_excel(reportname, index=False)

print(f"数据已保存到{reportname}文件中。")
create_excel_with_chart(result_df,'output_with_chart.xlsx')






