import time

from django.db import transaction

from common.utils.exceptions import ValidationError
from .models import PowerStation, Outline
from ..electrical_info.models import ElectricalInfromation
from console.powerstation.repositories import powerstation_repo


class powerstationService(object):
    @transaction.atomic()
    def delete_powerstation(self, pk_list):
        PowerStation.objects.filter(id__in=pk_list).update(
            deleted=True,
            deleted_time=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))

    def bind_elecrical_info(self, request_data, serializer_data):
        if "elecrical_info_list" not in request_data:
            raise ValidationError("没有创建电源编号")
        if "outline_list" not in request_data:
            raise ValidationError("没有创建出线侧设备")
        powerstation = PowerStation.objects.filter(
            id=serializer_data['id']).first()
        elecrical_info_list = request_data['elecrical_info_list']
        for elecrical_info in elecrical_info_list:
            try:
                ElectricalInfromation.objects.filter(
                    deleted=False, id=elecrical_info).update(
                    powerstation_id=serializer_data['id'])
            except Exception as e:
                raise ValidationError(e)
        outline_list = request_data['outline_list']
        for outline in outline_list:
            Outline.objects.filter(
                deleted=False,
                id=outline).update(powerstation_id=serializer_data['id'])

        return powerstation

    @transaction.atomic()
    def delete_outline(self, pk):
        Outline.objects.filter(id__in=pk).update(deleted=True,
                                                 powerstation=None,
                                                 deleted_time=time.strftime(
                                                     "%Y-%m-%d %H:%M:%S",
                                                     time.localtime()))

    def update_ele_info(self, data):
        for item in data.get("electricalinfromation_set"):
            ElectricalInfromation.objects.filter(id=item.get("id")).update(**{
                "electricity_user_id": data.get("electricity_user").get("id"),
                "customer_id": data.get("customer").get("id")
            })

    def get_monitor_points(self, station_id):
        return powerstation_repo.get_monitor_points(station_id)


powerstation_service = powerstationService()
