#!/usr/bin/env python3
"""导出6月份微信反馈数据到 Excel"""
import pymysql
from openpyxl import Workbook
from openpyxl.styles import Font, Alignment, PatternFill
from datetime import datetime

conn = pymysql.connect(
    host='bj-cdb-8frbdwju.sql.tencentcdb.com',
    port=25413,
    user='chatbot',
    password='xhuBx7d@uT2gUVv',
    database='vala_test',
    charset='utf8mb4'
)

cursor = conn.cursor()
cursor.execute("""
    SELECT 
        id, sender_name, msg_type, content, msg_time, svr_msg_id, refer_msg_svrid
    FROM wechat_group_message 
    WHERE msg_time >= '2026-06-01' AND msg_time < '2026-07-01'
    ORDER BY msg_time ASC
""")
rows = cursor.fetchall()
cursor.close()
conn.close()

print(f"共 {len(rows)} 条记录")

wb = Workbook()
ws = wb.active
ws.title = "6月微信反馈"

# Headers
headers = ['序号', '发送者', '消息类型', '消息内容', '发送时间', '消息ID', '引用消息ID']
header_fill = PatternFill(start_color="4472C4", end_color="4472C4", fill_type="solid")
header_font = Font(name='微软雅黑', bold=True, color="FFFFFF", size=11)
data_font = Font(name='微软雅黑', size=10)

for col, h in enumerate(headers, 1):
    cell = ws.cell(row=1, column=col, value=h)
    cell.fill = header_fill
    cell.font = header_font
    cell.alignment = Alignment(horizontal='center', vertical='center')

for i, row in enumerate(rows, 2):
    ws.cell(row=i, column=1, value=i-1).font = data_font
    ws.cell(row=i, column=2, value=row[1]).font = data_font
    ws.cell(row=i, column=3, value=row[2]).font = data_font
    ws.cell(row=i, column=4, value=row[3] or '').font = data_font
    ws.cell(row=i, column=5, value=str(row[4])).font = data_font
    ws.cell(row=i, column=6, value=str(row[5]) if row[5] else '').font = data_font
    ws.cell(row=i, column=7, value=str(row[6]) if row[6] else '').font = data_font

# Column widths
ws.column_dimensions['A'].width = 6
ws.column_dimensions['B'].width = 28
ws.column_dimensions['C'].width = 12
ws.column_dimensions['D'].width = 80
ws.column_dimensions['E'].width = 20
ws.column_dimensions['F'].width = 22
ws.column_dimensions['G'].width = 22

# Freeze header
ws.freeze_panes = 'A2'

# Auto-filter
ws.auto_filter.ref = f"A1:G{len(rows)+1}"

output_path = '/root/.openclaw/workspace-xiaokui/output/微信反馈_2026年6月.xlsx'
wb.save(output_path)
print(f"已保存到: {output_path}")
