from .models import Equipment
from apps.system.models import Dept
from apps.mtm.models import Mgroup
import datetime
from django.conf import settings
from dateutil import tz
from django.core.cache import cache
from apps.utils.tasks import ctask_run
import logging
from apps.mtm.services import mgroup_run_change
import random
import time

myLogger = logging.getLogger("log")
baseTime = datetime.datetime(year=1990, month=4, day=4, hour=0, minute=0, second=0, tzinfo=tz.gettz(settings.TIME_ZONE))

def get_eq_rs(equipId: str):
    """获取设备运行状态缓存
    """
    return cache.get(f"equipment_{equipId}", {"update_time":baseTime, "running_state": Equipment.OFFLINE, "running_state_timex": baseTime})

def set_eq_rs(equipId, last_timex: datetime, last_mrs: int):
    """更新设备运行状态(包括缓存和数据库)
    """
    if last_mrs == Equipment.OFFLINE: # 如果是离线直接更新
        cache.set(f"equipment_{equipId}", {"running_state": last_mrs, "running_state_timex": last_timex, "update_time":baseTime}) # 更新缓存
        Equipment.objects.filter(id=equipId).update(running_state=last_mrs)  # 更新数据库
    else:
        eq_rs_cache = get_eq_rs(equipId)
        eq_rs_change = False
        ten_minutes = datetime.timedelta(minutes=10)
        now = datetime.datetime.now()
        mgroup_sort_trigger = False
        if eq_rs_cache["running_state"] != last_mrs:  # 如果状态变动了要调用方法否则只需更新缓存
            eq_rs_change = True
            update_time = now
        elif now > eq_rs_cache.get('update_time', baseTime) + ten_minutes:  # 如果当前时间大于缓存时间10分钟则更新
            eq_rs_change = True
            update_time = now
            mgroup_sort_trigger = True
        else:
            update_time = eq_rs_cache.get('update_time', baseTime)
        cache.set(f"equipment_{equipId}", {"running_state": last_mrs, "running_state_timex": last_timex, "update_time":update_time}, timeout=None) # 更新缓存
        if eq_rs_change:
            ctask_run.delay("apps.em.services.shutdown_or_startup", equipId, last_timex, last_mrs, '', mgroup_sort_trigger)


def shutdown_or_startup(equipId: str, last_timex: datetime, last_mrs, note: str = "", mgroup_sort_trigger: bool = False):
    """
    last_mrs 设备运行状态值
    """
    # try:
    #     equip = Equipment.objects.get(id=equipId)
    # except Equipment.DoesNotExist:
    #     myLogger.error(f"设备{equipId}不存在")
    #     return
    equip =Equipment.objects.get_queryset(all=True).get(id=equipId)
    if equip.is_deleted:
        equip.is_deleted = False
        equip.save()
    equip.running_state = last_mrs
    equip.save(update_fields=["running_state"])

    # 设备运行状态决定工段运行状态
    mgroup: Mgroup = equip.mgroup
    indicate = equip.indicate_mgroup_running
    new_run = None
    
    if mgroup and indicate:
        if last_mrs in [Equipment.STOP, Equipment.FAILURE, Equipment.STANDBY]:  # 设备停止信号
            if indicate in [Equipment.IM_DANDAN, Equipment.IM_DOUDAN]:
                new_run = False
                note += f'{equip.number}-{equip.name}停止-'
            else:
                if not Equipment.objects.filter(mgroup=mgroup, indicate_mgroup_running=indicate, running_state=Equipment.RUNING).exists():
                    new_run = False
                    note += f'{equip.number}-{equip.name}停止-'
        elif last_mrs == Equipment.RUNING:  # 设备启动信号
            if indicate in [Equipment.IM_DANDAN, Equipment.IM_DANDOU]:
                new_run = True
            else:
                if not Equipment.objects.filter(mgroup=mgroup, indicate_mgroup_running=indicate, running_state__in=[Equipment.STOP, Equipment.FAILURE, Equipment.STANDBY]).exists():
                    new_run = True
                    
        if new_run is not None:
            if mgroup_sort_trigger:
                time.sleep(mgroup.sort)
            mgroup_run_change(mgroup, new_run, last_timex, note)


def daoru_equipment(path: str):
    from apps.utils.snowflake import idWorker
    from openpyxl import load_workbook

    wb = load_workbook(path)
    sheet = wb["em_equipment"]
    i = 2
    while sheet[f"a{i}"].value:
        name = sheet[f"a{i}"].value
        number = sheet[f"b{i}"].value
        model = sheet[f"c{i}"].value
        parameter = sheet[f"d{i}"].value
        place = sheet[f"e{i}"].value
        power_kw = sheet[f"f{i}"].value
        belong_dept_name = sheet[f"g{i}"].value
        mgroup_name = sheet[f"h{i}"].value
        Equipment.objects.get_or_create(
            number=number,
            defaults={
                "id": idWorker.get_id(),
                "name": name,
                "model": model,
                "parameter": parameter,
                "place": place,
                "power_kw": power_kw,
                "belong_dept": Dept.objects.get(name=belong_dept_name) if belong_dept_name else None,
                "mgroup": Mgroup.objects.get(name=mgroup_name) if mgroup_name else None,
            },
        )
        i = i + 1
