import time
import sys
import pendulum
# import schedule
import asyncio
import aioschedule as schedule

sys.path.append("/home/ubuntu/data/code/unify_api2/pot_libs")
sys.path.append("/home/ubuntu/data/code/unify_api2")
from pot_libs.logger import log
from pot_libs.aiokafka_util.kafka_util import KafkaUtils
from unify_api.modules.zhiwei_u.dao.install_sheet_dao import \
    data_warn_record_by_state, data_order_record_by_state

import logging

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s - %(name)s - %(filename)s - %(process)d_%(thread)d "
           "- line:%(lineno)s - %(levelname)s - %(message)s",
)
logger = logging.getLogger()

topic = "power_iot.push.wechat_task_statistic"


async def do_job():
    # 1. 报警记录中存在未处理记录（未转工单、未忽略）
    warn_record_list = await data_warn_record_by_state(state=0)
    if warn_record_list:
        tmp_dic = {
            "time": pendulum.now().to_datetime_string(),
            "belonging": "清科优能运维中心",
            "content": f"仍有{len(warn_record_list)}条报警待处理，请及时关注"
        }
        logger.info(f"send to kafka {tmp_dic}")
        await KafkaUtils.send_msg(topic=topic, dic_data=tmp_dic)
    # 2. 工单池中存在待接单状态工单。
    order_record_list = await data_order_record_by_state(state=1)
    if order_record_list:
        tmp_dic = {
            "time": pendulum.now().to_datetime_string(),
            "belonging": "清科优能运维中心",
            "content": f"仍有{len(order_record_list)}条工单待接单，请及时处理"
        }
        logger.info(f"send to kafka {tmp_dic}")
        await KafkaUtils.send_msg(topic=topic, dic_data=tmp_dic)


schedule = schedule.Scheduler()
schedule.every().monday.at("09:00").do(do_job)
schedule.every().tuesday.at("09:00").do(do_job)
schedule.every().wednesday.at("09:00").do(do_job)
schedule.every().thursday.at("09:00").do(do_job)
schedule.every().friday.at("09:00").do(do_job)

schedule.every().monday.at("14:00").do(do_job)
schedule.every().tuesday.at("14:00").do(do_job)
schedule.every().wednesday.at("14:00").do(do_job)
schedule.every().thursday.at("14:00").do(do_job)
schedule.every().friday.at("14:00").do(do_job)

schedule.every().monday.at("18:00").do(do_job)
schedule.every().tuesday.at("18:00").do(do_job)
schedule.every().wednesday.at("18:00").do(do_job)
schedule.every().thursday.at("18:00").do(do_job)
schedule.every().friday.at("18:00").do(do_job)

schedule.every().saturday.at("12:00").do(do_job)
schedule.every().sunday.at("12:00").do(do_job)

if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    while True:
        loop.run_until_complete(schedule.run_pending())
        time.sleep(1)
