import time

from django.db import transaction

from common.utils.exceptions import ValidationError
from console.electrical_info.models import ElectricalInfromation
from console.electrical_info.repositories import electrical_info_repo

from console.powerstation.models import Outline
from console.powerstation.models import PowerStation



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


    def get_electrical_info(self, enterprise_ids, **kwargs):
        return electrical_info_repo.get_electrical_info_sql(enterprise_ids, **kwargs)

    def create_electrical_info(self, data):
        ele_info_l = []
        for i in data:
            powerstation_id = i.pop("powerstation", None)
            powerstation = PowerStation.objects.filter(id=powerstation_id).first()
            if powerstation:
                i.update({
                    "electricity_user_id": powerstation.electricity_user.id,
                    "customer_id": powerstation.customer.id,
                    "powerstation_id": powerstation_id,
                })
            ele_info = ElectricalInfromation.objects.create(**i)
            ele_info_l.append(ele_info.to_dict())
        return ele_info_l


def create_outline(items):
    obj_list = []
    for item in items:
        obj_list.append(
            Outline(power_number=item.get("id"),
                    name="{}-1".format(item.get("meter_number"))))
    Outline.objects.bulk_create(obj_list)


electrical_info_service = ElectricalInfromationService()
