from apps.utils.viewsets import GenericViewSet
from rest_framework.decorators import action
from apps.em.models import Equipment
from apps.wpm.models import Mlog, Handover
from apps.mtm.models import Mgroup
from django.utils import timezone
from django.db.models import Sum
from datetime import datetime, timedelta
from rest_framework.response import Response
from rest_framework.serializers import Serializer
from apps.inm.models import MIOItem, MIO
from rest_framework.exceptions import ParseError

def tran_time_to_mstate(mstate_json, reminder_interval_list, work_start_time: datetime, now: datetime):
    if len(reminder_interval_list) != len(mstate_json):
        return '未运行'
    xval = 0
    for ind, val in enumerate(reminder_interval_list):
        xval += val
        if work_start_time + timedelta(minutes=xval) > now:
            return mstate_json[ind]['name']
    return '运行'

class AnaViewSet(GenericViewSet):
    perms_map = {}
    @action(methods=['post'], detail=False, perms_map={'post': '*'}, serializer_class=Serializer)
    def equip_last_mlog(self, request):
        """设备最后生产日志

        设备最后生产日志
        """
        data = request.data
        now = timezone.now()
        try:
            mgroup: Mgroup = Mgroup.objects.get(id=data['mgroup'])
        except Mgroup.DoesNotExist:
            raise ParseError("该工段不存在,请传入工段ID")
        # 子状态
        mstate_json = mgroup.process.mstate_json if mgroup.process.mstate_json else []
        # 生产设备
        equip_qs = Equipment.objects.filter(mgroup=mgroup, type = 10)
        equip_qs_v = equip_qs.values('id', 'name', 'number', 'state').order_by('number')
        equip_qs_l = list(equip_qs_v)
        # 设备最后生产日志
        mlog_qs_0 = Mlog.objects.filter(equipment__in=equip_qs, mgroup=mgroup)
        mlog_qs = mlog_qs_0.exclude(work_end_time__lt=now)
        mlog_qs = mlog_qs.annotate(t_count_use=Sum('b_mlog__count_use'))
        mlog_qs = mlog_qs.order_by('work_start_time')
        mlog_qs_v = mlog_qs.values('id', 'equipment__id', 't_count_use', 'reminder_interval_list', 'work_start_time', 'work_end_time')
        mlog_qs_l = list(mlog_qs_v)
        mlog_dict = {item['equipment__id']: item for item in mlog_qs_l}

        # 统计数据
        保温 = 0
        冷却 = 0
        未运行 = 0
        故障 = 0
        运行 = 0
        now = timezone.now()
        for item in equip_qs_l:
            item['mstate'] = '未运行'
            if item['id'] in mlog_dict:
                mlog_dict_v = mlog_dict[item['id']]
                item['t_count_use'] = mlog_dict_v['t_count_use']
                item['reminder_interval_list'] = mlog_dict_v['reminder_interval_list']
                item['work_start_time'] = timezone.localtime(mlog_dict_v['work_start_time']).strftime('%Y-%m-%d %H:%M:%S') if mlog_dict_v['work_start_time'] else None
                item['work_end_time'] = timezone.localtime(mlog_dict_v['work_end_time']).strftime('%Y-%m-%d %H:%M:%S') if mlog_dict_v['work_end_time'] else None
                item['mstate'] = tran_time_to_mstate(mstate_json, mlog_dict_v['reminder_interval_list'], mlog_dict_v['work_start_time'], now)
                
            if item['state'] in [Equipment.EQUIP_STATE_SCRAP, Equipment.EQUIP_STATE_FIX]:
                item['mstate'] = '故障'
            
            if item['mstate'] == '保温':
                保温 += 1
            elif item['mstate'] == '冷却':
                冷却 += 1
            elif item['mstate'] == '运行':
                运行 += 1
            elif item['mstate'] == '未运行':
                未运行 += 1
            elif item['mstate'] == '故障':
                故障 += 1
        ret = {"保温": 保温, "冷却": 冷却, "未运行": 未运行, "故障": 故障, "运行": 运行}
        ret['mstate_json'] = mstate_json
        ret['now'] = timezone.localtime(now).strftime('%Y-%m-%d %H:%M:%S')
        ret["rows"] = equip_qs_l
        return Response(ret)
    
    @action(methods=['post'], detail=False, perms_map={'post': '*'}, serializer_class=Serializer)
    def put_prod(self, request):
        """
        投产分析
        """
        now = timezone.now()
        now_2 = now.replace(hour=2, minute=0, second=0, microsecond=0)
        mgroup: Mgroup = Mgroup.objects.get(name='退火')
        # 子状态
        mstate_json = mgroup.process.mstate_json
        ret = {}
        ret['今日退火投产预测'] = 0
        ret['明日退火投产预测'] = 0
        ret['rows'] = {}
        # 生产记录/今日退火投产预测
        # 昨日2点
        now_2_yesterday = now_2 - timedelta(days=1)

        mlog_qs_0 = Mlog.objects.filter(mgroup=mgroup)
        mlog_qs = mlog_qs_0.exclude(work_end_time__lt=now_2_yesterday).annotate(t_count_use=Sum('b_mlog__count_use')).order_by('work_start_time')
        mlog_qs_v = mlog_qs.values('id', 'equipment__id', 't_count_use', 'reminder_interval_list', 'work_start_time', 'work_end_time')
        mlog_qs_l = list(mlog_qs_v)

        for item in mlog_qs_l:
            if tran_time_to_mstate(mstate_json, item['reminder_interval_list'], item['work_start_time'], now) == '冷却':
                if item['work_end_time'] is None or item['work_end_time'] > now_2:
                    ret['明日退火投产预测'] += item['t_count_use']
                ret['今日退火投产预测'] += item['t_count_use']
        
        return Response(ret)