# coding=utf-8
import os
import sys
import time
import logging
import django
import schedule
from datetime import datetime, timedelta
local_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
if local_path not in sys.path:
    sys.path.append(local_path)
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "kedong.settings")
django.setup()
from smartfarming.api.views.forecast.all_dict import insect_dict
from smartfarming.models.pest_count import MongoCBDPestWarning
from smartfarming.models.worm_forecast import MongoCBDphoto
from smartfarming.models.sim_card import MongoMsg_Conf
from django.conf import settings

logger = logging.getLogger("other")


def product_cbd_alarm():
    # 获取所有的预警配置
    msg_conf = MongoMsg_Conf.objects.all()
    for msg in msg_conf:
        # 获取device_id  conf
        device_id = msg.device_id
        conf = eval(msg.conf)
        # 获取该device_id 下前一天的害虫情况
        now = datetime.now()
        now_stamp = int(time.time())
        previous_day = now - timedelta(days=1)
        start_time = datetime(
            previous_day.year, previous_day.month, previous_day.day, 0, 0, 0).timestamp()
        end_time = datetime(now.year, now.month, now.day,
                            23, 59, 59).timestamp()
        photo_data = MongoCBDphoto.objects.filter(
            addtime__range=[start_time, end_time]).values_list("indentify_result", flat=True)
        # 把当天的害虫统计出来
        indentify_result = {}
        for p in photo_data:
            tmp = p.split("#")
            for tp in tmp:
                k = tp.split(",")
                if k[0] in indentify_result.keys():
                    indentify_result[k[0]] += int(k[1])
                else:
                    indentify_result[k[0]] = int(k[1])

        # 定义预警变量
        warning_result = ""
        # 指定害虫数量预警
        appointPest = conf.get("appointPest")
        if appointPest == "on":
            appointPestName = conf.get("appointPestName")
            appointPestNum = conf.get("appointPestNum")
            pest_cg = appointPestName.split("#")
            pest_nu = appointPestNum.split("#")
            for i in pest_cg:
                if i in indentify_result.keys():
                    if indentify_result[i] > int(pest_nu[pest_cg.index(i)]):
                        zh = insect_dict.get(i, "未知")
                        warning_result += f"害虫{zh}数量{str(indentify_result[i])},"
            # 写入数据库
            if warning_result:
                alarm_obj = MongoCBDPestWarning.objects.create(
                    device_id=device_id,
                    warning_content=f"{warning_result}请注意防范",
                    warning_types="2",
                    upltime=now_stamp
                )
                logger.warning(f"指定害虫数量预警: {alarm_obj.id}")

        # 害虫种类
        pestCategory = conf.get("pestCategory")
        if pestCategory == "on":
            pestCategoryNum = conf.get("pestCategoryNum")
            pest_cg_count = len(indentify_result.keys())
            if pest_cg_count > int(pestCategoryNum):
                # 写入数据库
                alarm_obj = MongoCBDPestWarning.objects.create(
                    device_id=device_id,
                    warning_content=f"害虫种类{pest_cg_count},请注意防范",
                    warning_types="1",
                    upltime=now_stamp
                )
                logger.warning(f"害虫种类: {alarm_obj.id}")

        # 害虫总数
        pestTotal = conf.get("pestTotal")
        if pestTotal == "on":
            pestTotalNum = conf.get("pestTotalNum")
            ct = 0
            for m, n in indentify_result.items():
                ct += int(n)
            if ct > int(pestTotalNum):
                # 写入数据库
                alarm_obj = MongoCBDPestWarning.objects.create(
                    device_id=device_id,
                    warning_content=f"害虫总数{str(ct)},请注意防范",
                    warning_types="3",
                    upltime=now_stamp
                )
                logger.warning(f"害虫总数: {alarm_obj.id}")

        # 综合预警
        total_warning = ""
        pestWarn = conf.get("pestWarn")
        if pestWarn == "on":
            for m, n in indentify_result.items():
                total_warning += f"害虫{insect_dict.get(m)},数量{str(n)};"
            # 写入数据库
            if total_warning.replace(" ", ""):
                alarm_obj = MongoCBDPestWarning.objects.create(
                    device_id=device_id,
                    warning_content=f"{total_warning}请注意防范!",
                    warning_types="4",
                    upltime=now_stamp
                )
                logger.warning(f"综合预警: {alarm_obj.id}")


# 每天的8点执行任务
schedule.every().day.at("05:00").do(product_cbd_alarm)

while True:
    schedule.run_pending()
    time.sleep(1)
