# Create your tasks here
from __future__ import absolute_import, unicode_literals
from datetime import timedelta
from apps.utils.tasks import CustomTask
from django.utils import timezone
from celery import shared_task
from .models import DrainEquip, EnvData
from apps.em.models import Equipment
import random


@shared_task(base=CustomTask)
def generate_envdata():
    """生成模拟数据"""
    now = timezone.now().replace(microsecond=0)
    eIds = DrainEquip.objects.values_list("equipment__id", flat=True)
    equips = (Equipment.objects.filter(id__in=eIds) | Equipment.objects.filter(cate__code="aqms")).distinct()
    save_list = []
    for equip in equips:
        default_dict = {"equipment": equip, "timex": now, "running_state": 10}
        equip.running_state = 10
        equip.save(update_fields=["running_state"])
        if equip.cate and equip.cate.code in ["cems", "aqms", "tsp"]:
            if equip.cate.code == "cems":
                dust_rtd = random.uniform(0.1, 0.3)
                default_dict["dust_rtd"] = dust_rtd
                default_dict["dust_zs"] = dust_rtd
                so2_rtd = random.uniform(0.1, 2)
                default_dict["so2_rtd"] = so2_rtd
                default_dict["so2_zs"] = so2_rtd
                nox_rtd = random.uniform(0.1, 2)
                default_dict["nox_rtd"] = nox_rtd
                default_dict["nox_zs"] = nox_rtd
                default_dict["temperature"] = random.uniform(12, 30)
                default_dict["pressure"] = random.uniform(-0.06, 0.1)
                default_dict["speed"] = random.uniform(8, 13)
                default_dict["humidity"] = random.uniform(1, 1.2)
                default_dict["flux"] = random.uniform(2000, 3000)
            elif equip.cate.code == "tsp":
                default_dict["tsp"] = random.uniform(0.01, 0.04)
                default_dict["temperature"] = random.uniform(12, 30)
                default_dict["humidity"] = random.uniform(30, 40)
            elif equip.cate.code == "aqms":
                default_dict["pm25"] = random.uniform(8, 12)
                default_dict["pm10"] = random.uniform(26, 35)
                default_dict["temperature"] = random.uniform(12, 30)
                default_dict["humidity"] = random.uniform(30, 40)
                default_dict["wind_speed"] = random.uniform(0.1, 1)
                default_dict["wind_direction"] = 1
        save_list.append(EnvData(**default_dict))
    EnvData.objects.bulk_create(save_list)


@shared_task(base=CustomTask)
def cal_envdata():
    """
    计算监测达标率等值
    """
    pass
