
import logging
from flask import Flask, request, jsonify, render_template
from mysql_connect import get_data_dict
from mqtt import MQTTClient
import time

# 配置日志记录器
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')

app = Flask(__name__)

# 获取 data_dict
data_dict = get_data_dict()

# 获取所有公司的ID
company_ids = set(row['roommaster_company_id'] for rows in data_dict.values() for row in rows)

# 创建MQTT客户端实例
mqtt_client = MQTTClient('config.json')

# 启动MQTT客户端
mqtt_client.start()

# 获取 MQTT 客户端对象和主题
mqtt_client_obj = mqtt_client.client
topic_publish = "/maintain/room/master/client/"
topic_publish_online = "/maintain/room/master/client/online/"

@app.route('/')
def index():
    return render_template('index.html', company_ids=sorted(company_ids))

@app.route('/get_regions', methods=['GET'])
def get_regions():
    company_id = int(request.args.get('company_id'))
    logging.debug(f"收到公司ID: {company_id}")
    regions = set()
    for row in data_dict.get(company_id, []):
        regions.add((row['roommaster_id'], row['roommaster_name']))
    return jsonify(list(regions))

@app.route('/get_devices', methods=['GET'])
def get_devices():
    region_ids = request.args.get('region_ids')
    logging.debug(f"收到区域ID: {region_ids}")
    region_ids = [int(id) for id in region_ids.split(',')]
    devices = []
    for company_id, rows in data_dict.items():
        for row in rows:
            if row['roommaster_id'] in region_ids:
                devices.append({
                    'device_id': row['roomdevice_udid'],
                    'device_name': row['roomdevice_name']
                })
    return jsonify(devices)

@app.route('/toggle_power', methods=['POST'])
def toggle_power():
    data = request.json
    regions = data.get('regions', [])
    on = data.get('on', False)
    logging.debug(f"收到请求参数: regions={regions}, on={on}")
    if not regions:
        logging.warning("未收到任何区域信息")
    else:
        for region in regions:
            roommaster_udid = get_roommaster_udid(region)
            if roommaster_udid:
                payload = {"udid": roommaster_udid, "action": "power", "value": 1 if on else 0}
                logging.debug(f"调用 mqtt.open_conference_room 区域: {region}, payload: {payload}")
                result = mqtt_client.open_conference_room(topic_publish, payload)
                logging.debug(f"mqtt.open_conference_room 的结果: {result}")
            else:
                logging.warning(f"未找到区域 {region} 对应的 roommaster_udid")
    return jsonify({'success': True})

@app.route('/toggle_status', methods=['POST'])
def toggle_status():
    data = request.json
    regions = data.get('regions', [])
    online = data.get('online', False)
    logging.debug(f"收到请求参数: regions={regions}, online={online}")
    if not regions:
        logging.warning("未收到任何区域信息")
    else:
        for region in regions:
            roommaster_udid = get_roommaster_udid(region)
            if roommaster_udid:
                payload = {"udid": roommaster_udid, "action": "status", "value": 1 if online else 0}
                logging.debug(f"调用 mqtt.conference_room_online 区域: {region}, payload: {payload}")
                if online:
                    result = mqtt_client.conference_room_online(topic_publish_online, payload)
                else:
                    result = mqtt_client.conference_room_offline(topic_publish_online, payload)
                logging.debug(f"mqtt.conference_room_online/offline 的结果: {result}")
            else:
                logging.warning(f"未找到区域 {region} 对应的 roommaster_udid")
    return jsonify({'success': True})

def get_roommaster_udid(roommaster_id):
    for rows in data_dict.values():
        for row in rows:
            if row['roommaster_id'] == roommaster_id:
                return row['roommaster_udid']
    return None

if __name__ == '__main__':
    try:
        app.run(debug=True)
    except KeyboardInterrupt:
        logging.info("已手动中断Flask应用进程！")
    finally:
        # 停止MQTT客户端
        mqtt_client.stop()